From a75210c6cdcab35ffb4f9cdac7aa01469e21b72c Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 21:08:04 +0900 Subject: [PATCH 01/34] fix(collab,sync): journal-fenced CRDT, multi-hunk diff3, and 8-peer exit safety --- CHANGELOG.md | 40 + architecture/cli-sync.md | 8 +- architecture/overview.md | 4 +- architecture/webapp-frontend.md | 19 +- architecture/webapp-server.md | 24 +- cmd/bdrive/desktop.go | 1 + internal/syncer/merge.go | 18 + internal/syncer/merge_contentproof_test.go | 168 ++ internal/syncer/merge_test.go | 9 +- internal/syncer/syncer.go | 40 +- internal/textmerge/merge.go | 558 +++++- internal/textmerge/merge_test.go | 53 + internal/webapp/collab_relay.go | 22 +- .../frontend/e2e/concurrent-edit.spec.ts | 11 +- .../webapp/frontend/e2e/solo-handoff.spec.ts | 138 +- internal/webapp/frontend/src/api/http.ts | 44 +- internal/webapp/frontend/src/apps/Browser.tsx | 32 +- .../webapp/frontend/src/components/Editor.tsx | 58 +- .../frontend/src/components/FileView.tsx | 21 + .../frontend/src/components/VisualEdit.tsx | 129 +- internal/webapp/frontend/src/lib/collab.ts | 107 +- internal/webapp/frontend/src/lib/merge3.ts | 376 ++++ .../webapp/frontend/src/lib/sharedfile.ts | 1395 +++++++++++---- .../src/lib/sharedfile_restore.test.ts | 1549 +++++++++++++++++ internal/webapp/mcp.go | 62 +- internal/webapp/server.go | 3 + ...{Editor-m3pwH2dA.js => Editor-CUvVSG63.js} | 38 +- .../static/assets/VisualEdit-CwChUaNM.js | 1 + .../static/assets/VisualEdit-DpNpdB4J.js | 1 - .../webapp/static/assets/index-BD48v6-0.js | 131 ++ .../webapp/static/assets/index-Bnuge9vv.js | 131 -- .../static/assets/sharedfile-DXV-dXg-.js | 16 + .../static/assets/sharedfile-nk3qnjVG.js | 6 - internal/webapp/static/index.html | 2 +- internal/webapp/upload.go | 287 ++- internal/webapp/upload_landed_test.go | 149 ++ internal/webapp/ycollab.go | 1261 ++++++++++++-- internal/webapp/ycollab_sync_test.go | 1427 +++++++++++++++ 38 files changed, 7467 insertions(+), 872 deletions(-) create mode 100644 internal/syncer/merge_contentproof_test.go create mode 100644 internal/webapp/frontend/src/lib/merge3.ts create mode 100644 internal/webapp/frontend/src/lib/sharedfile_restore.test.ts rename internal/webapp/static/assets/{Editor-m3pwH2dA.js => Editor-CUvVSG63.js} (72%) create mode 100644 internal/webapp/static/assets/VisualEdit-CwChUaNM.js delete mode 100644 internal/webapp/static/assets/VisualEdit-DpNpdB4J.js create mode 100644 internal/webapp/static/assets/index-BD48v6-0.js delete mode 100644 internal/webapp/static/assets/index-Bnuge9vv.js create mode 100644 internal/webapp/static/assets/sharedfile-DXV-dXg-.js delete mode 100644 internal/webapp/static/assets/sharedfile-nk3qnjVG.js create mode 100644 internal/webapp/upload_landed_test.go create mode 100644 internal/webapp/ycollab_sync_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e76e212..e64259ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,46 @@ Notable changes per release. Format loosely follows minor versions may ship breaking changes (see [SemVer §4](https://semver.org/#spec-item-4)). ## Unreleased +## v0.18.10 — 2026-11-11 + +**Update your devices and self-hosted hubs** for the co-editing and merge +fixes; running daemons switch over the first time the updated `bdrive` runs. +Client wire and local volume on-disk formats remain backward-compatible, and +v0.18.10 hubs read the bare-sha `ydoc/head/` records older hubs wrote. +**Upgrade every hub process that shares a storage root together:** v0.18.10 +hubs write `ydoc/head/` as JSON (`{sha, win}`), which a v0.18.9 or +earlier hub process cannot read. During a mixed-version rollout or a rollback, +that older process skips the newest stored room state and falls back to the +per-blob CRDT history (`ydoc/`) or, when none matches, to fresh file +bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. + +- **Co-editing rooms seed from the newest stored state across hub processes.** `ydoc/head/` now stores `{sha, win}`, where `win` is the `winKey` of the journal op that produced the stored room state. A head write with an older `win` is refused, so an older fold in any process can no longer move the head backwards, and a room whose file no longer matches the head seeds from the file. `knows()` merges the other state into a scratch copy and checks whether anything changed, so stored histories that contain deletions compare correctly. Empty rooms stay loaded for 2 minutes (`collabRoomIdleTimeout`), and the Redis relay keeps 30 minutes of updates (`StreamRetention`, up from ygo's 60-second default); a failed snapshot republishes the room's full state into that window and retries. +- **Outside writes merge into live rooms without losing concurrent typing.** `moveDocLive` computes the change on a private copy of one atomic room snapshot and applies only the resulting CRDT item delta, so keystrokes that arrive during the merge stay in place instead of shifting by stale character offsets. +- **`POST /api/p//ycollab/sync` merges browser edits into a room over HTTP.** A browser without a connected socket sends its Yjs state, or its text with the base it started from; `peek` reads the room without writing. The hub answers `ok` only after storage holds the edit, waiting up to 8 seconds (`ycollabSyncDurableWait`), including for the lease holder in another process; otherwise it returns `503` and the browser keeps its edits. +- **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict. +- **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. +- **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves before leaving (waiting up to 1.5 seconds, and staying only for an open shrink question). `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. + +## v0.18.9 — 2026-11-11 + +**Update self-hosted hubs** for faster history and cold starts on large +projects; **update your devices** to keep verified blobs across offline +cycles. Storage formats are unchanged. + +- **Incremental history and fold checkpoint tails.** `restoreFoldCheckpoint`, `tryIncrementalFold` and the history index apply only appended journal tails, so a checkpoint is no longer discarded when a journal has grown and a live file with historical delete tombstones (such as `log.md`) no longer forces a rebuild. (#354) +- **Version-pinned range reads for journal tails.** `VersionedRangeGetter` / `GetVersionedRange` (GCS, forwarded through `remote.Prefixed`) read only the appended tail of a peer journal once its prefix digest is verified for that object generation. (#354) +- **Blob existence cache.** `RemoteSource` caches positive `blobs/` and `chunks/` existence checks after folder-visibility checks, and the daemon keeps its `httpBackend` across transient offline cycles, clearing verified blobs on a `404` or a journal-list reset. (#354) + +## v0.18.8 — 2026-11-10 + +**Update self-hosted hubs** for the fold checkpoint, history and live tree +changes; **update your devices** for faster push retries. Storage formats are +unchanged. + +- **Push retries skip blobs the hub already confirmed.** The `https://` backend remembers blobs and chunks confirmed by `Exists` or `Put` during a session (bounded FIFO), so a retry after a partial failure skips `/store/sign` and `/store/exists` for them and `Session.push` does not reopen their local files. (#351) +- **Derived fold checkpoint, pre-sorted history and hub hot-path caches.** The hub persists a fold checkpoint (`hub-cache/fold-v1.bin.gz`: live winners, delete tombstones, move history) so a cold instance restores a large project without re-parsing every journal; journal hashes are verified on restore. `histIndex` keeps a time-ordered permutation and `handleHistory` stops once the page is full, instead of sorting every op per request. `handleStoreSign` checks blob existence before quota reservation, so an org at its storage limit can still reference blobs already stored. Journal append and tail prefixes, unsealed blob generations, restricted tree responses and visible blob sets are cached. (#352) +- **Open tabs patch the file tree from change events.** Small SSE `change` frames (up to 16 paths) carry permission-filtered file metadata, so open tabs update their tree and since-visit caches without refetching `/tree` or `/history`; a reader with hidden paths falls back to a filtered refetch. The ambient history query runs only on Home, the 30- and 60-second `/comments` polls are gone, and a tab promoted to stream leader resyncs at once. (#353) + ## v0.18.7 — 2026-11-10 **Update your devices** to reclaim superseded local blobs and skip redundant diff --git a/architecture/cli-sync.md b/architecture/cli-sync.md index 552676b5..21e808c5 100644 --- a/architecture/cli-sync.md +++ b/architecture/cli-sync.md @@ -235,12 +235,18 @@ classDiagram +tryMerge(path, mine, theirs, all) blob, ok +mergeText(base, a, b) out, ok via textmerge +commonAncestor(path, mine, theirs, all) + +latestPut(path, blob, lists) op, ok -maxMergeBytes 4 MiB, UTF-8 only } + note for merge "conflictCopiesWithState merges the losing op against the op that WON (latestPut: the greatest put holding the blob replay resolved to), fetching that blob first when it is not local. Lineage is never guessed from Base links. When the merge yields exactly the winner's bytes (merged blob == cur.Blob), the winner already holds both sides: another device or the hub merged first, so the cycle fast-forwards and writes no op. A real merge is journaled with Op.Base = the winning blob." class textmerge { <> +Merge(base, a, b) out, ok + +DiffHunks(old, new) []CharHunk + +RetainsChanges(base, candidate, head) bool + +IsText(b) bool } + note for textmerge "Each side is diffed against the base with a Myers O(ND) line diff, so a side that touched several places yields several small hunks. Non-overlapping hunks apply independently (diff3). Overlaps resolve only for an identical edit, same-point insertions (ordered by content, never argument position), and one line both sides edited in different words (a token-level merge3). Everything else stays a conflict. DiffHunks gives minimal UTF-16 splices for a CRDT; RetainsChanges proves a later head still carries an earlier edit." class daemon { +Run(folder, scan, remote) @@ -272,7 +278,7 @@ classDiagram note for localFolderWatcher "The watcher accumulates bounded per-mount events, coalesces paths, prunes reserved/nested/ignored directories, and evaluates echo suppression outside pendingMu without loading the state cache when no pre-fence events are pending. Child ENOENT during recursive setup triggers candidate rebuild (releasing the prior watcher first on EMFILE/ENFILE/ENOSPC) and full-scan fallback when roots still exist; ENOSPC watcher exhaustion is retried with 1m/2m/5m/10m backoff and duplicate errors are logged once. Missing roots, closed channels, overflow and other backend errors remain fatal." volumeWorker --> ScanHint : routes per-mount event batches ScanHint ..> localFolderWatcher : batch source - note for Session "Concurrent edits to different parts of one text file MERGE now instead of forking. conflictCopies tries a three-way merge first (merge.go): the common ancestor is the greatest op for that path ordered before BOTH sides, which the journal already holds. It declines far more than it resolves — no ancestor, non-UTF-8 or NUL, over 4 MiB, an unreadable blob, or edits touching the same lines all fall through to exactly the conflict copy that existed before, because a machine guessing between two rewrites of one sentence is how people lose work quietly. Only NON-overlapping regions are ever taken, which makes merge(base,a,b) equal merge(base,b,a) — the property that lets two devices each observe the same concurrency and merge independently without pushing different blobs. Result.Merged is counted apart from Result.Conflicts: a merge is work the machine finished, a conflict is work it handed back. An EMPTY version never forks and never keeps a path: an empty loser is not preserved at all, and content that lost to an empty winner is put back at the real path (keptOverEmptyNote, counted as Merged) — a truncated save or a failed read written back is almost never an edit anyone meant, and a copy beside an empty file leaves the reader the empty one" + note for Session "Concurrent edits to different parts of one text file MERGE now instead of forking. conflictCopies tries a three-way merge first (merge.go): the common ancestor is the greatest op for that path ordered before BOTH sides, which the journal already holds. It declines far more than it resolves — no ancestor, non-UTF-8 or NUL, over 4 MiB, an unreadable blob, or two different rewrites of the same words all fall through to exactly the conflict copy that existed before, because a machine guessing between two rewrites of one sentence is how people lose work quietly. Only non-overlapping hunks (or, within one line, non-overlapping words) are ever taken, and every tie is broken by content, which makes merge(base,a,b) equal merge(base,b,a) — the property that lets two devices each observe the same concurrency and merge independently without pushing different blobs. Result.Merged is counted apart from Result.Conflicts: a merge is work the machine finished, a conflict is work it handed back. An EMPTY version never forks and never keeps a path: an empty loser is not preserved at all, and content that lost to an empty winner is put back at the real path (keptOverEmptyNote, counted as Merged) — a truncated save or a failed read written back is almost never an edit anyone meant, and a copy beside an empty file leaves the reader the empty one" note for volumeWorker "remote.Watcher wakes a remote cycle when a peer pushes, reducing arrival latency from about 10s to 1s. A live stream stretches polling to remoteInterval x watchedPollFactor (5m by default); losing it restores remoteInterval on the next tick. Token changes and offline cycles drop the stream. Failed or ended dials back off for watchRetry (1m), including an older hub's 404. Periodic polling still bounds silent stream failure." class pulledVouch { diff --git a/architecture/overview.md b/architecture/overview.md index 015c216c..e0cbaaa8 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -36,7 +36,7 @@ flowchart LR store["object store (hub-owned)
internal/remote: file:// s3:// gs://
blobs + per-device journals"] - tm["internal/textmerge
line-level three-way merge,
non-overlapping regions only"] + tm["internal/textmerge
Myers multi-hunk diff3 merge + intra-line token merge
Merge, DiffHunks, RetainsChanges, IsText"] tpl["internal/templates
go:embed'ed starting structures
(docs, wiki, para, skills: skeleton + AGENTS.md)"] @@ -58,7 +58,7 @@ flowchart LR srv -->|"share mint: refuse · markdown render: badge"| sec cli -->|"init --template: seed locally"| tpl eng -->|"concurrent edits from two devices"| tm - srv -->|"an outside write under a co-editing room"| tm + srv -->|"co-editing room reconciliation, conditional
upload/content, MCP write / edit on a stale sha"| tm srv -->|"POST /api/projects template:
seed as ops under the hub's device"| tpl fe -->|/api/config, /api/projects, viewer APIs| srv cloud -.->|imports OSS packages,
replaces providers| srv diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index 1a526f19..cc8094a9 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -59,6 +59,7 @@ classDiagram +scroll restoration: contentRef, memo, goal from lib/scroll +fullscreen: body.full-view from route.full, Exit / Esc / Back +readWidth: dragged reading width, tab memory only + +Done: awaits editFlushRef (saveNow, 1.5s cap) before leaving the editor } note for Browser "readWidth is the reading column's width as the reader drags it (components/WidthHandle.tsx), held in Browser's state and nowhere else: it follows the reader across files and in and out of fullscreen because Browser outlives both, and a reload or a new tab is the reset — no storage, by design. It reaches the DOM as ONE variable, --page-read on the .page element, so the file rail's placement arithmetic follows without its own rule. During a drag the handle writes that variable straight onto the element and commits to state only on release, so the file page is not re-rendered on every pointer move" note for Browser "Fullscreen is a QUERY PARAM on the file route (?full=1), for the reason ?v= is one: the first segment after the project id is reserved for view names, and a fullscreen file is the same page with different chrome. Two things the code forced: routeKey is withoutFull(useLocationPath()), because a ?full=1 push otherwise looks like a fresh route and arms a scroll goal of 0 — the reader is thrown to the top of the document the moment they ask for more of it; and the chrome is HIDDEN by a body class, never unmounted, so <article id=content> survives the toggle and keeps its scrollTop in both directions. display:none also takes the hidden controls out of the tab order and the accessibility tree together, which is what syncSidebarInert already encodes for the off-canvas sidebar. The Exit control is rendered by AppShell OUTSIDE the topbar it hides and painted over the content: the HTML sandbox is an opaque origin and the PDF viewer is the browser's own, so Esc can never reach the app from inside either one (BEA-195)" @@ -101,6 +102,7 @@ classDiagram class api { +getJSON / postJSON / api + +putText(..., keepalive) / syncCollab(url, req, keepalive) POST ycollab/sync +getResponse (raw bytes) +PRODUCT_EVENTS method+path → event +prefetchForURL(queryClient, url) @@ -109,6 +111,7 @@ classDiagram } note for api "api/prefetch.ts — main.tsx calls prefetchForURL before React mounts: the requests a URL alone determines (projects, orgs, tree, heat, and render + comments for a markdown read) start under the SAME query keys the hooks use, so a mounting hook joins the request in flight. Config is deliberately excluded (its queryFn owns the signed-out redirect), and a prefetch never navigates — a failure is cached as an error the hook refetches through getJSON. bootRequests.ts is the import-free URL→requests mapping, so the node test runner can pin it" note for api "api/http.ts — all URLs root-absolute so deep paths never break relative resolution. Every mutating call goes through api()/postJSON(), so one table there is the whole product-event surface: a new write is measured or it isn't, instead of depending on someone remembering a capture() call" + note for api "syncCollab posts a staging checkpoint, a shrink confirmation or a peek to POST {prefix}ycollab/sync. putText and syncCollab take keepalive for the tab-close flush; it is set only for bodies up to KEEPALIVE_MAX_BYTES (60,000 bytes), below the 64 KiB browsers allow for in-flight keepalive bodies, past which they reject the fetch. A larger body goes out as a regular fetch, which the browser may cancel during unload." class analytics { +initAnalytics(config) @@ -160,7 +163,9 @@ classDiagram note for components "FileView's HtmlView re-mounts its iframe on the change stream. An iframe loads once, so leaving the editor rendered the file as it was when Done was pressed — BEFORE the save landed — and then sat there with the edit saved on the hub and invisible on screen; the same reload makes a teammate's edit appear in a page you are already looking at. EditView's banner is raised by the MERGE VERDICT for the source editor and by the change stream only for the visual one: the verdict knows whether the write could be folded in and the event cannot, so raising a banner on the event would flash the wrong answer ahead of it. For that visual path `mine` is a COUNT, not a flag: the change stream announces a write as soon as the hub journals it, often before the PUT's own response, so openSharedFile reports a write BEFORE it goes out, and two saves in flight (routine — clicking between paragraphs saves each) left the second event with nothing to claim it and raised the peer banner on the user's own edit" note for lib "A save carries the version its buffer was read at (If-Match), and a 409 is not an error to retry — it means somebody else's write is already the file. By then merge() has necessarily declined, because a save only happens when this buffer has changes of its own, so there is nothing left to reconcile: the losing version is written BESIDE the file as .bdrive-conflict--, the same name the sync path has used since the beginning and the same one ConflictBanner already explains. conflictName is therefore a second implementation of a pure function that lives in Go (syncer.go) — round-tripped through parseConflict in the unit tests, because two formats for one filename would be two explanations for one reader." note for lib "sharedfile.merge is how an agent's write reaches a document somebody is typing in. The editor still never re-seeds itself from the server — that resets the buffer under a cursor — so the write arrives as textEdit's single splice instead: everything it does not change is untouched, and so is the caret sitting in it. It REFUSES in the two cases where a splice destroys something, and the refusal is FileView's banner: unsaved local edits (never overwrite half a sentence), and a co-editor in the room (both clients would compute the same splice, and two identical splices into one CRDT is the change applied twice). `saved` moves to the incoming text BEFORE the splice, or the document change it causes schedules a save that writes back what was just read. A relay-less surface has no Y.Text to splice, so it passes soloApply — without one merge reports blocked rather than claiming a change it could not make" - note for lib "Solo is one-way. A room that was never reached by UNREACHABLE_MS (or a single-volume server, which has no room route) makes CollabDoc.stop() end the provider BEFORE onSolo runs, and status reads solo from then on. A provider left retrying would merge the hub's document into a solo surface's seeded copy (the whole file twice), or flip hubHoldsIt under a solo CodeMirror that is not bound to the room, so its saves became no-ops. A room that was reached once is never given up on: a later drop is a reconnect" + note for lib "Solo is only for a server with no room route (a single volume); CollabDoc.stop() is called for nothing else. A room that is merely slow raises onStalled once after STALLED_MS (2.5s) and the provider keeps reconnecting; it used to be onUnavailable, which ended the transport after 8s, so a room that answered at 8.6s was never joined and the editor wrote its own copy against everyone else's. Until the socket syncs the surface is STAGING: nothing is written into the Y.Doc (a local copy merged with the hub's would hold every character twice), the buffer is checkpointed into the room as TEXT over POST ycollab/sync, and on sync it is merged three ways (merge3) into the shared document. A checkpoint that failed ambiguously is settled by a peek before the join, so typing is never applied twice" + note for lib "sharedfile.ts save() is single-flight: a second call joins the save in flight and marks the buffer dirty for one more pass. saveNow() flushes a live room (its state over ycollab/sync when no snapshot is known to carry it) and askingShrink() reports a shrink question still open, which is what Done waits on. pagehide sends whatever the current mode owes the hub, with keepalive for bodies up to 60,000 bytes. pageshow sends nothing: it resets the exit-send guard so a page restored from the back/forward cache can flush again on a later close. After a save, seenRoomTexts keeps the room states newer than `saved` (bounded at 32) so a snapshot of this room coming back through the change stream is recognized as the room's own history instead of raising the peer-wrote banner" + note for lib "merge3.ts is the browser's copy of internal/textmerge: merge3 (Myers line hunks, diff3, intra-line token merge, content-ordered ties), diffSplices (minimal splices in old-text UTF-16 offsets, applied last first), applySplices and retainsChanges. Ordering compares codepoints so the browser and the hub break ties identically" note for lib "sharedfile.ts is everything about having a file open that is not about a keyboard — join the room, hold the CRDT, save on idle, save once more on the way out. Both surfaces sit on it: Editor binds CodeMirror to the Y.Text, VisualEdit splices ranges into the same one, so somebody typing markup and somebody clicking a headline are in one room and neither has to know the other exists" note for components "components/ui — shadcn/ui primitives (Radix, copied in), themed from BearDrive tokens in tw.css; rendered markdown is transformed as a string before mounting, link clicks delegated on the container — never patch the dangerouslySetInnerHTML subtree" @@ -182,13 +187,15 @@ classDiagram +recents.ts noteOpened useRecents pushRecent (localStorage, per project) +home.ts greeting sinceSummary devicesFrom conflictsIn staleHot readsByFolder +sidebarSearch.ts useSidebarSearch setFilterQuery registerFilterResults - +collab.ts CollabDoc peerCount isRemote stop (y-websocket to the hub-held document; stop = solo for good) + +collab.ts CollabDoc peerCount isRemote onStalled encodeState applySplices applyRemoteUpdate (y-websocket to the hub-held document; stop only when there is no room route) +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once) - +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS + +merge3.ts merge3 diffSplices applySplices retainsChanges (TS port of internal/textmerge) + +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room) +sharedfile.ts rebase (the head sha moved because a co-editor saved) +sharedfile.ts preserve (a save that lost, parked beside the file) +sharedfile.ts ShrinkAsk onShrinkRefused onShrinkWithdrawn onPending (the empty-save guard, client side; destroy withdraws its open ask) + +sharedfile.ts staging checkpoints, peek recovery, seenRoomTexts, pagehide keepalive flush, pageshow exit-guard reset +meeting.ts isMeetingNote sections actionItems openItems previousNote sharpShrink personHue +cm-meeting.ts meetingSections (per-person folds, status, offline section guard) +cm-slash.ts slashMenu (/ commands, @mention, [[ file) @@ -224,7 +231,8 @@ classDiagram components --> lib : buildRows filterTree (FileTree), sidebarSearch (ProjectNav) Browser --> components components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand) - note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain
 — not a second CodeMirror, so nothing looking for the editor finds it. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
+    note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain 
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
+    note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow + askingShrink, and Done waits for it (at most 1.5s, never a veto) before leaving; an open shrink question keeps the user in the editor"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
@@ -236,6 +244,9 @@ classDiagram
     shareMermaid --> lib : renderMermaid
     inlineComment --> lib : anchor.ts (no app imports)
     components --> lib : rangeFor describe hitTest (Comments)
+    components --> lib : merge3 diffSplices (VisualEdit), saveNow askingShrink (FileView flush)
+    Browser ..> components : Done awaits FileView's flushRef
+    lib --> api : syncCollab putText keepalive (sharedfile)
     components ..> inlineComment : postMessage via the ?comment=1 iframe
     hooks --> api
     App --> api : main.tsx startConfig, then prefetchForURL (same query keys as hooks)
diff --git a/architecture/webapp-server.md b/architecture/webapp-server.md
index 5b4cf1b3..51c58284 100644
--- a/architecture/webapp-server.md
+++ b/architecture/webapp-server.md
@@ -48,6 +48,10 @@ classDiagram
         +Close(ctx) error
         -collabContext() process-lifetime context
         -collabHookContext() closing caller or process context
+        -handleYCollabSync() POST {prefix}ycollab/sync, PermWrite
+        -syncDurable / awaitDurable(ctx, room, text, synced) sha, snapFailure
+        -mergeStaleUpload(w, r, v, path, base, head, tmp, size) handled, now
+        -moveDocLive(ctx, room, text, to, sha, filed, recompute)
     }
     class recordingMux {
         <>
@@ -68,6 +72,8 @@ classDiagram
     note for Server "ReportRead is the desktop's read seam, dead on a hub. The sidecar keeps no ReadLedger and answers the viewer routes locally, so a person reading in the Mac app reached no ledger at all while the same file in the web app counted. The hook hands each viewer read to the sidecar, which forwards it to the project's own hub as HUMAN traffic — routing it through the agent report route instead would have filed a person's browsing as a device's."
     note for Server "Desktop marks the loopback sidecar posture (`bdrive desktop`), NOT a hub: the server fronts this machine's own volume stores. It is set in exactly one production place — cmd/bdrive/desktop.go — so on a deployed hub it stays false and both branches below are dead code, leaving /api/config byte-identical to a hub without it. DesktopMe supplies `me` from the device's saved sign-in (settings.json), a func because the tray can change it at runtime; the desktop has no AuthProvider"
     note for Server "clientIP is a METHOD now, not a package func: X-Forwarded-For is honored when the PEER is loopback/private (the operator's own proxy) or TrustProxy is set, and then only its LAST hop. Every caller that gates on an IP — the auth rate limiter, /s/*, device rows, share telemetry — goes through it, so a client-supplied header cannot forge the identity a limiter counts"
+    note for Server "mergeStaleUpload settles a conditional PUT {prefix}upload/content whose If-Match base lost a race: base, the head that replaced it and the incoming bytes are merged three ways (textmerge.Merge), and the result is written held to that head. Every conditional put now records the version it was held to in Op.Base (commitIfBase), so a device merging against it finds the ancestor without guessing. Text only, under maxUploadMergeBytes (4 MiB), never for a room's own write (X-Bdrive-No-Merge), merged again up to three times if the head moves during the append. A retried write whose bytes already landed (landedAfter) and that the head still carries (textmerge.RetainsChanges) is answered as done instead of merged twice. Only the same lines rewritten two ways still return 409. MCP write and edit reach the same door: a stale sha that names a real older version (staleShaError) becomes the base instead of a refusal."
+    note for Server "POST {prefix}ycollab/sync merges a client's Yjs state (or its text against base_text) into the live room over plain HTTP, for a browser whose socket has not connected yet or a shrink it must confirm. peek reads the room without writing. ok rests on positive proof: syncDurable snapshots a few times back to back, then waits for storage (snapshotting each second, or for the lease holder's write in another process) up to ycollabSyncDurableWait (8s); an edit storage does not hold yet is a 503 the browser keeps its edits by."
 
     class volume {
         -source Source
@@ -310,21 +316,30 @@ classDiagram
         <<reearth/ygo, embedded>>
         +ServeHTTP websocket, behind proj(PermRead)
         +Authorize per connection, ReadOnly for a reader
-        +OnLoadDocument lease (no relay), seed from the newest stored state
+        +OnLoadDocument lease (no relay), seed from the newest stored state behind the ydoc/head fence
         +OnLastPeer / OnUnloadDocument snapshot to the file
         +reconcile 409 or blind base: merge, keep, append, or park
         +AttachRelay cluster.Relay, one per process
+        -collabRoomIdleTimeout 2m warm room after the last peer
+        -snapshotMax 6s
     }
+    note for ydocs "ydoc/head/<path> holds {sha, win}: the blob of the newest stored state and the hex winKey of the journal op that produced it (a bare sha from an older hub still parses). A head write whose win sorts below the stored one is refused, so no older fold in any process can move the head backwards, and a seed whose current file is not the head's blob seeds from the file instead (freshRoomFile). knows() merges the other state into a scratch copy and asks whether anything changed, so a history holding deletions is compared by items AND delete set. A reconcile on a live room goes through moveDocLive: the move is computed on a private copy of one atomic snapshot and only the resulting item delta (anchored by ID) is applied, so it integrates around concurrent typing instead of landing at stale character offsets. A failed snapshot republishes the room's whole state to the relay and retries with backoff (snapshotRetryMax 30s)."
     class textmerge {
         <<internal/textmerge>>
         +Merge(base, a, b) out, ok
+        +DiffHunks(old, new) []CharHunk
+        +RetainsChanges(base, candidate, head) bool
+        +IsText(b) bool
     }
-    note for textmerge "Seeding and snapshotting a room. seedDoc tells a missing file from an unreadable one: a path absent from the current snapshot opens empty, but a read that fails REFUSES the room, because an empty document with no base wrote unconditionally — past both the stale-write and the shrink guard, which only look at If-Match writes — and every editor who opened the file in that window emptied it. An empty file is still a file: the room's base is the empty blob and its writes stay conditional. When a snapshot is refused (409) or has no base to send, reconcile reads their version and picks, in order: the line merge of base, room and theirs; theirs alone when the room adds no line theirs lacks (or a conflict copy already holds that text); theirs followed by the room's new lines when the base was empty, or when both sides only added to its end (the line merge has no order for two insertions at one point, and the room, as the only writer, can pick one); and only then a conflict copy. A merged result is spliced into the live document (only if nobody typed since the snapshot read it) so editors see it, and the room rebases onto theirs. A conflict copy holds the room's text, and the document then takes theirs the same way (moveDoc) before rebasing: a room rebased onto theirs while still holding its own text writes that text over theirs on its next pause, conditional on their sha and so accepted. Typed into since, the document keeps its base and the next pause reconciles again. Empty text is never parked"
+    note for textmerge "Seeding and snapshotting a room. seedDoc tells a missing file from an unreadable one: a path absent from the current snapshot opens empty, but a read that fails REFUSES the room, because an empty document with no base wrote unconditionally — past both the stale-write and the shrink guard, which only look at If-Match writes — and every editor who opened the file in that window emptied it. An empty file is still a file: the room's base is the empty blob and its writes stay conditional. When a snapshot is refused (409) or has no base to send, reconcile (reconcileTarget) reads their version and picks, in order: the multi-hunk merge of base, room and theirs; theirs alone when the room adds no line theirs lacks (or a conflict copy already holds that text); theirs followed by the room's new lines when the base was empty, or when both sides only added to its end; and only then a conflict copy. A merged result reaches the live document through moveDocLive as a CRDT item delta built from one atomic snapshot, so typing that arrives meanwhile is kept around it, and the room rebases onto theirs. A conflict copy holds the room's text, and the document then takes theirs the same way before rebasing: a room rebased onto theirs while still holding its own text writes that text over theirs on its next pause, conditional on their sha and so accepted. Typed into since, recompute re-derives the target from the snapshot or the document keeps its base and the next pause reconciles again. Empty text is never parked"
     class CollabConfig {
         <<internal/webapp, collab_relay.go>>
         +Redis string
+        -collabStreamRetention 30m
+        -collabStreamMaxLen 32768
     }
     note for CollabConfig "How co-editing crosses hub PROCESSES. Set, ConnectCollab attaches ygo's cluster/redis relay on the STREAMS tier (never pub/sub: at-most-once, and one lost update parks every later edit from that client until the room reloads) so every process may host a room and the relay carries each update between them; the relay carries only live edits, so a process opening a room mid-session builds it from the state the writer last stored (ydoc/head/<path>) and the stream replays its retained window on top. Unset, one process holds each document: a second one refuses the room (errRoomElsewhere → 500) and y-websocket's retry carries the browser to the one that does. Required once a hub runs as more than one process; a single process needs none. Server.Close writes every live room back and is what bdrive serve and the cloud binary call on SIGTERM — Cloud Run gives ten seconds"
+    note for CollabConfig "The relay's StreamRetention is 30 minutes (ygo's default is 60s) and StreamMaxLen 32768 entries. The retained window is what a process opening a room mid-session replays on top of the last stored state, so it must outlast the gap between two snapshots that landed: a write retried with backoff, a dead lease holder waiting out leaseTTL, an idle room. republishRoom re-sends a room's whole state after a failed snapshot so the window always holds the edits storage does not."
     class roomLease {
         <<internal/webapp, lease.go>>
         -version remote.Version
@@ -912,7 +927,9 @@ classDiagram
     Server *-- roomLease : one per live room, holdLease / keepLease / releaseLease
     roomLease ..> ConditionalPutter : one lease object per path in the project storage
     ydocs ..> roomLease : OnLoadDocument without a relay, every snapshot with one
-    ydocs ..> textmerge : reconcile an outside write into the room
+    ydocs ..> textmerge : reconcile an outside write (Merge), splice it as minimal hunks (DiffHunks)
+    Server ..> textmerge : mergeStaleUpload (Merge, RetainsChanges), ycollab/sync text against base_text
+    Server ..> ydocs : POST ycollab/sync applies a client state, syncDurable waits for storage
     ydocs ..> ConditionalPutter : claimRoomHistory stores a seed once across processes
     QuotaProvider <|.. UnlimitedQuota
 ```
@@ -986,6 +1003,7 @@ classDiagram
         query describe
     }
     note for mcpTools "mcp.go — list and glob are the ls/tree pair; grep is an on-demand bounded scan (2000 files / 64 MiB / 200 matches), no index to build or invalidate. history and restore are the two BearDrive has that a local filesystem does not, and they are why an agent can undo itself. Bounds are reported in the output, never silent: a truncated grep says so, because a scan that quietly stopped reads to an agent as proof the string is absent"
+    note for mcpTools "write and edit given a sha the file has moved on from are not refused outright: checkStale returns staleShaError carrying the full older sha, edit applies its substitution to that version, and both send it as the If-Match base so the upload door merges it with what landed since (mergeStaleUpload). Only the same lines changed two ways still come back as stale."
 
     class internalClient {
         <>
diff --git a/cmd/bdrive/desktop.go b/cmd/bdrive/desktop.go
index 734043be..53d3ef21 100644
--- a/cmd/bdrive/desktop.go
+++ b/cmd/bdrive/desktop.go
@@ -171,6 +171,7 @@ var desktopRoutes = []struct {
 	// argument to the URL. Decoration — the hub names the room itself — but
 	// it has to be classified, or the desktop answers it locally.
 	{"GET /api/p/{project}/ycollab/{room...}", routeProxy, ""},
+	{"POST /api/p/{project}/ycollab/sync", routeProxy, ""},
 
 	{"POST /api/p/{project}/reads", routeLocal, "the sync client posts these straight to the hub, never through here; the app's own viewer reads go out through desktop_reads.go instead, as human traffic"},
 }
diff --git a/internal/syncer/merge.go b/internal/syncer/merge.go
index 315bf596..7a231dd9 100644
--- a/internal/syncer/merge.go
+++ b/internal/syncer/merge.go
@@ -228,3 +228,21 @@ func (s *Session) readBlob(sum string, max int64) ([]byte, bool) {
 	}
 	return b, true
 }
+
+// latestPut is the greatest put on path holding blob across lists: the op
+// that produced the version replay resolved to, as far as these lists show.
+func latestPut(path, blob string, lists ...[]journal.Op) (journal.Op, bool) {
+	var best journal.Op
+	found := false
+	for _, ops := range lists {
+		for _, op := range ops {
+			if op.Path != path || op.Kind != journal.KindPut || op.Blob != blob {
+				continue
+			}
+			if !found || journal.Less(best, op) {
+				best, found = op, true
+			}
+		}
+	}
+	return best, found
+}
diff --git a/internal/syncer/merge_contentproof_test.go b/internal/syncer/merge_contentproof_test.go
new file mode 100644
index 00000000..aef13d73
--- /dev/null
+++ b/internal/syncer/merge_contentproof_test.go
@@ -0,0 +1,168 @@
+package syncer
+
+import (
+	"os"
+	"strings"
+	"testing"
+	"time"
+)
+
+// conflictCopies lists the conflict copies of rel in a folder's root.
+func conflictCopies(t *testing.T, folder, rel string) []string {
+	t.Helper()
+	entries, err := os.ReadDir(folder)
+	if err != nil {
+		t.Fatal(err)
+	}
+	stem := strings.TrimSuffix(rel, ".md")
+	var out []string
+	for _, e := range entries {
+		if strings.HasPrefix(e.Name(), stem) && strings.Contains(e.Name(), "conflict") {
+			out = append(out, e.Name())
+		}
+	}
+	return out
+}
+
+func mergeOps(t *testing.T, s *Session) int {
+	t.Helper()
+	ops, err := s.Store.DeviceOps(s.Device.ID)
+	if err != nil {
+		t.Fatal(err)
+	}
+	n := 0
+	for _, op := range ops {
+		if op.Note == mergeNote {
+			n++
+		}
+	}
+	return n
+}
+
+// X₁ → A → X₂ (a revert) → then A again on this device, offline, while a
+// peer writes B on X₂ and wins. B's history passes through an OLDER A, but B
+// does not hold the A that lost: the edit must be merged into the file or
+// preserved as a conflict copy — never dropped because a blob recurs in
+// history.
+func TestSyncerRevertDoesNotDropConcurrentEdit(t *testing.T) {
+	const x = "one\ntwo\nthree\n"
+	for _, c := range []struct {
+		name, a, b, merged string
+	}{
+		{name: "disjoint edits merge", a: "ONE\ntwo\nthree\n", b: "one\ntwo\nTHREE\n", merged: "ONE\ntwo\nTHREE\n"},
+		{name: "overlapping edits keep a conflict copy", a: "one\nTWO-A\nthree\n", b: "one\nTWO-B\nthree\n"},
+	} {
+		t.Run(c.name, func(t *testing.T) {
+			be := sharedRemote(t)
+			a := newDevice(t, "deva", be)
+			b := newDevice(t, "devb", be)
+
+			write(t, a.Folder, "f.md", x) // X₁
+			cycle(t, a)
+			cycle(t, b)
+			time.Sleep(10 * time.Millisecond)
+			write(t, a.Folder, "f.md", c.a) // A₁
+			cycle(t, a)
+			cycle(t, b)
+			time.Sleep(10 * time.Millisecond)
+			write(t, b.Folder, "f.md", x) // X₂, the revert
+			cycle(t, b)
+			cycle(t, a)
+			if got := read(t, a.Folder, "f.md"); got != x {
+				t.Fatalf("a did not receive the revert: %q", got)
+			}
+
+			// A₂ on X₂, journaled offline: it stays unpushed.
+			a.Backend = nil
+			time.Sleep(10 * time.Millisecond)
+			write(t, a.Folder, "f.md", c.a)
+			cycle(t, a)
+
+			// B on X₂ wins: b's clock runs ahead with an unrelated edit first.
+			write(t, b.Folder, "other.md", "bump")
+			cycle(t, b)
+			time.Sleep(10 * time.Millisecond)
+			write(t, b.Folder, "f.md", c.b)
+			cycle(t, b)
+
+			a.Backend = be
+			cycle(t, a)
+			cycle(t, b)
+			cycle(t, a)
+
+			gotA, gotB := read(t, a.Folder, "f.md"), read(t, b.Folder, "f.md")
+			if gotA != gotB {
+				t.Fatalf("devices diverged: a=%q b=%q", gotA, gotB)
+			}
+			if c.merged != "" {
+				if gotA != c.merged {
+					t.Fatalf("f.md = %q, want the merge %q", gotA, c.merged)
+				}
+				if cc := conflictCopies(t, a.Folder, "f.md"); len(cc) != 0 {
+					t.Fatalf("clean merge left conflict copies: %v", cc)
+				}
+				return
+			}
+			if gotA != c.b {
+				t.Fatalf("f.md = %q, want the winner %q", gotA, c.b)
+			}
+			for _, s := range []*Session{a, b} {
+				cc := conflictCopies(t, s.Folder, "f.md")
+				if len(cc) != 1 {
+					t.Fatalf("%s: conflict copies = %v, want one holding A", s.Device.Name, cc)
+				}
+				if got := read(t, s.Folder, cc[0]); got != c.a {
+					t.Fatalf("%s: conflict copy = %q, want A's edit %q", s.Device.Name, got, c.a)
+				}
+			}
+		})
+	}
+}
+
+// When the version that won already holds the local edit — Merge(X, mine, M)
+// is byte-for-byte M — the cycle fast-forwards: no merge op and no conflict
+// copy duplicate what the winner already says.
+func TestSyncerFastForwardsWhenWinnerHoldsLocalEdit(t *testing.T) {
+	const (
+		x     = "one\ntwo\nthree\n"
+		local = "one\ntwo\nTHREE\n"
+		m     = "ONE\ntwo\nTHREE\n"
+	)
+	be := sharedRemote(t)
+	a := newDevice(t, "deva", be)
+	h := newDevice(t, "hub", be)
+
+	write(t, a.Folder, "f.md", x)
+	cycle(t, a)
+	cycle(t, h)
+
+	a.Backend = nil
+	time.Sleep(10 * time.Millisecond)
+	write(t, a.Folder, "f.md", local)
+	cycle(t, a)
+
+	write(t, h.Folder, "other.md", "bump")
+	cycle(t, h)
+	time.Sleep(10 * time.Millisecond)
+	write(t, h.Folder, "f.md", m)
+	cycle(t, h)
+
+	a.Backend = be
+	res := cycle(t, a)
+	if res.Merged != 0 || res.Conflicts != 0 {
+		t.Fatalf("fast-forward wrote merged=%d conflicts=%d, want 0/0", res.Merged, res.Conflicts)
+	}
+	if got := read(t, a.Folder, "f.md"); got != m {
+		t.Fatalf("f.md = %q, want the winner %q", got, m)
+	}
+	if n := mergeOps(t, a); n != 0 {
+		t.Fatalf("a journaled %d merge ops, want 0", n)
+	}
+	if cc := conflictCopies(t, a.Folder, "f.md"); len(cc) != 0 {
+		t.Fatalf("fast-forward left conflict copies: %v", cc)
+	}
+	cycle(t, h)
+	if got := read(t, h.Folder, "f.md"); got != m {
+		t.Fatalf("hub f.md = %q, want %q", got, m)
+	}
+}
diff --git a/internal/syncer/merge_test.go b/internal/syncer/merge_test.go
index 6800b434..cca431b7 100644
--- a/internal/syncer/merge_test.go
+++ b/internal/syncer/merge_test.go
@@ -1,6 +1,8 @@
 package syncer
 
-import "testing"
+import (
+	"testing"
+)
 
 func TestMergeText(t *testing.T) {
 	for _, c := range []struct {
@@ -35,11 +37,14 @@ func TestMergeText(t *testing.T) {
 		b:    "a\nY\nc\n",
 		ok:   false,
 	}, {
+		// Two additions at one place are not a conflict: both are kept, in
+		// an order picked by content so either device merges the same blob.
 		name: "both sides inserted at the same point",
 		base: "a\nc\n",
 		a:    "a\nFROM-A\nc\n",
 		b:    "a\nFROM-B\nc\n",
-		ok:   false,
+		want: "a\nFROM-A\nFROM-B\nc\n",
+		ok:   true,
 	}, {
 		name: "one side deleted a region the other left alone",
 		base: "keep\ndrop\nkeep2\n",
diff --git a/internal/syncer/syncer.go b/internal/syncer/syncer.go
index 8bf09584..d92e1a4a 100644
--- a/internal/syncer/syncer.go
+++ b/internal/syncer/syncer.go
@@ -2186,8 +2186,26 @@ func (s *Session) conflictCopiesWithState(unpushedOps []journal.Op, seqBase int6
 			})
 			continue
 		}
+		// What the loser is merged against is the op that WON — the version
+		// replay resolved to — so the merge proves by content alone whether
+		// that version already holds the loser's edit. Lineage is never
+		// guessed from Base links: in X → A → X → B, B built on the second X
+		// does not hold A even though a chain of blobs leads back through it.
 		merged, canMerge := mergedBlob{}, false
-		if collided {
+		other, haveOther := theirs, collided
+		if !mineWon && exists && cur.Link == "" && cur.Blob != "" {
+			if all == nil {
+				var err error
+				all, err = s.Store.AllOps()
+				if err != nil {
+					return nil, err
+				}
+			}
+			if winner, ok := latestPut(p, cur.Blob, theirsList, unpushedOps, all); ok {
+				other, haveOther = winner, true
+			}
+		}
+		if haveOther {
 			if all == nil {
 				var err error
 				all, err = s.Store.AllOps()
@@ -2195,19 +2213,33 @@ func (s *Session) conflictCopiesWithState(unpushedOps []journal.Op, seqBase int6
 					return nil, err
 				}
 			}
-			merged, canMerge = s.tryMerge(p, mine, theirs, all)
+			if other.Blob != "" && !s.Store.HasBlob(other.Blob) {
+				_, _ = s.fetchBlobs(context.Background(), []journal.Op{other}, nil)
+			}
+			merged, canMerge = s.tryMerge(p, mine, other, all)
+		}
+		if canMerge && exists && merged.blob == cur.Blob {
+			// Content proof: merging the loser into the winner yields the
+			// winner's exact bytes, so it already holds both sides — another
+			// device (or the hub) computed the merge first. Fast-forward: no
+			// second op for it.
+			continue
 		}
 		if canMerge {
 			st.Lamport = tickLamport(st.Lamport)
 			seqBase++
-			out = append(out, journal.Op{
+			op := journal.Op{
 				Seq: seqBase, Lamport: st.Lamport, Time: time.Now().UTC(),
 				Device: s.Device.ID, DeviceName: s.Device.Name, Author: s.Device.Author,
 				User: s.Account.Email, UserName: s.Account.Name,
 				Kind: journal.KindPut, Path: p,
 				Blob: merged.blob, Size: merged.size, Mode: mine.Mode,
 				Note: mergeNote,
-			})
+			}
+			if exists && cur.Link == "" {
+				op.Base = cur.Blob // built on the version that won
+			}
+			out = append(out, op)
 			continue
 		}
 		st.Lamport = tickLamport(st.Lamport)
diff --git a/internal/textmerge/merge.go b/internal/textmerge/merge.go
index 179d064b..48c16910 100644
--- a/internal/textmerge/merge.go
+++ b/internal/textmerge/merge.go
@@ -3,14 +3,23 @@
 // under a live co-editing room).
 //
 // Hand-written, no dependency: the code that decides what a merged file
-// contains should be readable in one sitting. Line-based on purpose. Word- or
-// character-level merging resolves more cases and silently produces sentences
-// neither author wrote; a line is the unit people actually edit, and anything
-// overlapping is left to the caller's conflict path.
+// contains should be readable in one sitting. Each side is diffed against the
+// base with a Myers O(ND) line diff, so a side that touched several places in
+// a file produces several small hunks rather than one span from its first
+// change to its last. Hunks that do not touch the same base lines apply
+// independently (diff3). Where both sides changed the same lines, three
+// narrow cases still resolve without inventing text: an identical edit, two
+// insertions at one point of a non-empty file (one already holding the other,
+// or both kept in a content-defined order), and a single line both sides
+// edited in different words. Everything else is a real conflict and stays one.
 package textmerge
 
 import (
 	"bytes"
+	"sort"
+	"strings"
+	"unicode"
+	"unicode/utf16"
 	"unicode/utf8"
 )
 
@@ -22,120 +31,467 @@ func IsText(b []byte) bool {
 }
 
 // Merge merges two edits of the same base. ok is false when the two sides
-// changed the same region, which is a real conflict and stays one.
+// changed the same region in different ways, which is a real conflict and
+// stays one, or when any input is not text.
 //
 // Determinism matters more than cleverness here: two devices can each observe
 // the same concurrency and merge independently, so merge(base, a, b) and
-// merge(base, b, a) must agree or the fleet diverges. Only NON-overlapping
-// hunks are ever taken, which makes the result the union either way.
+// merge(base, b, a) must agree or the fleet diverges. Every rule below is
+// symmetric in a and b; where an order has to be picked (two insertions at
+// one point) it is picked by content, never by argument position.
 func Merge(base, a, b []byte) ([]byte, bool) {
+	if !IsText(base) || !IsText(a) || !IsText(b) {
+		return nil, false
+	}
 	ls, la, lb := splitLines(base), splitLines(a), splitLines(b)
-	ca, cb := changedRegions(ls, la), changedRegions(ls, lb)
-	if overlaps(ca, cb) {
+	out, ok := merge3(ls, la, lb, true)
+	if !ok {
 		return nil, false
 	}
+	// The final newline is one more thing a side may change: whichever side
+	// changed it from the base wins, and both can only change it one way.
+	trailing := trailingNewline(a)
+	if trailing == trailingNewline(base) {
+		trailing = trailingNewline(b)
+	}
+	return joinLines(out, trailing), true
+}
+
+// region is a half-open span of BASE units one side replaced, plus where the
+// replacement lives in that side.
+type region struct {
+	from, to     int // in base
+	toFrom, toTo int // in the edited side
+}
 
-	// Walk the base once, emitting whichever side replaced each region.
-	type edit struct {
-		r    region
-		with [][]byte
+// conflicting reports whether two hunks from opposite sides touch the same
+// base units. Regions that merely ABUT do not — one side replacing 1-3 and
+// the other 3-5 do, because unit 3 is in both. Two pure insertions at the same
+// point are ordered by nothing, so they are grouped and resolved explicitly.
+func conflicting(x, y region) bool {
+	if x.from < y.to && y.from < x.to {
+		return true
 	}
-	var edits []edit
-	for _, r := range ca {
-		edits = append(edits, edit{r, la[r.toFrom:r.toTo]})
+	return x.from == x.to && y.from == y.to && x.from == y.from
+}
+
+// merge3 is diff3 over sequences of units (lines, or tokens of one line).
+// lines enables the two line-only resolutions: concatenating same-point
+// insertions and merging one line word by word.
+func merge3(base, a, b [][]byte, lines bool) ([][]byte, bool) {
+	ca, cb := diffRegions(base, a), diffRegions(base, b)
+	if len(ca) == 0 {
+		return b, true
 	}
-	for _, r := range cb {
-		edits = append(edits, edit{r, lb[r.toFrom:r.toTo]})
+	if len(cb) == 0 {
+		return a, true
+	}
+
+	// Group hunks that conflict, transitively (union-find). Both lists are
+	// sorted by base position and disjoint within a side, so a sweep finds
+	// every conflicting pair without comparing all of them.
+	n := len(ca) + len(cb)
+	parent := make([]int, n)
+	for i := range parent {
+		parent[i] = i
 	}
-	// Sorted by base position. Disjoint regions can still START at one line:
-	// an insertion before line k and the other side replacing from line k.
-	// The insertion goes first, whichever side made it — taken the other
-	// way round the walk would step back to k and re-emit the replaced
-	// lines, and merge(base, a, b) would differ from merge(base, b, a).
-	before := func(x, y region) bool {
-		if x.from != y.from {
-			return x.from < y.from
+	var find func(int) int
+	find = func(i int) int {
+		for parent[i] != i {
+			parent[i] = parent[parent[i]]
+			i = parent[i]
 		}
-		return x.to < y.to
+		return i
 	}
-	for i := 1; i < len(edits); i++ {
-		for j := i; j > 0 && before(edits[j].r, edits[j-1].r); j-- {
-			edits[j], edits[j-1] = edits[j-1], edits[j]
+	j := 0
+	for i, x := range ca {
+		for j < len(cb) && cb[j].to < x.from {
+			j++
 		}
+		for k := j; k < len(cb) && cb[k].from <= x.to; k++ {
+			if conflicting(x, cb[k]) {
+				if ri, rk := find(i), find(len(ca)+k); ri != rk {
+					parent[ri] = rk
+				}
+			}
+		}
+	}
+
+	type unit struct {
+		lo, hi int
+		as, bs []region
 	}
+	units := map[int]*unit{}
+	order := []int{}
+	add := func(idx int, r region, sideA bool) {
+		root := find(idx)
+		u := units[root]
+		if u == nil {
+			u = &unit{lo: r.from, hi: r.to}
+			units[root] = u
+			order = append(order, root)
+		}
+		u.lo, u.hi = min(u.lo, r.from), max(u.hi, r.to)
+		if sideA {
+			u.as = append(u.as, r)
+		} else {
+			u.bs = append(u.bs, r)
+		}
+	}
+	for i, r := range ca {
+		add(i, r, true)
+	}
+	for k, r := range cb {
+		add(len(ca)+k, r, false)
+	}
+	list := make([]*unit, 0, len(order))
+	for _, root := range order {
+		list = append(list, units[root])
+	}
+	// Sorted by base position. Disjoint units can still START at one unit:
+	// an insertion before k and the other side replacing from k. The
+	// insertion goes first, whichever side made it.
+	sort.SliceStable(list, func(i, j int) bool {
+		if list[i].lo != list[j].lo {
+			return list[i].lo < list[j].lo
+		}
+		return list[i].hi < list[j].hi
+	})
 
 	var out [][]byte
 	at := 0
-	for _, e := range edits {
-		for ; at < e.r.from; at++ {
-			out = append(out, ls[at])
+	for _, u := range list {
+		for ; at < u.lo; at++ {
+			out = append(out, base[at])
 		}
-		out = append(out, e.with...)
-		at = e.r.to
+		switch {
+		case len(u.bs) == 0:
+			out = append(out, applyWithin(base, a, u.lo, u.hi, u.as)...)
+		case len(u.as) == 0:
+			out = append(out, applyWithin(base, b, u.lo, u.hi, u.bs)...)
+		default:
+			got, ok := resolve(base, a, b, u.lo, u.hi, u.as, u.bs, lines)
+			if !ok {
+				return nil, false
+			}
+			out = append(out, got...)
+		}
+		at = max(at, u.hi)
 	}
-	for ; at < len(ls); at++ {
-		out = append(out, ls[at])
+	for ; at < len(base); at++ {
+		out = append(out, base[at])
 	}
-	// The final newline is one more thing a side may change: whichever side
-	// changed it from the base wins, and both can only change it one way.
-	trailing := trailingNewline(a)
-	if trailing == trailingNewline(base) {
-		trailing = trailingNewline(b)
+	return out, true
+}
+
+// applyWithin is one side's version of base[lo:hi], with that side's hunks
+// inside the span applied.
+func applyWithin(base, side [][]byte, lo, hi int, hunks []region) [][]byte {
+	var out [][]byte
+	at := lo
+	for _, h := range hunks {
+		out = append(out, base[at:h.from]...)
+		out = append(out, side[h.toFrom:h.toTo]...)
+		at = h.to
 	}
-	return joinLines(out, trailing), true
+	return append(out, base[at:hi]...)
 }
 
-// region is a half-open span of BASE lines one side replaced, plus where the
-// replacement lives in that side.
-type region struct {
-	from, to     int // in base
-	toFrom, toTo int // in the edited side
+// resolve settles a span both sides changed, or reports a conflict.
+func resolve(base, a, b [][]byte, lo, hi int, as, bs []region, lines bool) ([][]byte, bool) {
+	spanA, spanB := applyWithin(base, a, lo, hi, as), applyWithin(base, b, lo, hi, bs)
+	if equalUnits(spanA, spanB) {
+		return spanA, true // the same edit on both sides: emitted once
+	}
+	if len(as) != 1 || len(bs) != 1 {
+		return nil, false
+	}
+	x, y := as[0], bs[0]
+	aRepl, bRepl := a[x.toFrom:x.toTo], b[y.toFrom:y.toTo]
+	if x.from == x.to && y.from == y.to {
+		// Two different insertions at one point (identical ones were emitted
+		// once above). Neither is taken as a retry of the other: a repeated
+		// log line appended twice is two lines, and only the caller knows
+		// whether a write already landed.
+		if !lines {
+			return nil, false // two different words at one point: no sentence to make
+		}
+		if len(base) == 0 {
+			// Over an EMPTY ancestor the "one point" is the whole file: two
+			// devices each creating it, or filling in a file that was touched
+			// empty. One body that begins with the whole other is that file
+			// written further; two different bodies are two documents, not
+			// two additions to one, and spliced together they read as neither.
+			if len(aRepl) <= len(bRepl) && equalUnits(bRepl[:len(aRepl)], aRepl) {
+				return bRepl, true
+			}
+			if len(bRepl) < len(aRepl) && equalUnits(aRepl[:len(bRepl)], bRepl) {
+				return aRepl, true
+			}
+			return nil, false
+		}
+		// Two people adding at one place: keep both, in an order that does
+		// not depend on which side is which.
+		first, second := aRepl, bRepl
+		if bytes.Compare(bytes.Join(bRepl, []byte("\n")), bytes.Join(aRepl, []byte("\n"))) < 0 {
+			first, second = bRepl, aRepl
+		}
+		out := make([][]byte, 0, len(first)+len(second))
+		out = append(out, first...)
+		return append(out, second...), true
+	}
+	if lines && x.from == y.from && x.to == y.to && x.to-x.from == 1 && len(aRepl) == 1 && len(bRepl) == 1 {
+		// One line both sides edited: merge it word by word, with the same
+		// rule — different words merge, the same word changed two ways is a
+		// conflict.
+		got, ok := merge3(tokens(base[x.from]), tokens(aRepl[0]), tokens(bRepl[0]), false)
+		if !ok {
+			return nil, false
+		}
+		return [][]byte{bytes.Join(got, nil)}, true
+	}
+	return nil, false
 }
 
-// changedRegions is the coarsest useful diff: trim the common prefix and
-// suffix and call the rest one changed span. That is exactly what makes the
-// merge safe to reason about — a side "changed" one contiguous region, and
-// two sides that changed different regions cannot interfere.
-//
-// It resolves the case that matters (two people working in different parts of
-// a document) and declines everything else to the conflict copy, rather than
-// resolving more cases with a hunk matcher nobody can audit.
-func changedRegions(base, side [][]byte) []region {
+// tokens splits one line into maximal runs of whitespace and non-whitespace,
+// which join back to exactly the line.
+func tokens(line []byte) [][]byte {
+	var out [][]byte
+	start, prev := 0, -1
+	for i, r := range string(line) {
+		kind := 0
+		if unicode.IsSpace(r) {
+			kind = 1
+		}
+		if prev != -1 && kind != prev {
+			out = append(out, line[start:i])
+			start = i
+		}
+		prev = kind
+	}
+	if start < len(line) {
+		out = append(out, line[start:])
+	}
+	return out
+}
+
+func equalUnits(a, b [][]byte) bool {
+	if len(a) != len(b) {
+		return false
+	}
+	for i := range a {
+		if !bytes.Equal(a[i], b[i]) {
+			return false
+		}
+	}
+	return true
+}
+
+// maxEditDistance bounds the Myers search, whose trace costs O(D²) memory.
+// Past it the changed middle is one region, which is the coarse diff this
+// package used before: still correct, only less able to merge.
+const maxEditDistance = 2000
+
+// diffRegions is a minimal line diff of side against base: the disjoint
+// hunks, each separated from the next by at least one unchanged unit.
+func diffRegions(base, side [][]byte) []region {
+	n, m := len(base), len(side)
 	p := 0
-	for p < len(base) && p < len(side) && bytes.Equal(base[p], side[p]) {
+	for p < n && p < m && bytes.Equal(base[p], side[p]) {
 		p++
 	}
-	if p == len(base) && p == len(side) {
-		return nil // identical
+	if p == n && p == m {
+		return nil
 	}
 	s := 0
-	for s < len(base)-p && s < len(side)-p &&
-		bytes.Equal(base[len(base)-1-s], side[len(side)-1-s]) {
+	for s < n-p && s < m-p && bytes.Equal(base[n-1-s], side[m-1-s]) {
 		s++
 	}
-	return []region{{from: p, to: len(base) - s, toFrom: p, toTo: len(side) - s}}
+	whole := []region{{from: p, to: n - s, toFrom: p, toTo: m - s}}
+	if n-s == p || m-s == p {
+		return whole // pure insertion or pure deletion
+	}
+	ids := map[string]int{}
+	intern := func(units [][]byte) []int {
+		out := make([]int, len(units))
+		for i, u := range units {
+			id, ok := ids[string(u)]
+			if !ok {
+				id = len(ids)
+				ids[string(u)] = id
+			}
+			out[i] = id
+		}
+		return out
+	}
+	x, y := intern(base[p:n-s]), intern(side[p:m-s])
+	matches, ok := myers(x, y)
+	if !ok {
+		return whole
+	}
+	var out []region
+	pi, pj := 0, 0
+	for _, mt := range matches {
+		if mt[0] > pi || mt[1] > pj {
+			out = append(out, region{from: p + pi, to: p + mt[0], toFrom: p + pj, toTo: p + mt[1]})
+		}
+		pi, pj = mt[0]+1, mt[1]+1
+	}
+	if pi < len(x) || pj < len(y) {
+		out = append(out, region{from: p + pi, to: p + len(x), toFrom: p + pj, toTo: p + len(y)})
+	}
+	return out
 }
 
-// overlaps reports whether the two sides touched the same base lines. Regions
-// that merely ABUT do not overlap — one side replacing lines 1-3 and the other
-// 3-5 do, because line 3 is in both.
-func overlaps(a, b []region) bool {
-	if len(a) == 0 || len(b) == 0 {
-		return false // one side did not change anything to conflict with
-	}
-	for _, x := range a {
-		for _, y := range b {
-			if x.from < y.to && y.from < x.to {
-				return true
+// myers returns the matched (a, b) index pairs of a shortest edit script, in
+// order, or false when the edit distance exceeds maxEditDistance.
+func myers(a, b []int) ([][2]int, bool) {
+	n, m := len(a), len(b)
+	limit := min(n+m, maxEditDistance)
+	off := limit + 1
+	v := make([]int, 2*limit+3)
+	// trace[d] is v[-d..d] after step d, indexed by k+d.
+	var trace [][]int
+	for d := 0; d <= limit; d++ {
+		done := false
+		for k := -d; k <= d; k += 2 {
+			var x int
+			if k == -d || (k != d && v[off+k-1] < v[off+k+1]) {
+				x = v[off+k+1]
+			} else {
+				x = v[off+k-1] + 1
+			}
+			y := x - k
+			for x < n && y < m && a[x] == b[y] {
+				x++
+				y++
 			}
-			// A pure insertion is an empty base span; two insertions at the
-			// same point are ordered by nothing and must not be merged.
-			if x.from == x.to && y.from == y.to && x.from == y.from {
-				return true
+			v[off+k] = x
+			if x >= n && y >= m {
+				done = true
+				break
 			}
 		}
+		trace = append(trace, append([]int(nil), v[off-d:off+d+1]...))
+		if done {
+			return backtrack(trace, n, m), true
+		}
+	}
+	return nil, false
+}
+
+func backtrack(trace [][]int, n, m int) [][2]int {
+	var rev [][2]int
+	x, y := n, m
+	for d := len(trace) - 1; d > 0; d-- {
+		prev := trace[d-1]
+		at := func(k int) int { return prev[k+d-1] }
+		k := x - y
+		var prevK int
+		if k == -d || (k != d && at(k-1) < at(k+1)) {
+			prevK = k + 1
+		} else {
+			prevK = k - 1
+		}
+		prevX := at(prevK)
+		prevY := prevX - prevK
+		for x > prevX && y > prevY {
+			rev = append(rev, [2]int{x - 1, y - 1})
+			x--
+			y--
+		}
+		x, y = prevX, prevY
+	}
+	for x > 0 && y > 0 {
+		rev = append(rev, [2]int{x - 1, y - 1})
+		x--
+		y--
+	}
+	for i, j := 0, len(rev)-1; i < j; i, j = i+1, j-1 {
+		rev[i], rev[j] = rev[j], rev[i]
+	}
+	return rev
+}
+
+// CharHunk is one edit turning old text into new: replace old[Start:End] with
+// Insert. Offsets are UTF-16 code units into the OLD text, which is what Yjs
+// counts in.
+type CharHunk struct {
+	Start, End int
+	Insert     string
+}
+
+// DiffHunks is the minimal set of disjoint edits turning oldText into
+// newText, ascending: a Myers line diff, each changed span then trimmed to
+// the characters that actually differ. Applied from last to first, each
+// edit's offsets stay valid. A splice made this way keeps every unchanged
+// line as the same CRDT items instead of re-inserting the whole middle.
+func DiffHunks(oldText, newText string) []CharHunk {
+	if oldText == newText {
+		return nil
+	}
+	ol, nl := splitKeep(oldText), splitKeep(newText)
+	toBytes := func(ss []string) [][]byte {
+		out := make([][]byte, len(ss))
+		for i, s := range ss {
+			out[i] = []byte(s)
+		}
+		return out
+	}
+	regions := diffRegions(toBytes(ol), toBytes(nl))
+	// UTF-16 offset at the start of each old line.
+	starts := make([]int, len(ol)+1)
+	for i, l := range ol {
+		starts[i+1] = starts[i] + u16len(l)
+	}
+	out := make([]CharHunk, 0, len(regions))
+	for _, r := range regions {
+		was := strings.Join(ol[r.from:r.to], "")
+		now := strings.Join(nl[r.toFrom:r.toTo], "")
+		a, b := []rune(was), []rune(now)
+		p := 0
+		for p < len(a) && p < len(b) && a[p] == b[p] {
+			p++
+		}
+		s := 0
+		for s < len(a)-p && s < len(b)-p && a[len(a)-1-s] == b[len(b)-1-s] {
+			s++
+		}
+		start := starts[r.from] + len(utf16.Encode(a[:p]))
+		del := len(utf16.Encode(a[p : len(a)-s]))
+		ins := string(b[p : len(b)-s])
+		if del == 0 && ins == "" {
+			continue
+		}
+		out = append(out, CharHunk{Start: start, End: start + del, Insert: ins})
 	}
-	return false
+	return out
+}
+
+// splitKeep splits text into lines that keep their "\n", so they join back
+// to exactly the text.
+func splitKeep(s string) []string {
+	if s == "" {
+		return nil
+	}
+	out := strings.SplitAfter(s, "\n")
+	if out[len(out)-1] == "" {
+		out = out[:len(out)-1]
+	}
+	return out
+}
+
+// u16len is the length of s in UTF-16 code units.
+func u16len(s string) int {
+	n := 0
+	for _, r := range s {
+		if r >= 0x10000 {
+			n += 2
+		} else {
+			n++
+		}
+	}
+	return n
 }
 
 func splitLines(b []byte) [][]byte {
@@ -158,3 +514,47 @@ func joinLines(lines [][]byte, trailing bool) []byte {
 }
 
 func trailingNewline(b []byte) bool { return len(b) > 0 && b[len(b)-1] == '\n' }
+
+// RetainsChanges reports whether head still carries every line edit that
+// took base to candidate, untouched: no later edit (candidate -> head)
+// overlaps a span candidate inserted or rewrote, inserts inside such a span,
+// or inserts where candidate deleted lines, and a final newline candidate
+// changed is still the way candidate left it. It is deliberately strict —
+// false means "cannot prove it is retained", never "it was reverted".
+func RetainsChanges(base, candidate, head []byte) bool {
+	if !IsText(base) || !IsText(candidate) || !IsText(head) {
+		return false
+	}
+	lc := splitLines(candidate)
+	ours := diffRegions(splitLines(base), lc)
+	later := diffRegions(lc, splitLines(head))
+	for _, h1 := range ours {
+		for _, h2 := range later {
+			if h1.toFrom < h1.toTo {
+				if h1.from < h1.to {
+					// candidate REPLACED base lines: a later edit even abutting
+					// the span may be the old lines going back in beside it
+					// (a\nb\nc -> a\nX\nc -> a\nX\nb\nc), so it must keep clear.
+					if !(h2.to < h1.toFrom || h2.from > h1.toTo) {
+						return false
+					}
+					continue
+				}
+				// A pure insertion: nothing may touch it or insert strictly
+				// inside it; appending right after it is someone else's line.
+				if !(h2.to <= h1.toFrom || h2.from >= h1.toTo) {
+					return false
+				}
+				continue
+			}
+			// A pure deletion at h1.toFrom: nothing may put lines back there.
+			if h2.toFrom < h2.toTo && h2.from <= h1.toFrom && h1.toFrom <= h2.to {
+				return false
+			}
+		}
+	}
+	if trailingNewline(candidate) != trailingNewline(base) && trailingNewline(head) != trailingNewline(candidate) {
+		return false
+	}
+	return true
+}
diff --git a/internal/textmerge/merge_test.go b/internal/textmerge/merge_test.go
index 75adc7e4..b1128cbb 100644
--- a/internal/textmerge/merge_test.go
+++ b/internal/textmerge/merge_test.go
@@ -82,3 +82,56 @@ func TestMergeKeepsNewlineEdits(t *testing.T) {
 		}
 	}
 }
+
+// Two insertions at one point of a file both survive, in an order picked by
+// content; over an EMPTY ancestor the point is the whole file, and two
+// different bodies there are two documents, never spliced into one.
+func TestSamePointInsertions(t *testing.T) {
+	for _, c := range []struct {
+		name, base, a, b, want string
+		ok                     bool
+	}{
+		{"inside a file: both kept", "a\nc\n", "a\nFROM-A\nc\n", "a\nFROM-B\nc\n", "a\nFROM-A\nFROM-B\nc\n", true},
+		{"inside a file: one append repeating the other is two appends", "log\n", "log\nx\n", "log\nx\nx\n", "log\nx\nx\nx\n", true},
+		{"empty ancestor: two different bodies", "", "x\n", "y\n", "", false},
+		{"empty ancestor: one body holds the other", "", "a\n", "a\nb\n", "a\nb\n", true},
+		{"empty ancestor: the same body", "", "x\n", "x\n", "x\n", true},
+	} {
+		for _, swap := range []bool{false, true} {
+			x, y := c.a, c.b
+			if swap {
+				x, y = y, x
+			}
+			got, ok := Merge([]byte(c.base), []byte(x), []byte(y))
+			if ok != c.ok || (ok && string(got) != c.want) {
+				t.Errorf("%s: Merge(%q, %q, %q) = %q, %v; want %q, %v", c.name, c.base, x, y, got, ok, c.want, c.ok)
+			}
+		}
+	}
+}
+
+func TestRetainsChanges(t *testing.T) {
+	cases := []struct {
+		name             string
+		base, cand, head string
+		want             bool
+	}{
+		{"T5 append after", "- item 1\n", "- item 1\n- alice\n", "- item 1\n- alice\n- bob\n", true},
+		{"edit elsewhere", "a\nb\nc\nd\n", "a\nB\nc\nd\n", "a\nB\nc\nD\n", true},
+		{"head removed the line", "a\nc\n", "a\nA\nc\n", "a\nc\nB\n", false},
+		{"head rewrote the line", "a\nb\nc\n", "a\nA\nc\n", "a\nZ\nc\n", false},
+		{"head inserted inside span", "a\nd\n", "a\nb\nc\nd\n", "a\nb\nX\nc\nd\n", false},
+		{"deletion kept", "a\nb\nc\n", "a\nc\n", "a\nc\nd\n", true},
+		{"deletion undone", "a\nb\nc\n", "a\nc\n", "a\nb\nc\n", false},
+		{"newline change undone", "a", "a\n", "a", false},
+		{"newline change kept", "a", "a\n", "a\nb\n", true},
+		{"binary", "a\x00", "a\x00b", "a\x00b", false},
+		{"replaced line restored beside it", "a\nb\nc\n", "a\nX\nc\n", "a\nX\nb\nc\n", false},
+		{"replaced line restored before it", "a\nb\nc\n", "a\nX\nc\n", "a\nb\nX\nc\n", false},
+	}
+	for _, c := range cases {
+		if got := RetainsChanges([]byte(c.base), []byte(c.cand), []byte(c.head)); got != c.want {
+			t.Errorf("%s: RetainsChanges = %v, want %v", c.name, got, c.want)
+		}
+	}
+}
diff --git a/internal/webapp/collab_relay.go b/internal/webapp/collab_relay.go
index 2d548779..54ddf68b 100644
--- a/internal/webapp/collab_relay.go
+++ b/internal/webapp/collab_relay.go
@@ -5,6 +5,7 @@ import (
 	"errors"
 	"fmt"
 	"strings"
+	"time"
 
 	goredis "github.com/redis/go-redis/v9"
 	"github.com/reearth/ygo/cluster"
@@ -36,6 +37,19 @@ type CollabConfig struct {
 	Redis string
 }
 
+// How long the relay keeps a room's updates. The retained window is what a
+// process opening the room mid-session replays on top of the last stored
+// state (ydoc/), so it has to outlast the gap between two snapshots
+// that actually landed — a failed write retried with backoff, a lease holder
+// that died and must expire (leaseTTL) before another process writes, an
+// idle room (collabRoomIdleTimeout). ygo's 60s default is shorter than
+// several of those together; a gap past the window is typing no later
+// joiner can see. Vars so a test can shorten them.
+var (
+	collabStreamRetention       = 30 * time.Minute
+	collabStreamMaxLen    int64 = 32768
+)
+
 // ConnectCollab attaches the configured relay. Called at startup, before
 // any room exists, so a Redis that cannot be reached fails the start
 // instead of silently leaving every process alone with its own copy.
@@ -56,9 +70,11 @@ func (s *Server) ConnectCollab(ctx context.Context) error {
 		return fmt.Errorf("collab redis %s: %w", opt.Addr, err)
 	}
 	relay, err := redisrelay.New(client, redisrelay.Config{
-		Transport:     redisrelay.Streams,
-		ChannelPrefix: "bdrive:collab:",
-		StreamPrefix:  "bdrive:collab:stream:",
+		Transport:       redisrelay.Streams,
+		ChannelPrefix:   "bdrive:collab:",
+		StreamPrefix:    "bdrive:collab:stream:",
+		StreamRetention: collabStreamRetention,
+		StreamMaxLen:    collabStreamMaxLen,
 	})
 	if err != nil {
 		return fmt.Errorf("collab redis: %w", err)
diff --git a/internal/webapp/frontend/e2e/concurrent-edit.spec.ts b/internal/webapp/frontend/e2e/concurrent-edit.spec.ts
index f0d91feb..ac0450e2 100644
--- a/internal/webapp/frontend/e2e/concurrent-edit.spec.ts
+++ b/internal/webapp/frontend/e2e/concurrent-edit.spec.ts
@@ -217,10 +217,13 @@ test("a bystander in a shared document does not write the file", async ({ browse
    to refuse and both tests fail on their own "409 was never delivered" guard.
    That is the right outcome for a live room, and it is why these tests must
    run in the other mode: the older-hub / no-websocket-proxy case the retry
-   was kept for. Refusing the upgrade is how a test gets there; the client
-   gives up on the room after UNREACHABLE_MS and mounts solo. */
+   was kept for. An older hub has neither the socket nor the HTTP room route,
+   so both are refused: the editor mounts its buffer once the room stalls
+   (STALLED_MS), its first checkpoint to ycollab/sync is answered 404, and
+   from then on it saves the file itself with If-Match — the solo path. */
 async function forceSolo(page: Page) {
   await page.routeWebSocket(/\/ycollab/, (ws) => ws.close({ code: 1006 }));
+  await page.route("**/ycollab/sync*", (route) => route.fulfill({ status: 404, body: "not found" }));
 }
 
 /* A save refused for a stale base must be retried, not parked.
@@ -257,7 +260,7 @@ test("a save refused for a stale base is retried, not parked beside the file", a
   await forceSolo(page);
   await page.goto(`/${id}/edit/${file}`);
   await page.waitForSelector(".cm-host .cm-content");
-  await page.waitForTimeout(9_500); // past UNREACHABLE_MS: the editor is solo now
+  await page.waitForTimeout(9_500); // well past STALLED_MS: the buffer is mounted and saves itself
 
   // Refuse exactly one save the way a peer winning the race would, then let
   // everything through. The retry must land on the real path.
@@ -335,7 +338,7 @@ test("a save the file has already moved past is dropped, not parked", async ({ p
   await forceSolo(page);
   await page.goto(`/${id}/edit/${file}`);
   await page.waitForSelector(".cm-host .cm-content");
-  await page.waitForTimeout(9_500); // past UNREACHABLE_MS: the editor is solo now
+  await page.waitForTimeout(9_500); // well past STALLED_MS: the buffer is mounted and saves itself
 
   /* Refuse the save, and have the hub's copy be a SUPERSET of what the editor
      is holding — which is what a peer saving a newer state looks like from
diff --git a/internal/webapp/frontend/e2e/solo-handoff.spec.ts b/internal/webapp/frontend/e2e/solo-handoff.spec.ts
index 29113af9..c16af698 100644
--- a/internal/webapp/frontend/e2e/solo-handoff.spec.ts
+++ b/internal/webapp/frontend/e2e/solo-handoff.spec.ts
@@ -1,16 +1,21 @@
 import { test, expect, Page } from "@playwright/test";
 import { login, ADMIN } from "./helpers";
 
-/* An editor that gave up on the co-editing room stays solo, even when the
-   room becomes reachable a moment later.
-
-   Solo means this tab holds its own copy of the file and saves it itself. A
-   provider still retrying underneath would, on its first good handshake,
-   merge the hub's document (built from the same file) into that copy — the
-   whole file twice — or leave the solo surface unbound from a room that
-   now does the saving, so nothing typed after it reaches the file. Either
-   way the check is the stored bytes: the edit is there, and the file's
-   text appears exactly once. */
+/* An editor whose co-editing room is slow to answer lets the user type at
+   once, and joins the room cleanly when it does answer.
+
+   A hub that refuses the socket for a while (a deploy rolling, a proxy that
+   will not upgrade yet) is not an older hub: past STALLED_MS the editor
+   mounts a staging buffer, checkpoints its typing into the room over
+   POST ycollab/sync, and moves onto the shared document once the socket
+   syncs. The danger in that hand-off is the stored bytes: the room's
+   document is built from the same file, so a careless merge writes the
+   whole file twice, and a careless swap drops what was typed before it.
+   Either way the check is the file: every edit is there, and every line of
+   it appears exactly once.
+
+   A hub with no room at all — no socket and no ycollab/sync route — never
+   goes live: the buffer saves the file itself, with If-Match, as solo. */
 
 const PROJECT = "zz-solo-handoff";
 let projectId = "";
@@ -48,7 +53,7 @@ async function source(page: Page, id: string, file: string): Promise {
 
 const count = (hay: string, needle: string) => hay.split(needle).length - 1;
 
-/* Refuse the room until the editor has gone solo, then let it through. */
+/* Refuse the room's socket until allowed, then let it through. */
 async function refuseThenAllow(page: Page): Promise<() => void> {
   let refuse = true;
   await page.routeWebSocket(/ycollab/, (ws) => {
@@ -60,40 +65,93 @@ async function refuseThenAllow(page: Page): Promise<() => void> {
   };
 }
 
-async function waitSoloThenOpen(page: Page, allow: () => void) {
-  await expect(page.locator("#editor-state")).toHaveAttribute("data-collab", "solo", {
-    timeout: 15_000,
-  });
-  allow();
-  // Longer than y-websocket's reconnect backoff: a provider left running
-  // would have completed its handshake by now.
+/* The room stays refused well past STALLED_MS while the user already types,
+   then opens; the editor must reach the live room. */
+async function stallThenOpen(page: Page, allow: () => void) {
   await page.waitForTimeout(4_000);
+  await expect(page.locator("#editor-state")).not.toHaveAttribute("data-collab", "live");
+  allow();
+  await expect(page.locator("#editor-state")).toHaveAttribute("data-collab", "live", {
+    timeout: 20_000,
+  });
 }
 
-test("a solo source editor keeps saving after the room becomes reachable", async ({ page }) => {
-  test.setTimeout(60_000);
+test("a source editor typed into while the room stalled joins it without duplicating or dropping", async ({
+  page,
+}) => {
+  test.setTimeout(90_000);
   await login(page, ADMIN);
   const id = await project(page);
-  const file = `solo-${Date.now()}.md`;
-  const body = "# Solo note\n\nThe one and only paragraph.\n";
+  const file = `stall-${Date.now()}.md`;
+  const body = "# Stalled note\n\nThe one and only paragraph.\n";
   await put(page, id, file, body);
 
   const allow = await refuseThenAllow(page);
   await page.goto(`/${id}/edit/${file}`);
+  // The staging buffer: mounted once the room has stalled, editable at once.
   await page.waitForSelector(".cm-host .cm-content");
-  await waitSoloThenOpen(page, allow);
+  await page.locator(".cm-host .cm-content").click();
+  await page.keyboard.press("ControlOrMeta+End");
+  await page.keyboard.type("Typed while the room was down.");
+  // Checkpointed into the room over HTTP: on the hub before any socket.
+  await expect
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
+    .toContain("Typed while the room was down.");
+
+  await stallThenOpen(page, allow);
 
   await page.locator(".cm-host .cm-content").click();
   await page.keyboard.press("ControlOrMeta+End");
+  await page.keyboard.press("Enter");
   await page.keyboard.type("Typed after the room came back.");
 
   await expect
-    .poll(() => source(page, id, file), { timeout: 10_000, intervals: [250] })
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
     .toContain("Typed after the room came back.");
   const after = await source(page, id, file);
+  expect(count(after, "# Stalled note")).toBe(1);
   expect(count(after, "The one and only paragraph.")).toBe(1);
+  expect(count(after, "Typed while the room was down.")).toBe(1);
+  expect(count(after, "Typed after the room came back.")).toBe(1);
+  await expect(page.locator("#editor-state")).toHaveAttribute("data-collab", "live");
+});
+
+test("an older hub with no room route never goes live and saves without duplicating", async ({ page }) => {
+  test.setTimeout(60_000);
+  await login(page, ADMIN);
+  const id = await project(page);
+  const file = `solo-${Date.now()}.md`;
+  const body = "# Solo note\n\nThe one and only paragraph.\n";
+  await put(page, id, file, body);
+
+  // Neither the socket nor the HTTP room route exists on an older hub.
+  await page.routeWebSocket(/ycollab/, (ws) => ws.close());
+  await page.route("**/ycollab/sync*", (route) => route.fulfill({ status: 404, body: "not found" }));
+  const filePuts: string[] = [];
+  page.on("request", (r) => {
+    if (r.method() === "PUT" && r.url().includes("/upload/content?")) filePuts.push(r.url());
+  });
+
+  await page.goto(`/${id}/edit/${file}`);
+  await page.waitForSelector(".cm-host .cm-content");
+  await page.locator(".cm-host .cm-content").click();
+  await page.keyboard.press("ControlOrMeta+End");
+  await page.keyboard.type("Typed with no room at all.");
+
+  await expect
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
+    .toContain("Typed with no room at all.");
+  // Saved by the tab itself — and it keeps saving: nothing ever goes live.
+  expect(filePuts.length).toBeGreaterThan(0);
+  await page.keyboard.type(" And more.");
+  await expect
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
+    .toContain("Typed with no room at all. And more.");
+  const after = await source(page, id, file);
   expect(count(after, "# Solo note")).toBe(1);
-  await expect(page.locator("#editor-state")).toHaveAttribute("data-collab", "solo");
+  expect(count(after, "The one and only paragraph.")).toBe(1);
+  expect(count(after, "Typed with no room at all. And more.")).toBe(1);
+  await expect(page.locator("#editor-state")).not.toHaveAttribute("data-collab", "live");
 });
 
 const HTML = `
@@ -105,13 +163,13 @@ const HTML = `
 
 `;
 
-test("a solo visual editor neither duplicates nor drops edits once the room is reachable", async ({
+test("a visual editor typed into while the room stalled joins it without duplicating or dropping", async ({
   page,
 }) => {
-  test.setTimeout(60_000);
+  test.setTimeout(90_000);
   await login(page, ADMIN);
   const id = await project(page);
-  const file = `solo-${Date.now()}.html`;
+  const file = `stall-${Date.now()}.html`;
   await put(page, id, file, HTML);
 
   const allow = await refuseThenAllow(page);
@@ -119,18 +177,30 @@ test("a solo visual editor neither duplicates nor drops edits once the room is r
   await page.click("#edit-btn");
   const frame = page.frameLocator("iframe.htmlview");
   await frame.locator("html[data-bd-ready]").waitFor();
-  await waitSoloThenOpen(page, allow);
+  await page.waitForTimeout(3_000); // past STALLED_MS: the staging document is up
 
-  const lead = frame.locator("p.lead");
-  await lead.click();
+  // Typed into the staging document while the socket is still refused.
+  await frame.locator("p.lead").click();
   await page.keyboard.press("End");
   await page.keyboard.type(" Especially EMEA.");
-
   await expect
-    .poll(() => source(page, id, file), { timeout: 10_000, intervals: [250] })
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
     .toContain("Revenue grew steadily. Especially EMEA.");
+
+  await stallThenOpen(page, allow);
+  await frame.locator("html[data-bd-ready]").waitFor();
+
+  await frame.locator("h1").click();
+  await page.keyboard.press("End");
+  await page.keyboard.type(" Q3");
+
+  await expect
+    .poll(() => source(page, id, file), { timeout: 15_000, intervals: [250] })
+    .toContain("

Solo report Q3

"); const after = await source(page, id, file); - expect(count(after, "

Solo report

")).toBe(1); expect(count(after, "")).toBe(1); + expect(count(after, "

Solo report Q3

")).toBe(1); + expect(count(after, "Solo report")).toBe(1); + expect(count(after, "Revenue grew steadily. Especially EMEA.")).toBe(1); expect(count(after, "Revenue grew steadily.")).toBe(1); }); diff --git a/internal/webapp/frontend/src/api/http.ts b/internal/webapp/frontend/src/api/http.ts index 4654e3d5..a613f547 100644 --- a/internal/webapp/frontend/src/api/http.ts +++ b/internal/webapp/frontend/src/api/http.ts @@ -243,7 +243,12 @@ export async function putText( // The user confirmed a save the hub refused for emptying or sharply // shrinking the file (422, upload.go sharpShrink). confirmShrink = false, -): Promise<{ sha?: string }> { + // Outlive the page (a closing tab parking its buffer). Past the browser's + // keepalive cap the request goes as an ordinary one, as syncCollab's does. + keepalive = false, + // `merged`: the hub found the file had moved past `base` and folded this + // body into it three ways (upload.go) — the file is NOT exactly `text`. +): Promise<{ sha?: string; merged?: boolean }> { const r = await fetch(url, { method: "PUT", headers: { @@ -252,9 +257,42 @@ export async function putText( ...(confirmShrink ? { "X-Bdrive-Confirm-Shrink": "1" } : {}), }, body: text, + keepalive: Boolean(keepalive && new TextEncoder().encode(text).byteLength <= KEEPALIVE_MAX_BYTES), }); - if (r.status === 401) toLogin(); + // A page being torn down must not navigate. + if (r.status === 401 && !keepalive) toLogin(); if (!r.ok) await fail(r); trackWrite("PUT", url); - return (await r.json().catch(() => ({}))) as { sha?: string }; + return (await r.json().catch(() => ({}))) as { sha?: string; merged?: boolean }; +} + +/* Write into a file's co-editing room over plain HTTP, for a client that is + not (or not yet) on the room's websocket: either a Yjs update this client's + document holds (queued offline edits), or a text the hub merges three ways + against the room — `base_text` is what the client started from, `text` what + it has now. The hub answers with the room's text and the sha it wrote. + + `keepalive` lets the request outlive the page: it is what a closing tab + uses to hand over edits the socket never got to carry. Browsers cap the + keepalive bodies in flight at 64 KiB and REJECT the fetch outright past it + (a TypeError, so nothing is sent at all), which is why a larger body goes + as an ordinary request instead: it may still finish before the page does. + Deliberately no login bounce — a page being torn down must not navigate. */ +const KEEPALIVE_MAX_BYTES = 60_000; + +export async function syncCollab( + url: string, + payload: { update?: string; base?: string; base_text?: string; text?: string; confirm_shrink?: boolean; peek?: boolean; prior_sent?: string[] }, + keepalive = false, +): Promise<{ sha: string; text: string; merged?: boolean; update?: string }> { + const body = JSON.stringify(payload); + const bodyBytes = new TextEncoder().encode(body).byteLength; + const r = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body, + keepalive: Boolean(keepalive && bodyBytes <= KEEPALIVE_MAX_BYTES), + }); + if (!r.ok) await fail(r); + return (await r.json()) as { sha: string; text: string; merged?: boolean; update?: string }; } diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx index 9373f19e..82aeee37 100644 --- a/internal/webapp/frontend/src/apps/Browser.tsx +++ b/internal/webapp/frontend/src/apps/Browser.tsx @@ -248,6 +248,10 @@ export default function Browser(props: { ); const downloadRef = useRef(null); const printRef = useRef(null); + // "Save the open file now", filled by the editor while editing: Done awaits + // it (briefly) so leaving never strands the last words in a pending save. + // It answers false when the save is waiting on the user (ShrinkDialog). + const editFlushRef = useRef<(() => Promise) | null>(null); const panel = props.panel ?? null; // Sharing is a write — a read-only member sees no Share button rather than @@ -1006,6 +1010,7 @@ export default function Browser(props: { editSource={editSource} me={editorIdentity} commentable={commentsOn} + flushRef={editFlushRef} /> ); if (!commentsOn) return file; @@ -1147,9 +1152,30 @@ export default function Browser(props: { prefetchEditText(qc, apiBase, path); }} title={editing ? "Stop editing" : "Edit this file"} - onClick={() => - navigate(urlForPath(path, project?.id, version, route.full, !editing)) - } + onClick={async () => { + if (!editing) { + navigate(urlForPath(path, project?.id, version, route.full, true)); + return; + } + // Save and leave: the flush gets a moment, never a veto — a + // hub that does not answer must not trap the user in the + // editor. Only a question the user must answer keeps them here. + const target = urlForPath(path, project?.id, version, route.full, false); + const here = window.location.pathname + window.location.search; + let okToLeave = true; + try { + okToLeave = await Promise.race([ + editFlushRef.current?.() ?? Promise.resolve(true), + new Promise((r) => setTimeout(() => r(true), 1_500)), + ]); + } catch { + // The editor's own teardown still sends what it holds. + } + if (!okToLeave) return; // the shrink dialog is open: answer it here + // Somewhere else already (a click elsewhere while saving): stay there. + if (window.location.pathname + window.location.search !== here) return; + navigate(target); + }} > {!editing && } {editing ? "Done" : "Edit"} diff --git a/internal/webapp/frontend/src/components/Editor.tsx b/internal/webapp/frontend/src/components/Editor.tsx index ddbab72f..fdeb2639 100644 --- a/internal/webapp/frontend/src/components/Editor.tsx +++ b/internal/webapp/frontend/src/components/Editor.tsx @@ -238,16 +238,40 @@ export function Editor({ : undefined, onNotice: (m) => toast(m), }), - keymap.of([...completionKeymap, ...foldKeymap, ...defaultKeymap, ...historyKeymap, indentWithTab]), + keymap.of([ + // Save now, not after the idle wait — and never the browser's own + // "Save Page As" dialog. In a live room this hands the hub the room's + // state; clean, it sends nothing. + { + key: "Mod-s", + preventDefault: true, + run: () => { + void file.saveNow(); + return true; + }, + }, + ...completionKeymap, + ...foldKeymap, + ...defaultKeymap, + ...historyKeymap, + indentWithTab, + ]), EditorView.lineWrapping, EditorView.updateListener.of((u) => { if (u.docChanged || u.selectionSet || u.focusChanged) report(u.view); }), ]; let viaRoom = false; + // A plain buffer mounted while the room was slow to answer (onStalled). + // Its typing is checkpointed into the room over HTTP and merged into the + // shared document on sync, when the CRDT-bound editor replaces it. + let staging = false; + // What this editor opened on: the staging buffer's text until one exists. + const openedWith = seed.current; // Without the CRDT there is no shared document to observe, so the save - // timer hangs off CodeMirror's own updates instead. + // timer hangs off CodeMirror's own updates instead — for a solo buffer + // (written to the file) and a staging one (checkpointed into the room). const soloListener = EditorView.updateListener.of((u) => { if (!u.docChanged) return; cb.current.onStateChange?.("dirty"); @@ -257,12 +281,15 @@ export function Editor({ // The fallback surface: the same editor without the Yjs binding, seeded // from the file. Its edits still reach everyone through the ordinary save. - const mountSolo = () => { + const mountSolo = (asStaging = false) => { if (view || !host.current) return; + staging = asStaging; view = new EditorView({ parent: host.current, state: EditorState.create({ - doc: seed.current, + // A staging buffer starts from exactly the text the room join will + // merge it against. + doc: asStaging ? openedWith : seed.current, extensions: [...baseExtensions, meetingExt(), soloListener], }), }); @@ -276,11 +303,25 @@ export function Editor({ // document that already holds either the file's text or the room's — // never to an empty one that would then have text appear underneath it. const mount = () => { - if (view || !host.current) return; + if (!host.current) return; + // Late join: the staging buffer's typing is already in the shared + // document (sharedfile.ts join), so the buffer gives way to the real + // editor, keeping the caret where it was as near as the text allows. + let caret = -1; + if (view && staging) { + if (timer.current) clearTimeout(timer.current); + caret = view.state.selection.main.head; + view.destroy(); + view = null; + staging = false; + } + if (view) return; + const doc = file.collab.text.toString(); view = new EditorView({ parent: host.current, state: EditorState.create({ - doc: file.collab.text.toString(), + doc, + ...(caret >= 0 ? { selection: { anchor: Math.min(caret, doc.length) } } : {}), extensions: [ ...baseExtensions, // The binding: every local edit becomes a Yjs update, every @@ -316,6 +357,9 @@ export function Editor({ // route. Editing is single-writer then — exactly what it was before // co-editing existed — rather than a pane that never appears. onSolo: () => mountSolo(), + // The room is slow (a deploy, a cold start): let the user type now + // rather than stare at a preview. The socket keeps retrying underneath. + onStalled: () => mountSolo(true), onState: (s) => cb.current.onStateChange?.(s), onCollab: (s) => { live.current = s; @@ -325,7 +369,7 @@ export function Editor({ onPeers: (n) => cb.current.onPeers?.(n), onSaved: (t) => cb.current.onSaved?.(t), onWriting: () => cb.current.onWriting?.(), - soloText: () => view?.state.doc.toString() ?? "", + soloText: () => (view ? view.state.doc.toString() : openedWith), // No CRDT to splice into, so the outside write goes straight into // CodeMirror — which maps the cursor through it for free. soloApply: (e) => view?.dispatch({ changes: e }), diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx index 0ab1918b..d0e87b43 100644 --- a/internal/webapp/frontend/src/components/FileView.tsx +++ b/internal/webapp/frontend/src/components/FileView.tsx @@ -130,6 +130,11 @@ export function FileView(props: { // An HTML file renders its commentable variant (comments.go's ?comment=1), // which carries the bootstrap Comments.tsx talks to. commentable?: boolean; + // Filled while editing with "save the open file now": what Done awaits + // before it leaves, so the last words are on the hub, not a pending idle + // timer or room snapshot. False: the save is waiting on a question to the + // user (a sharp shrink), which leaving would withdraw unanswered. + flushRef?: { current: (() => Promise) | null }; }) { const { apiBase, path, version, onMeta } = props; const fileURL = fileURLFor(apiBase, path, version); @@ -505,6 +510,21 @@ function EditView(props: Parameters[0]) { void qc.invalidateQueries({ queryKey: ["text", fileURL] }); void qc.invalidateQueries({ queryKey: ["render", apiBase, path] }); }; + const { flushRef } = props; + useEffect(() => { + if (!flushRef) return; + const flush = async () => { + const f = fileHandle.current; + await f?.saveNow(); + void qc.invalidateQueries({ queryKey: ["render", apiBase, path] }); + void qc.invalidateQueries({ queryKey: ["text", fileURL] }); + return !f?.askingShrink(); + }; + flushRef.current = flush; + return () => { + if (flushRef.current === flush) flushRef.current = null; + }; + }, [flushRef, qc, apiBase, path, fileURL]); // Co-editors in this document right now. A write while somebody else is in // the room is their snapshot of the document I already have — warning about // it would fire on every co-editing save. Alone, the same event means @@ -704,6 +724,7 @@ function EditView(props: Parameters[0]) { }} me={props.me} onRendered={props.onRendered} + handle={fileHandle} /> ) ) : !Editor ? ( diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index d1fbe7b7..d29562ae 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import * as Y from "yjs"; -import { openSharedFile, type SaveState } from "../lib/sharedfile"; +import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile"; +import { diffSplices, merge3 } from "../lib/merge3"; import { type CollabStatus } from "../lib/collab"; import { askShrink, withdrawShrink } from "./ShrinkDialog"; @@ -65,6 +66,7 @@ export function VisualEdit({ onSaved, onWriting, onRendered, + handle, }: { apiBase: string; fileURL: string; @@ -79,6 +81,8 @@ export function VisualEdit({ onSaved?: (text: string) => void; onWriting?: () => void; onRendered?: () => void; + // The open file, for a caller that must save it now (EditView's Done). + handle?: { current: SharedFile | null }; }) { const frame = useRef(null); const [warning, setWarning] = useState(null); @@ -135,6 +139,9 @@ export function VisualEdit({ corrupts a document in the field. */ let ranges: Span[] | null = null; let docReady = false; + let stageDoc: Y.Doc | null = null; + let stageTimer: ReturnType | undefined; + const STAGE_IDLE_MS = 700; setArmed(false); setStuck(false); @@ -169,28 +176,66 @@ export function VisualEdit({ // Nothing to mount either way: the surface is the iframe, which is // already on screen. The room is joined for the CRDT alone. onReady: () => { + clearTimeout(stageTimer); + stageTimer = undefined; + if (stageDoc) { + const prev = stageDoc; + stageDoc = null; + const prevText = prev.getText("body").toString(); + const nextText = file.collab.text.toString(); + if (anchored && prevText === nextText) { + for (const [k, a] of anchors) { + const f = Y.createAbsolutePositionFromRelativePosition(a.from, prev); + const t = Y.createAbsolutePositionFromRelativePosition(a.to, prev); + if (f && t) { + anchors.set(k, { + from: Y.createRelativePositionFromTypeIndex(file.collab.text, f.index), + to: Y.createRelativePositionFromTypeIndex(file.collab.text, t.index), + span: a.span, + orig: a.orig, + }); + } + } + } else { + anchors.clear(); + anchored = false; + if (prevText !== nextText) setGen((g) => g + 1); + } + prev.destroy(); + } docReady = true; void anchorRanges(); }, onSolo: () => { - // No relay, so no room and no peer that could double-seed it: the - // provider is stopped before this runs and cannot later hand this - // document the hub's copy of the same bytes. Filling - // the document locally keeps ONE code path for splicing instead of a - // second plain-string one that would only ever run on an older hub. if (!file.collab.text.length) { file.collab.text.insert(0, seed.current); } docReady = true; void anchorRanges(); }, + onStalled: () => { + if (docReady || stageDoc) return; + stageDoc = new Y.Doc(); + stageDoc.getText("body").insert(0, seed.current); + docReady = true; + void anchorRanges(); + }, onState: (s) => cb.current.onStateChange?.(s), onCollab: (s) => cb.current.onCollab?.(s), onPeers: (n) => cb.current.onPeers?.(n), onSaved: (t) => cb.current.onSaved?.(t), onWriting: () => cb.current.onWriting?.(), - soloText: () => seed.current, + soloText: () => (stageDoc ? stageDoc.getText("body").toString() : seed.current), + soloApply: ({ from, to, insert }) => { + if (!stageDoc) return; + stageDoc.transact(() => { + const t = stageDoc!.getText("body"); + if (to > from) t.delete(from, to - from); + if (insert) t.insert(from, insert); + }); + }, })); + if (handle) handle.current = file; /* Ranges are held as RELATIVE positions, not offsets. @@ -204,7 +249,10 @@ export function VisualEdit({ // be sanity-checked before anything is deleted (see the splice below). const anchors = new Map< string, - { from: Y.RelativePosition; to: Y.RelativePosition; span: number } + // `orig`: the source the iframe's element was last rendered from (the + // stamped bytes, then each patch this side applied) — the base a patch + // and a co-editor's typing in the same element are merged against. + { from: Y.RelativePosition; to: Y.RelativePosition; span: number; orig: string } >(); const key = (s: Span) => s.start + "," + s.end; @@ -229,7 +277,8 @@ export function VisualEdit({ resolved to the same empty span, which became from=0 to=end once the document filled, and the first patch replaced THE WHOLE FILE with one paragraph. The guard has to look at the thing being measured. */ - const text = file.collab.text.toString(); + const activeYText = stageDoc ? stageDoc.getText("body") : file.collab.text; + const text = activeYText.toString(); if (!text) return; // nothing to anchor into yet — try again on the next update // A range that runs past the end cannot belong to this document. Cheap, // and it fails closed on any future way the two could drift apart. @@ -257,9 +306,10 @@ export function VisualEdit({ anchors.clear(); for (const s of ranges) { anchors.set(key(s), { - from: Y.createRelativePositionFromTypeIndex(file.collab.text, s.start), - to: Y.createRelativePositionFromTypeIndex(file.collab.text, s.end), + from: Y.createRelativePositionFromTypeIndex(activeYText, s.start), + to: Y.createRelativePositionFromTypeIndex(activeYText, s.end), span: s.end - s.start, + orig: text.slice(s.start, s.end), }); } anchored = true; @@ -296,6 +346,35 @@ export function VisualEdit({ if (msg.type !== "bd-edit:patch") return; const a = anchors.get(key(msg)); if (!a) return; // a range from a render this side has already replaced + if (stageDoc) { + const sFrom = Y.createAbsolutePositionFromRelativePosition(a.from, stageDoc); + const sTo = Y.createAbsolutePositionFromRelativePosition(a.to, stageDoc); + if (!sFrom || !sTo || sFrom.index > sTo.index) return; + const sText = stageDoc.getText("body"); + const sSpan = sTo.index - sFrom.index; + const sWhole = sFrom.index === 0 && sTo.index === sText.length; + if ((sWhole && a.span < sText.length) || sSpan > a.span * 4 + 256) { + anchors.clear(); + anchored = false; + setGen((g) => g + 1); + return; + } + const sLive = sText.toString().slice(sFrom.index, sTo.index); + const sMerged = merge3(a.orig, sLive, msg.html); + const sWant = sMerged.ok ? sMerged.text : msg.html; + a.orig = msg.html; + if (sLive === sWant) return; + stageDoc.transact(() => { + for (const s of diffSplices(sLive, sWant)) { + if (s.deleteCount > 0) sText.delete(sFrom.index + s.index, s.deleteCount); + if (s.insertText) sText.insert(sFrom.index + s.index, s.insertText); + } + }); + cb.current.onStateChange?.("dirty"); + clearTimeout(stageTimer); + stageTimer = setTimeout(() => void file.saveNow(), STAGE_IDLE_MS); + return; + } const doc = file.collab.doc; const from = Y.createAbsolutePositionFromRelativePosition(a.from, doc); const to = Y.createAbsolutePositionFromRelativePosition(a.to, doc); @@ -331,13 +410,23 @@ export function VisualEdit({ return; } - if (text.toString().slice(from.index, to.index) === msg.html) return; - // One transaction, so peers see the replacement rather than a delete - // followed by a moment of missing content. - doc.transact(() => { - text.delete(from.index, span); - text.insert(from.index, msg.html); - }); + const live = text.toString().slice(from.index, to.index); + /* Only the characters that changed, not the whole element. A co-editor + typing elsewhere in the same paragraph is in `live` but not in the + patch, which the iframe built from what it last rendered — replacing + the span wholesale erased their keystrokes. So: their change + (live − orig) and ours (html − orig), merged three ways; where they + collide on the same words the patch wins, as it always did. */ + const merged = merge3(a.orig, live, msg.html); + const want = merged.ok ? merged.text : msg.html; + a.orig = msg.html; + if (live === want) return; + // Splices run last-first in `live` coordinates, so shifting by the + // span's start keeps every one valid. One transaction, so peers see one + // change rather than a moment of missing content. + file.collab.applySplices( + diffSplices(live, want).map((s) => ({ ...s, index: s.index + from.index })), + ); }; // The document filling in is itself a reason to try anchoring again: the @@ -348,8 +437,10 @@ export function VisualEdit({ window.addEventListener("message", onMessage); return () => { + if (handle?.current === file) handle.current = null; clearTimeout(retryTimer); clearTimeout(stuckTimer); + clearTimeout(stageTimer); file.collab.text.unobserve(retry); /* Torn down a beat later, so a patch already in flight still lands. @@ -365,7 +456,9 @@ export function VisualEdit({ browsers. */ setTimeout(() => { window.removeEventListener("message", onMessage); + clearTimeout(stageTimer); file.destroy(); + stageDoc?.destroy(); }, 300); }; // The document, and the render generation. Not the callbacks: they are diff --git a/internal/webapp/frontend/src/lib/collab.ts b/internal/webapp/frontend/src/lib/collab.ts index 42a2ab9a..83d646fc 100644 --- a/internal/webapp/frontend/src/lib/collab.ts +++ b/internal/webapp/frontend/src/lib/collab.ts @@ -1,6 +1,7 @@ import * as Y from "yjs"; import { WebsocketProvider } from "y-websocket"; import { Awareness } from "y-protocols/awareness"; +import type { Splice } from "./merge3"; /* A Yjs document, held by the hub. @@ -23,10 +24,15 @@ import { Awareness } from "y-protocols/awareness"; `awareness`, `peerCount`, `connect`, `destroy`), so swapping the transport underneath them changed almost nothing above. */ -// "solo": the room was given up on for the life of this editor (see stop()); -// the file is saved by this client alone and nothing will ever go live. +// "solo": this server has no room route at all (see stop()); the file is +// saved by this client alone and nothing will ever go live. A room that is +// merely SLOW never becomes solo: the provider keeps retrying for the life of +// the editor, and the caller hears about the wait through onStalled. export type CollabStatus = "connecting" | "live" | "offline" | "solo"; +// The origin of a hub update that arrived over HTTP before the socket existed. +const HTTP_REMOTE = Symbol("collab-http-remote"); + export class CollabDoc { readonly doc = new Y.Doc(); readonly text: Y.Text; @@ -35,6 +41,7 @@ export class CollabDoc { private ws: WebsocketProvider | null = null; private closed = false; private reached = false; + private stallTimer: ReturnType | null = null; // Where each OTHER participant's caret sits, by name, as an index into the // text. A method rather than a helper beside the editor, so a caller that @@ -55,13 +62,17 @@ export class CollabDoc { private readonly url: string, private readonly onStatus: (s: CollabStatus) => void, private readonly onReady: () => void, - // Called when the document cannot be reached at all — an older hub with - // no such route, or a proxy that will not upgrade a websocket. The editor - // still opens and still saves; what it loses is LIVE collaboration, not - // the ability to write. That is deliberately not a second CRDT path: a - // client editing its own copy of a shared document is how two browsers - // came to overwrite each other. - private readonly onUnavailable: () => void, + // Called once when the first handshake has not finished after + // STALLED_MS — a deploy rolling, a cold start, a proxy that will not + // upgrade. Advisory only: the provider is NOT torn down, it keeps + // reconnecting, and when it does get through onReady fires as usual. The + // caller may let the user type in the meantime and hand that typing to + // the hub over HTTP (sharedfile.ts, staging). + // + // This used to be onUnavailable, which ended the transport for good after + // 8s: a room that answered at 8.6s was never joined, and the editor wrote + // its own copy against everybody else's for the rest of the session. + private readonly onStalled: () => void, private readonly me?: { name: string; colour: string }, ) { this.text = this.doc.getText("body"); @@ -131,34 +142,54 @@ export class CollabDoc { this.onReady(); } }); - /* A connection that never succeeds has to be reported, or the editor - waits forever for a document that is not coming. y-websocket retries on - its own — which is right, a flaky network should heal — so this asks - only once, well past the first few attempts. */ - setTimeout(() => { - // Once reached, a later drop is a reconnect to wait out, never solo: - // the editor is already bound to this document. + /* A slow first handshake is reported, never acted on here. y-websocket + retries on its own — which is right, a flaky network should heal — and + this document stays EMPTY until the hub's arrives: nothing local is + ever written into it before "sync", so joining late can never merge a + locally built copy of the file with the hub's and double the text. */ + this.stallTimer = setTimeout(() => { + this.stallTimer = null; if (this.closed || this.reached) return; - this.stop(); - this.onUnavailable(); - }, UNREACHABLE_MS); + this.onStalled(); + }, STALLED_MS); } - /* Give up on the room for good, keeping the document. - - A solo editor edits its own copy. If the provider were left retrying, a - handshake that finally succeeded would merge the hub's document — built - from the same file — with that copy, and every character the two share - would be in the result twice. So the transport goes before anything - local is written, and nothing after this can bring it back. */ + /* There is no room to join: the server has no such route at all (a + single-volume server). Never called for a room that is merely slow. */ stop() { if (this.closed) return; this.closed = true; + if (this.stallTimer) clearTimeout(this.stallTimer); this.ws?.destroy(); this.ws = null; this.onStatus("solo"); } + /* This document's whole state as one Yjs update, base64: what a client that + cannot reach the socket hands the hub over HTTP. Applying it to the room + is idempotent — whatever the room already holds is not added twice. */ + encodeState(): string { + const u8 = Y.encodeStateAsUpdate(this.doc); + let bin = ""; + for (let i = 0; i < u8.length; i += 0x8000) { + bin += String.fromCharCode(...u8.subarray(i, i + 0x8000)); + } + return btoa(bin); + } + + /* Apply splices (lib/merge3.ts diffSplices: old-text coordinates, last + first) in one transaction, so peers see one change and every character + outside them keeps its identity. */ + applySplices(splices: Splice[]) { + if (!splices.length) return; + this.doc.transact(() => { + for (const s of splices) { + if (s.deleteCount) this.text.delete(s.index, s.deleteCount); + if (s.insertText) this.text.insert(s.index, s.insertText); + } + }); + } + /* Did this change come from the hub, or from the person at this keyboard? Yjs stamps every transaction with an origin, and y-websocket applies what @@ -171,7 +202,20 @@ export class CollabDoc { provider, so testing against the provider identifies remote changes precisely rather than guessing at the local ones. */ isRemote(origin: unknown): boolean { - return this.ws !== null && origin === this.ws; + return origin === HTTP_REMOTE || (this.ws !== null && origin === this.ws); + } + + /* Apply a Yjs update the hub answered over HTTP (ycollab/sync's `update`: + the room's state with a staging checkpoint in it). It carries the room's + own item IDs, so applying it is idempotent with the same items arriving + on the socket — before or after — and a join that follows splices only + what the room does not hold yet. Stamped remote: it is the hub's change, + never a keystroke here. */ + applyRemoteUpdate(b64: string): void { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + Y.applyUpdate(this.doc, bytes, this.ws ?? HTTP_REMOTE); } /* How many OTHER editors are in this document right now, from awareness. @@ -185,6 +229,7 @@ export class CollabDoc { destroy() { this.closed = true; + if (this.stallTimer) clearTimeout(this.stallTimer); this.ws?.destroy(); this.ws = null; this.awareness.destroy(); @@ -192,7 +237,7 @@ export class CollabDoc { } } -// How long to let the provider retry before telling the caller the document -// is unreachable. Long enough to cover a reconnect on a bad network, short -// enough that a hub without the route does not leave an editor waiting. -const UNREACHABLE_MS = 8_000; +// How long the first handshake may take before the caller is told the room is +// slow. Short, because nothing is given up when it fires: the user just gets +// a buffer to type into while the provider keeps trying. +const STALLED_MS = 2_500; diff --git a/internal/webapp/frontend/src/lib/merge3.ts b/internal/webapp/frontend/src/lib/merge3.ts new file mode 100644 index 00000000..e202d0bf --- /dev/null +++ b/internal/webapp/frontend/src/lib/merge3.ts @@ -0,0 +1,376 @@ +/* Three-way text merge and minimal splices. Pure, no dependency. + + merge3(base, a, b) folds two versions that both started from `base` into + one, or says it cannot. It is what lets an editor that is NOT in the live + room (solo, or still waiting for the room to answer) take somebody else's + write without either refusing it or overwriting its own unsaved typing. + + Three granularities, each tried only where the coarser one collided: + + lines -> Myers O(ND) over lines; disjoint hunks anywhere in the file + merge, identical hunks are emitted once. + tokens -> the same algorithm over words / whitespace runs / single + punctuation, inside a line-level collision only. + chars -> used only to recognise one side CONTINUING the other's + insertion ("x" -> "xA" vs "x" -> "xAB"); a char-level + collision is never resolved any other way. + + Two insertions at the same anchor are deduplicated when one already holds + the other at its start or end (the same keystrokes reaching us twice), and + otherwise concatenated in codepoint order, so the result does not depend on + which side is called `a`: merge3(base, a, b) === merge3(base, b, a). + + { ok: false } is the honest answer only for the same token changed two + different ways. */ + +export type Merge3Result = { ok: true; text: string } | { ok: false }; + +export type Splice = { index: number; deleteCount: number; insertText: string }; + +type Hunk = { aS: number; aE: number; bS: number; bE: number }; + +// Beyond this many edit steps Myers' trace grows quadratically; past it the +// changed middle is reported as one hunk instead (still correct, coarser). +const MAX_D = 4_000; + +/* Myers' greedy O((N+M)·D) shortest edit script, as hunks of [aS,aE) in `a` + replaced by [bS,bE) of `b`. Inputs are interned ids, so a comparison is an + integer compare whatever the token. */ +function myers(a: Int32Array, b: Int32Array): Hunk[] { + let p = 0; + while (p < a.length && p < b.length && a[p] === b[p]) p++; + let s = 0; + while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s]) s++; + const n = a.length - p - s; + const m = b.length - p - s; + if (n === 0 && m === 0) return []; + if (n === 0 || m === 0) return [{ aS: p, aE: p + n, bS: p, bE: p + m }]; + const A = a.subarray(p, p + n); + const B = b.subarray(p, p + m); + + const max = Math.min(n + m, MAX_D); + const trace: Int32Array[] = []; + let found = -1; + for (let d = 0; d <= max && found < 0; d++) { + const prev = d > 0 ? trace[d - 1] : null; + const v = new Int32Array(2 * d + 1); + for (let k = -d; k <= d; k += 2) { + let x: number; + if (d === 0) x = 0; + else if (k === -d || (k !== d && prev![k - 1 + d - 1] < prev![k + 1 + d - 1])) x = prev![k + 1 + d - 1]; + else x = prev![k - 1 + d - 1] + 1; + let y = x - k; + while (x < n && y < m && A[x] === B[y]) { + x++; + y++; + } + v[k + d] = x; + if (x >= n && y >= m) { + found = d; + break; + } + } + trace.push(v); + } + if (found < 0) return [{ aS: p, aE: p + n, bS: p, bE: p + m }]; + + // Walk back collecting the matched diagonals, then report the gaps. + const matches: number[] = []; // pairs (x, y), reversed + let x = n; + let y = m; + for (let d = found; d > 0; d--) { + const prev = trace[d - 1]; + const k = x - y; + const pk = k === -d || (k !== d && prev[k - 1 + d - 1] < prev[k + 1 + d - 1]) ? k + 1 : k - 1; + const px = prev[pk + d - 1]; + const py = px - pk; + // The snake after the edit step. + const sx = pk === k + 1 ? px : px + 1; + const sy = pk === k + 1 ? py + 1 : py; + while (x > sx && y > sy) { + x--; + y--; + matches.push(x, y); + } + x = px; + y = py; + } + while (x > 0 && y > 0) { + x--; + y--; + matches.push(x, y); + } + + const out: Hunk[] = []; + let ai = 0; + let bi = 0; + for (let i = matches.length - 2; i >= 0; i -= 2) { + const mx = matches[i]; + const my = matches[i + 1]; + if (mx > ai || my > bi) out.push({ aS: p + ai, aE: p + mx, bS: p + bi, bE: p + my }); + ai = mx + 1; + bi = my + 1; + } + if (ai < n || bi < m) out.push({ aS: p + ai, aE: p + n, bS: p + bi, bE: p + m }); + return out; +} + +// Lines keep their "\n", so joining tokens always reproduces the text exactly. +const LINE_RE = /[^\n]*\n|[^\n]+$/g; +// A word, a whitespace run, or one other character (a surrogate pair is one). +const TOKEN_RE = /\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu; + +const LINES = 0; +const TOKENS = 1; +const CHARS = 2; +type Level = typeof LINES | typeof TOKENS | typeof CHARS; + +function split(text: string, level: Level): string[] { + if (text === "") return []; + if (level === LINES) return text.match(LINE_RE) ?? [text]; + if (level === TOKENS) return text.match(TOKEN_RE) ?? [text]; + return Array.from(text); +} + +function intern(toks: string[], ids: Map): Int32Array { + const out = new Int32Array(toks.length); + for (let i = 0; i < toks.length; i++) { + let id = ids.get(toks[i]); + if (id === undefined) { + id = ids.size; + ids.set(toks[i], id); + } + out[i] = id; + } + return out; +} + +// Codepoint order, not UTF-16 unit order: the two disagree around surrogates, +// and the hub orders the same way (Go compares UTF-8 bytes, which sort as +// codepoints). +function cmpCodepoints(x: string, y: string): number { + const xs = Array.from(x); + const ys = Array.from(y); + const n = Math.min(xs.length, ys.length); + for (let i = 0; i < n; i++) { + const d = xs[i].codePointAt(0)! - ys[i].codePointAt(0)!; + if (d) return d; + } + return xs.length - ys.length; +} + +/* Two insertions at one anchor, matching Go textmerge.Merge. The same text + arriving twice is one insertion. Anything else is both, in an order + neither side gets to pick: one side appending a line the other already + appended is two lines, since only the caller knows whether a write landed. + Over an EMPTY ancestor the anchor is the whole file: a body that begins + with the whole other (at a line boundary) is that file written further, + and two different bodies are two documents, so they conflict. */ +function sameAnchor(x: string, y: string, concat: boolean, emptyBase: boolean): string | null { + if (x === y) return x; + if (emptyBase) { + const extends_ = (long: string, short: string) => + long.startsWith(short) && (short === "" || short.endsWith("\n") || long[short.length] === "\n"); + if (x.length >= y.length && extends_(x, y)) return x; + if (y.length > x.length && extends_(y, x)) return y; + return null; + } + if (!concat) return null; + return cmpCodepoints(x, y) <= 0 ? x + y : y + x; +} + +type Side = { h: Hunk; toks: string[]; side: 0 | 1 }; + +function mergeAt(base: string, a: string, b: string, level: Level): string | null { + if (a === b) return a; + if (a === base) return b; + if (b === base) return a; + + const ids = new Map(); + const bt = split(base, level); + const at = split(a, level); + const btk = split(b, level); + const baseIds = intern(bt, ids); + const all: Side[] = [ + ...myers(baseIds, intern(at, ids)).map((h): Side => ({ h, toks: at, side: 0 })), + ...myers(baseIds, intern(btk, ids)).map((h): Side => ({ h, toks: btk, side: 1 })), + ]; + all.sort((x, y) => x.h.aS - y.h.aS || x.h.aE - y.h.aE || x.side - y.side); + + const join = (toks: string[], s: number, e: number) => toks.slice(s, e).join(""); + // The base region [gs, ge) as one side sees it. + const sideText = (group: Side[], side: 0 | 1, gs: number, ge: number) => { + let out = ""; + let pos = gs; + for (const g of group) { + if (g.side !== side) continue; + out += join(bt, pos, g.h.aS) + join(g.toks, g.h.bS, g.h.bE); + pos = g.h.aE; + } + return out + join(bt, pos, ge); + }; + + let out = ""; + let pos = 0; + let i = 0; + while (i < all.length) { + const group = [all[i]]; + let gs = all[i].h.aS; + let ge = all[i].h.aE; + i++; + // Overlapping base ranges, or two insertions at the same point, collide. + // Merely touching ranges do not: an edit to one line and an edit to the + // next are two separate hunks. + while (i < all.length) { + const h = all[i].h; + const overlaps = h.aS < ge && gs < h.aE; + const sharedAnchor = h.aS === h.aE && gs === ge && h.aS === gs; + const inside = h.aS === h.aE && gs < h.aS && h.aS < ge; + if (!overlaps && !sharedAnchor && !inside) break; + group.push(all[i]); + gs = Math.min(gs, h.aS); + ge = Math.max(ge, h.aE); + i++; + } + out += join(bt, pos, gs); + pos = ge; + const sides = new Set(group.map((g) => g.side)); + if (sides.size === 1) { + out += sideText(group, group[0].side, gs, ge); + continue; + } + const ra = sideText(group, 0, gs, ge); + const rb = sideText(group, 1, gs, ge); + if (ra === rb) { + out += ra; + continue; + } + if (gs === ge) { + const s = sameAnchor(ra, rb, level !== CHARS, bt.length === 0); + if (s === null) return null; + out += s; + continue; + } + if (level === CHARS) return null; + const sub = mergeAt(join(bt, gs, ge), ra, rb, (level + 1) as Level); + if (sub === null) return null; + out += sub; + } + return out + join(bt, pos, bt.length); +} + +/* Lines are merged as Go textmerge.Merge merges them: every line terminated, + and the final newline decided on its own afterwards. A line unit keeps its + "\n", so an unterminated last line would otherwise be glued onto whatever + lands after it — "x" + "x\nx" is "xx\nx", one line where Go has two. */ +const terminated = (s: string) => (s === "" || s.endsWith("\n") ? s : s + "\n"); + +export function merge3(base: string, a: string, b: string): Merge3Result { + const text = mergeAt(terminated(base), terminated(a), terminated(b), LINES); + if (text === null) return { ok: false }; + // The final newline is one more thing a side may change: whichever side + // changed it from the base wins, and both can only change it one way. + let trailing = a.endsWith("\n"); + if (trailing === base.endsWith("\n")) trailing = b.endsWith("\n"); + if (text === "" || trailing === text.endsWith("\n")) return { ok: true, text }; + return { ok: true, text: trailing ? text + "\n" : text.slice(0, -1) }; +} + +/* The splices that turn `oldText` into `newText`, touching as little as + possible: line hunks, refined to token hunks, trimmed to the characters + that actually differ. Every untouched character keeps its identity in a + CRDT, and with it every cursor and remote caret sitting in it. + + Indices are UTF-16 units in OLD-text coordinates and the list runs from the + END of the text backwards, so applying them one after another — to a + Y.Text, a string, or as a CodeMirror change set — never invalidates the + ones still to come. */ +export function diffSplices(oldText: string, newText: string): Splice[] { + if (oldText === newText) return []; + const out: Splice[] = []; + const ids = new Map(); + const ol = split(oldText, LINES); + const nl = split(newText, LINES); + const offs = (toks: string[]) => { + const o = new Array(toks.length + 1); + o[0] = 0; + for (let i = 0; i < toks.length; i++) o[i + 1] = o[i] + toks[i].length; + return o; + }; + const oo = offs(ol); + const no = offs(nl); + for (const h of myers(intern(ol, ids), intern(nl, ids))) { + const oldSeg = oldText.slice(oo[h.aS], oo[h.aE]); + const newSeg = newText.slice(no[h.bS], no[h.bE]); + refine(oldSeg, newSeg, oo[h.aS], out); + } + return out.reverse(); +} + +function refine(oldSeg: string, newSeg: string, at: number, out: Splice[]) { + const ids = new Map(); + const ot = split(oldSeg, TOKENS); + const nt = split(newSeg, TOKENS); + let oi = 0; + let ni = 0; + let oc = 0; + let nc = 0; + for (const h of myers(intern(ot, ids), intern(nt, ids))) { + while (oi < h.aS) oc += ot[oi++].length; + while (ni < h.bS) nc += nt[ni++].length; + let oe = oc; + while (oi < h.aE) oe += ot[oi++].length; + let ne = nc; + while (ni < h.bE) ne += nt[ni++].length; + let del = oldSeg.slice(oc, oe); + let ins = newSeg.slice(nc, ne); + let from = at + oc; + // Trim what the replaced and replacing tokens share at either end. + let p = 0; + while (p < del.length && p < ins.length && del[p] === ins[p]) p++; + let s = 0; + while (s < del.length - p && s < ins.length - p && del[del.length - 1 - s] === ins[ins.length - 1 - s]) s++; + // Never split a surrogate pair. + const hi = p > 0 ? del.charCodeAt(p - 1) : 0; + if (hi >= 0xd800 && hi <= 0xdbff) p--; + const lo = s > 0 ? del.charCodeAt(del.length - s) : 0; + if (lo >= 0xdc00 && lo <= 0xdfff) s--; + from += p; + del = del.slice(p, del.length - s); + ins = ins.slice(p, ins.length - s); + if (del.length || ins.length) out.push({ index: from, deleteCount: del.length, insertText: ins }); + oc = oe; + nc = ne; + } +} + +// Apply splices from diffSplices to a plain string. +export function applySplices(text: string, splices: Splice[]): string { + for (const s of splices) text = text.slice(0, s.index) + s.insertText + text.slice(s.index + s.deleteCount); + return text; +} + +/* Whether `head` still carries every line edit that took `base` to + `candidate`, untouched — textmerge.RetainsChanges, line for line: no later + edit (candidate → head) overlaps a span candidate inserted or rewrote, + inserts inside one, or puts lines back where candidate deleted them, and a + final newline candidate changed is still the way candidate left it. */ +export function retainsChanges(base: string, candidate: string, head: string): boolean { + const ids = new Map(); + const lc = intern(split(candidate, LINES), ids); + const ours = myers(intern(split(base, LINES), ids), lc); + const later = myers(lc, intern(split(head, LINES), ids)); + for (const h1 of ours) { + for (const h2 of later) { + if (h1.bS < h1.bE) { + // A replacement must keep clear even of an abutting edit (the old + // lines going back in beside it); a pure insertion only of its inside. + if (h1.aS < h1.aE ? !(h2.aE < h1.bS || h2.aS > h1.bE) : !(h2.aE <= h1.bS || h2.aS >= h1.bE)) return false; + } else if (h2.bS < h2.bE && h2.aS <= h1.bS && h1.bS <= h2.aE) { + return false; // lines put back where candidate deleted + } + } + } + const nl = (s: string) => s.endsWith("\n"); + return !(nl(candidate) !== nl(base) && nl(head) !== nl(candidate)); +} diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index e8b23fff..d29b7f74 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -1,7 +1,7 @@ import { CollabDoc, type CollabStatus } from "./collab"; import { hasCollabRoute } from "./collabroute"; -import { textEdit } from "./diff"; -import { HttpError, putText } from "../api/http"; +import { diffSplices, merge3, retainsChanges } from "./merge3"; +import { HttpError, putText, syncCollab } from "../api/http"; import { conflictName } from "./conflict"; import { fetchBlobText, fileURLFor } from "../hooks/useBlob"; import { byteLength, sharpShrink } from "./meeting"; @@ -54,12 +54,37 @@ export type ShrinkAsk = { // Idle time before the document is written to the file. export const SAVE_IDLE_MS = 700; +// Backoff between attempts to re-send a save that failed transiently (a 5xx, +// a 429, no answer). The last value repeats while the buffer stays unsaved. +export const SAVE_RETRY_MS = [2_000, 4_000, 8_000, 15_000]; + +// How long edits may sit queued in a document that has lost its socket before +// they are handed to the hub over HTTP instead. +const OFFLINE_FLUSH_MS = 2_000; + +// Consecutive refusals one save may rebase across before its text is parked +// beside the file. A path contended this hard is not a race any more. +const MAX_REBASES = 4; + +// Above this, a staging checkpoint names its ancestor by sha alone when it can +// (the hub reads the blob) instead of carrying it as text. +const INLINE_BASE_MAX = 32_000; + +// How many of a held room's recent texts are remembered, to recognise a +// snapshot of this room coming back through the change stream (merge()). +const SEEN_ROOM_TEXTS = 32; + export type SharedFile = { readonly collab: CollabDoc; /** Text as it stands, whether the relay ever answered or not. */ current(): string; - /** Force a save now, skipping the idle wait. */ + /** Force a save now, skipping the idle wait (Done, Mod-s). In a live room + this hands the hub the room's state only when this tab has typing no + snapshot carries yet; clean or a bystander, it sends nothing. */ saveNow(): Promise; + /** A shrink question is waiting on the user: leaving now would leave it + unanswered (Done stays on the editor). */ + askingShrink(): boolean; /** Fold an outside write — an agent, a CLI, another device — into the open document. "blocked" means the caller should SAY so instead, because this refused to resolve it. `held` says the hub has already put this text @@ -75,10 +100,11 @@ export type SharedFile = { destroy(): void; }; -export function openSharedFile(opts: { +export type SharedFileOptions = { apiBase: string; path: string; - /** The file's current bytes, used only if this client seeds the room. */ + /** The file's current bytes: what a surface typing before the room answers + starts from, and the base its typing is merged against when it does. */ seed: string; /** The version those bytes ARE (the read's ETag). Every save says it was built on this, so the hub can refuse one that would erase a write that @@ -100,16 +126,24 @@ export function openSharedFile(opts: { answer runs after destroy — both are no-ops on a closed file. */ onShrinkWithdrawn?: (ask: ShrinkAsk) => void; /** Local edits made while the room is not live: they are queued in this - tab's document and merge when the socket comes back. 0 once it has. */ + tab's document and merge when the socket comes back (or are handed to + the hub over HTTP if it stays away). 0 once they have. */ onPending?: (n: number) => void; me?: { name: string; colour: string }; - /** The document arrived: it is live and holds the truth. */ + /** The document arrived: it is live and holds the truth. Called again on + every reconnect. Anything typed into a staging surface before it has + already been merged into `collab.text` when this runs. */ onReady: (collab: CollabDoc) => void; - /** The document could not be reached — an older hub, or a proxy that will - not upgrade a websocket. The caller falls back to single-writer editing: - the editor still opens and still saves, it just has no live - collaboration. Deliberately NOT a second CRDT path. */ + /** The server has no co-editing room at all (a single-volume server). The + caller edits a buffer of its own and this file saves it with If-Match, + rebasing over other writers three ways. Never called for a room that is + merely slow — see onStalled. */ onSolo: () => void; + /** The room has not answered yet and is still being retried. The caller + MAY mount a staging surface over `seed` (soloText/soloApply, saveNow on + idle): its typing is checkpointed into the room over HTTP and merged + into the shared document the moment the socket syncs. */ + onStalled?: () => void; onState?: (s: SaveState) => void; onCollab?: (s: CollabStatus) => void; onPeers?: (n: number) => void; @@ -120,94 +154,498 @@ export function openSharedFile(opts: { that only learns about its own write afterwards will see its own save arrive as if a stranger had made it. */ onWriting?: () => void; - /** Text to save when the relay never answered, so there is no CRDT to read - it from. The solo surface owns its own buffer. */ + /** The caller's own buffer while there is no shared document under it + (solo, or staging before the room answers). Must return `seed` while + nothing has been typed. */ soloText?: () => string; - /** Apply a merged-in outside write to that same solo buffer. Without it a - relay-less surface cannot take one, and merge() says so rather than - claiming a change it could not make. */ + /** Apply a merged-in change to that same buffer. Without it a relay-less + surface cannot take one, and merge() says so rather than claiming a + change it could not make. */ soloApply?: (e: { from: number; to: number; insert: string }) => void; -}): SharedFile { +}; + +/* Three ways to be connected, and what writes the file in each: + + - hub-held (`hubHoldsIt`): the socket synced at least once. The hub is the + ONLY writer (ycollab.go). Edits made while the socket is down queue in + the Y.Doc and, if it stays down, are handed over as a Yjs update on + POST ycollab/sync — never as a PUT that would race the hub's own write. + - staging: the room has a route but has not answered yet. Nothing goes + into the Y.Doc (a locally built copy of the file merged with the hub's + would hold every character twice); the caller's buffer is checkpointed + into the room as TEXT over POST ycollab/sync, and three-way merged into + the shared document the moment the socket syncs. + - solo: no room route at all. The file is written with If-Match by a + single-flight loop that rebases over other writers with merge3, and + parks a conflict copy only for a genuine same-token conflict. */ +export function openSharedFile(opts: SharedFileOptions): SharedFile { + /* The text `base` names: the last version of the file this buffer is known + to be built on. Every local change is (buffer − saved); every outside + write is (next − saved). That is what makes a three-way merge possible. */ let saved = opts.seed; let base = opts.baseSha; - /* The texts of writes that have left but not landed. - - A SET, not a slot: a second idle timer can fire while the first PUT is - still out — type, pause, type again on a slow link — and a single slot - would forget the earlier write exactly when its own refetch arrives. That - is not hypothetical, it is what the first version of this fix did, and - the e2e caught it. - - `saved` only moves when a PUT RESOLVES, and the hub announces a write the - moment it journals it — so the change frame, and the refetch it triggers, - routinely beat our own response back. Without this, that refetch looked - like a stranger's write: merge() saw text that matched neither `saved` - nor a buffer we had typed further into, and raised "someone else changed - this file" over the user's own save. It also stops a second idle timer - re-sending bytes that are already on their way, which is how two - byte-identical PUTs 4.5s apart ended up in one user's history. */ - const inFlight = new Set(); + /* Only two texts are ever "ours" and so never merged back in: `saved`, the + version the buffer is built on, and `inFlightSentText`, the one save on + the wire right now (its echo through the change stream routinely beats + the response back). Nothing older is remembered: a text this client once + wrote can come back legitimately — a History restore from B back to A — + and must then be merged like any other outside write. */ + const adopt = (text: string, sha?: string) => { + saved = text; + savedSha = sha; + rebase(sha); + // Only room states NEWER than `saved` stay recognisable as this room's + // own past; a text not among them (an outside write, a restore) leaves + // nothing older to match. + const idx = seenRoomTexts.lastIndexOf(text); + if (idx >= 0) seenRoomTexts.splice(0, idx + 1); + else seenRoomTexts.length = 0; + }; + /* The sha known to spell exactly `saved` — `base` can move on its own (a + co-editor's save learned from the change stream). When the two agree the + hub can read the ancestor itself, so a large one is not sent: the request + stays small enough for a keepalive on the way out, and half the bytes. */ + let savedSha: string | undefined = opts.baseSha; + const priorSentList = (head: Ambiguous | null): string[] | undefined => { + if (!head) return undefined; + const out: string[] = []; + for (let c: Ambiguous | null = head; c !== null && out.length < 4; c = c.prev) { + if (c.sent !== c.from && !out.includes(c.sent)) out.push(c.sent); + } + return out.length ? out : undefined; + }; + const roomPayload = (text: string, prior: Ambiguous | null = ambiguousRoomCheckpoint) => { + const prior_sent = priorSentList(prior); + return savedSha && savedSha === base && saved.length > INLINE_BASE_MAX + ? { base, text, ...(prior_sent ? { prior_sent } : {}) } + : { base, base_text: saved, text, ...(prior_sent ? { prior_sent } : {}) }; + }; + + let solo = false; + // The room route answered 404/405 to an HTTP checkpoint: an older hub. + // Staging then saves like solo, with If-Match. + let noRoomHttp = false; + let hubHoldsIt = false; + let live = false; + let gone = false; + let pending = 0; + let finalText: string | null = null; + /* A late join whose buffer conflicts with the room: the buffer is the only + copy of those words until its conflict copy lands, so it stays the text + (and the editor stays on it) until then. See join(). */ + let pendingJoin = false; + let joining = false; // a park of the buffer is on the wire + /* join() is waiting for a staging checkpoint on the wire to land before it + reads the buffer and the room: the save loop sends nothing more, so the + join is the only thing that hands the rest of the buffer to the room. */ + let waitingToJoin = false; + let parkedName: string | null = null; + let parkedText: string | null = null; // what `parkedName` was minted for + /* Every conflict copy this file opens gets a name no other copy from it + has had: conflictName stamps whole UTC seconds, so each name is minted + at least a second after the last. Two parks on the wire at once — a + staging checkpoint's and a join's, or either and a teardown — can then + never share a path, and a slow older PUT can never land over a newer + one. A name is reused only to retry the same text. */ + let lastConflictMs = 0; + const mintConflictPath = (now = Date.now()): string => { + const ms = Math.max(now, lastConflictMs + 1000); + lastConflictMs = ms; + return conflictName(opts.path, opts.who || "browser", new Date(ms)); + }; + // The conflict copies whose PUT is on the wire right now, and what each holds. + const conflictPuts = new Map(); + // Bumped per park: only the newest park moves `saved` when it lands. + let conflictSeq = 0; + /* A staging checkpoint the room refused for a genuine clash, whose buffer + has not durably landed as a conflict copy yet. Sending it to the room + again on the way out would only be refused again: destroy() parks it. */ + let stagingConflict = false; + let joinTimer: ReturnType | null = null; + let joinAttempt = 0; + let readyWaiting = false; // the room synced; onReady waits for the join + /* A staging checkpoint whose outcome is unknown: it failed in a way (5xx, + 429, 422, no answer) that may come after the hub already put `sent` into + the room's document. Until a peek or a later checkpoint settles it, a + join cannot know whether the room holds `sent` — and guessing "not" would + splice its lines in a second time under fresh item IDs. See join(). + `from` is the ancestor it was sent against (`saved` then); `prev` is an + earlier checkpoint still unsettled when this one went out, since a later + one that never reached the room says nothing about it. */ + type Ambiguous = { sent: string; from: string; prev: Ambiguous | null }; + let ambiguousRoomCheckpoint: Ambiguous | null = null; + // Set when a peek confirms an ambiguous checkpoint is in room memory while + // its durable write had failed: saveLoop must still call syncCollab to flush + // storage even when `current() === saved`. + let roomNeedsFlush = false; + + /* A held room's file is a PAST state of the document by the time anybody + reads it: with eight people typing, every snapshot the hub writes is + behind the room the moment it lands. `seenRoomTexts` remembers, oldest + first, the texts this room has held SINCE `saved` (every change, ours or + a peer's), so a snapshot coming back through the change stream is + recognised as our own history rather than refused as an outside write. + adopt() drops everything up to the adopted text, so a restore to a state + from before `saved` is never mistaken for one. Bounded: a snapshot older + than this still passes when the room carries every edit it made. */ + const seenRoomTexts: string[] = []; + const seeRoomText = (t: string) => { + if (seenRoomTexts.at(-1) === t) return; + seenRoomTexts.push(t); + if (seenRoomTexts.length > SEEN_ROOM_TEXTS) seenRoomTexts.shift(); + }; + /* Typing in a held room that no snapshot is known to carry yet — what an + explicit save (Done, Mod-s) or a closing tab still has to hand the hub. + `lastLocalRoomText` is the room's text after the latest such edit; + `localRoomSeq` counts those edits, so a request that settles can tell + whether anything was typed while it was out. */ + let localDirtyInRoom = false; + let lastLocalRoomText: string | null = null; + let localRoomSeq = 0; + const roomCaughtUp = () => { + localDirtyInRoom = false; + lastLocalRoomText = null; + }; + // Settled a request that carried every local edit up to `sentSeq`. + const roomHandedOver = (sentSeq: number) => { + if (localRoomSeq === sentSeq) roomCaughtUp(); + }; + /* Edits made while a held room's socket is down, as watermarks rather than + a count: `offlineEditSeq` numbers every one, `offlineAckedSeq` is the + newest the hub has confirmed. Two flushes settling in any order can only + move the acknowledgement forward — never subtract the same edits twice. */ + let offlineEditSeq = 0; + let offlineAckedSeq = 0; + let offlineFlushing: Promise | null = null; + + /* Single-flight. At most one write is ever on the wire: a second idle timer + firing while one is out only marks the buffer dirty, and the loop sends + the latest text when the first lands — rebased onto whatever it learned. + Two writes in flight from one buffer are two writes against one base, + and the second is a 409 against our own first. */ + let saving: Promise | null = null; + let dirtyWhileSaving = false; + // The text on the wire, so its own echo through the change stream (which + // routinely beats the response back) is not mistaken for a stranger's. + // Cleared the moment the request settles. + let inFlightSentText: string | null = null; + // An outside write was merged into the buffer while `inFlightSentText` was out. + let disturbed = false; + let timer: ReturnType | null = null; + let offlineTimer: ReturnType | null = null; const setState = (s: SaveState) => opts.onState?.(s); const contentURL = (p: string) => opts.apiBase + "upload/content?path=" + encodeURIComponent(p); + const syncURL = opts.apiBase + "ycollab/sync?path=" + encodeURIComponent(opts.path); - const save = async (text: string) => { - if (inFlight.has(text)) return; // already on its way; its response decides - if (text === saved) { - // Nothing to write IS clean, and saying so matters: seeding the room - // marks the document dirty, and the save it schedules lands here — so - // without this the status line read "unsaved" for the rest of a session - // in which everything had been saved all along. - setState("clean"); - return; + /* A save the network or the hub failed for a moment (a 5xx, a 429, no + answer) is tried again on its own, backing off to a cap, for as long as + the buffer stays unsaved: typing that stopped would otherwise wait for a + next keystroke that may never come. A refusal that cannot change by + waiting (401/403/404/422) is never retried. The next edit's idle timer, + the room going live, and destroy() each cancel it. */ + let retryTimer: ReturnType | null = null; + let retryAttempt = 0; + const cancelRetry = () => { + clearTimeout(retryTimer ?? undefined); + retryTimer = null; + }; + const retryAfterFailure = (e: unknown) => { + const transient = e instanceof HttpError ? e.status >= 500 || e.status === 429 : true; + if (!transient || gone || hubHoldsIt) return; + cancelRetry(); + const delay = SAVE_RETRY_MS[Math.min(retryAttempt, SAVE_RETRY_MS.length - 1)]; + retryAttempt++; + retryTimer = setTimeout(() => { + retryTimer = null; + if (!gone && !hubHoldsIt) void save(); + }, delay); + }; + // A write got through: the backoff starts over at its first step. + const landedWrite = () => { + cancelRetry(); + retryAttempt = 0; + }; + + const scheduleSave = () => { + cancelRetry(); + if (timer) clearTimeout(timer); + timer = setTimeout(() => void save(), SAVE_IDLE_MS); + }; + + /* Replace what the buffer holds with `next`, touching only what differs: + multi-hunk splices, so every character outside them — and every cursor + and remote caret in them — stays where it was. */ + const applyText = (next: string): boolean => { + if (gone) { + finalText = next; + return true; } - setState("saving"); - opts.onWriting?.(); - inFlight.add(text); + const cur = current(); + if (cur === next) return true; + const splices = diffSplices(cur, next); + if (onShared()) { + collab.applySplices(splices); + return true; + } + if (!opts.soloApply) return false; + for (const s of splices) opts.soloApply({ from: s.index, to: s.index + s.deleteCount, insert: s.insertText }); + return true; + }; + + const save = (): Promise => { + if (hubHoldsIt) return Promise.resolve(); // the hub writes a held room + // The room has the file; the buffer waits on its conflict copy. A save + // request is a nudge to try parking it again, never a write of its own. + if (pendingJoin) return joining ? Promise.resolve() : join(); + if (saving) { + dirtyWhileSaving = true; + return saving; + } + const run = (async () => { + try { + await saveLoop(); + } finally { + saving = null; + } + })(); + saving = run; + return run; + }; + + const saveLoop = async () => { + let rebases = 0; + for (;;) { + dirtyWhileSaving = false; + if (asking || hubHoldsIt || waitingToJoin) return; + const text = current(); + if (text === saved && !roomNeedsFlush) { + // Nothing to write IS clean, and saying so matters: a merge that + // marked the buffer dirty and scheduled this save lands here. + setState("clean"); + return; + } + setState("saving"); + opts.onWriting?.(); + const r = solo || noRoomHttp ? await sendFile(text) : await sendRoom(text); + if (r === "stop") return; + if (r === "rebased") { + if (++rebases > MAX_REBASES) { + await preserve(current(), base ?? ""); + return; + } + continue; + } + if (!dirtyWhileSaving) { + // Typing since the send that no timer has asked for yet: its own + // idle timer will. + setState(current() === saved && !roomNeedsFlush ? "clean" : "dirty"); + return; + } + } + }; + let confirmShrinkOnce = false; + + /* Solo: PUT the whole file with If-Match. */ + const sendFile = async (text: string): Promise<"done" | "rebased" | "stop"> => { + inFlightSentText = text; + disturbed = false; + let out: { sha?: string; merged?: boolean }; try { - const out = await putText(contentURL(opts.path), text, base); - saved = text; - if (out.sha) base = out.sha; - setState("clean"); - opts.onSaved?.(text); + out = await putText(contentURL(opts.path), text, base, confirmShrinkOnce); } catch (e) { + inFlightSentText = null; if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) { + confirmShrinkOnce = false; askShrink(text); - return; + return "stop"; } + /* A 409 is a write that landed since `saved`. Ours did not. Rebase over + it three ways and send again: two people editing different parts of + a file is not a conflict, and parking one of them beside the file — + which is what this did until now — erased that edit from the file + for everyone, every round, until the other side lost too. */ if (e instanceof HttpError && e.status === 409) { - inFlight.delete(text); // preserve() writes under a different path - /* A 409 in a shared room is usually a LOST RACE, not a disagreement. - - Everyone in the room holds one document, so a co-editor's save is - a past state of the text we are about to write: their bytes are - already in our CRDT. If they land between our reading `base` and - our PUT arriving, the hub is right to refuse us — our base moved — - but parking the result beside the file is nonsense, because our - text already contains theirs. A real session did exactly that and - collected dozens of conflict copies of files against themselves. - - No amount of care about WHEN we adopt a peer's sha closes this: - the window is between the read and the write, and something has to - happen after the refusal. So, once: re-read, check that our text - still contains theirs, rebase and try again. Same shape as the - hub's own journal append (appendConditional), for the same reason. - - If containment fails, the writer was an outsider — an agent, the - CLI, another device — whose work is NOT in our document, and the - conflict copy below is exactly right. */ - if (await rebaseOnLostRace(text)) return; - await preserve(text, e); - return; + return (await rebaseOnHead(saved, false)) ? "rebased" : "stop"; } - // Keep the document: the CRDT is the truth until a save lands, and the - // next edit schedules another attempt. + // Keep the buffer: it is the truth until a save lands. A transient + // failure is retried on its own; anything else waits for the next edit. setState("error"); - } finally { - inFlight.delete(text); + retryAfterFailure(e); + return "stop"; } + inFlightSentText = null; + confirmShrinkOnce = false; + landedWrite(); + if (out.merged) { + // The hub folded our body into a newer file (upload.go): the file is + // not `text`. Learn what it is, carrying anything typed since onto it. + return (await rebaseOnHead(text, true)) ? "rebased" : "stop"; + } + // A write merged in while ours was out landed AFTER ours (ours was not + // refused), so it is the newer version and `saved` already names it. + if (!disturbed) adopt(text, out.sha); + opts.onSaved?.(text); + return "done"; + }; + + /* Read the file and rebase the buffer onto it: merge3(from, head, buffer). + `from` is the version both descend from — `saved` after a refusal, the + text we sent after the hub merged it. `landed` says our write is in the + head. False when it could not, and then the buffer has been parked. */ + const rebaseOnHead = async (from: string, landed: boolean): Promise => { + let head; + try { + head = await fetchBlobText(fileURLFor(opts.apiBase, opts.path)); + } catch (e) { + setState("error"); + // The buffer is still unsaved and nothing else may ever ask again (the + // typing stopped): a read that failed for a moment arms the same retry + // a failed save does, which re-sends and lands here again once the hub + // recovers. + if (current() !== saved) retryAfterFailure(e); + return false; + } + if (head.kind !== "text") { + setState("error"); + return false; + } + const cur = current(); + const res = merge3(from, head.text, cur); + if (!res.ok || !applyText(res.text)) { + // The same words changed two different ways: genuinely contended. + // Theirs is the file (it got there first); ours goes beside it. + if (landed) adopt(head.text, head.sha); + await preserve(cur, head.sha ?? ""); + return false; + } + adopt(head.text, head.sha); + if (landed) opts.onSaved?.(head.text); + return true; + }; + + /* Staging: hand the typing to the room as text. The hub merges + (saved, room, text) and answers with the room's text, which this buffer + is then rebased onto, so the next checkpoint is a small diff again. */ + const applyAmbiguousPeek = (peek: { sha: string; text: string; update?: string }) => { + if (peek.update) collab.applyRemoteUpdate(peek.update); + if (typeof peek.text !== "string") { + ambiguousRoomCheckpoint = null; + return; + } + let landed: Ambiguous | null = null; + for (let c: Ambiguous | null = ambiguousRoomCheckpoint; c !== null; c = c.prev) { + if (c.sent !== c.from && retainsChanges(c.from, c.sent, peek.text)) { + landed = c; + break; + } + } + ambiguousRoomCheckpoint = null; + if (landed) { + roomNeedsFlush = true; + // The room holds `sent`: what the buffer adds is only past it. + const res = merge3(landed.sent, peek.text, current()); + if (res.ok && applyText(res.text)) { + saved = peek.text; + savedSha = undefined; + rebase(peek.sha); + } else { + saved = landed.sent; + savedSha = undefined; + } + } + }; + + const sendRoom = async (text: string): Promise<"done" | "rebased" | "stop"> => { + inFlightSentText = text; + disturbed = false; + let out: { sha: string; text: string; update?: string }; + const before = ambiguousRoomCheckpoint; + try { + ambiguousRoomCheckpoint = { sent: text, from: saved, prev: before }; + out = await syncCollab(syncURL, { ...roomPayload(text, before), ...(confirmShrinkOnce ? { confirm_shrink: true } : {}) }); + } catch (e) { + inFlightSentText = null; + // Refusals the hub gives before it touches the room's document; any + // other failure may have landed `text` there first. + if (e instanceof HttpError && [400, 401, 403, 404, 405, 409, 413].includes(e.status)) { + ambiguousRoomCheckpoint = before; + } + if (e instanceof HttpError && (e.status === 404 || e.status === 405)) { + noRoomHttp = true; // an older hub: save the file as solo does + return "rebased"; + } + if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) { + confirmShrinkOnce = false; + askShrink(text); + return "stop"; + } + if (e instanceof HttpError && e.status === 409 && !hubHoldsIt) { + /* The room changed the same lines this checkpoint did. The checkpoint + was `text`, but the buffer may have moved on while it was out — and + its idle timer already asked for that, into this loop — so what is + settled is the buffer as it is NOW, never the stale `text`. */ + let theirs: { sha?: string; text?: string } = {}; + try { + theirs = JSON.parse(e.body) as typeof theirs; + } catch { + // an older hub, or a body we cannot read: park the buffer + } + const room = typeof theirs.text === "string" ? theirs.text : null; + if (room !== null) { + const res = merge3(saved, room, current()); + if (res.ok && applyText(res.text)) { + // Rebased onto the room: send the merge, as a diff against it. + saved = room; + savedSha = undefined; + rebase(theirs.sha); + return "rebased"; + } + } + stagingConflict = true; + const parked = current(); + const failed = await preserve(parked, theirs.sha ?? ""); + if (gone) return "stop"; // destroy() parked the buffer itself + if (failed) { + retryAfterFailure(failed.err); + return "stop"; + } + stagingConflict = false; + // Typing that landed while the copy was on the wire is not in it: + // it goes to the room, built on what was parked. + return current() !== parked ? "rebased" : "stop"; + } + setState(hubHoldsIt ? "dirty" : "error"); + retryAfterFailure(e); + return "stop"; + } + inFlightSentText = null; + confirmShrinkOnce = false; + landedWrite(); + /* The room's state with this checkpoint in it, with the room's own item + IDs: in the document before anything else reads it, so a join waiting + on this request splices only what the room does not hold yet — and the + same items arriving on the socket, before or after, merge as no-ops. + Without it a join that read the room before the socket delivered them + inserted the checkpoint's lines a second time. */ + if (out.update) collab.applyRemoteUpdate(out.update); + ambiguousRoomCheckpoint = null; + roomNeedsFlush = false; + // Joined while this was out: the join merged the same buffer into the + // shared document, which now holds the truth. + if (hubHoldsIt) return "stop"; + const res = merge3(text, out.text, current()); + // The buffer is now built on `out.text` even with typing past `text` in + // it: that is the base the join and the next checkpoint diff against. + if (res.ok && applyText(res.text)) { + if (!disturbed) adopt(out.text, out.sha); + } + // Otherwise the newest typing could not be carried across here; `saved` + // stays where it was and the hub's own merge decides on the next checkpoint. + opts.onSaved?.(out.text); + return "done"; }; /* One question at a time: while the user is deciding, a second refusal or @@ -221,40 +659,66 @@ export function openSharedFile(opts: { now: byteLength(text), confirm: async () => { if (gone) return; - // The user may keep typing while the dialog is open, so the - // confirmation writes the document as it stands when clicked. - const now = current(); - setState("saving"); - opts.onWriting?.(); - try { - const out = await putText(contentURL(opts.path), now, base, true); - saved = now; - if (out.sha) base = out.sha; - setState("clean"); - opts.onSaved?.(now); - } catch { - setState("error"); - } finally { - asking = null; + if (hubHoldsIt) { + setState("saving"); + opts.onWriting?.(); + // Edits queued offline are in this update too: it acknowledges them. + const targetOfflineSeq = offlineEditSeq; + const sentRoomSeq = localRoomSeq; + try { + const out = await syncCollab(syncURL, { update: collab.encodeState(), base, confirm_shrink: true }); + adopt(out.text, out.sha); + offlineAcked(targetOfflineSeq, sentRoomSeq); + const caughtUp = !localDirtyInRoom && offlineAckedSeq >= offlineEditSeq; + setState(caughtUp ? "clean" : "dirty"); + opts.onSaved?.(saved); + // Typed while the question was open: still queued, still sent. + if (!live && !gone && offlineAckedSeq < offlineEditSeq) { + asking = null; + void flushOffline(false); + } + } catch { + setState("error"); + } finally { + asking = null; + } + return; } + // Staging or solo: run through the single-flight `save()` loop so + // join() awaits it, `ambiguousRoomCheckpoint` tracks it, and the + // returned room text rebases any concurrent typing. + confirmShrinkOnce = true; + asking = null; + roomNeedsFlush = true; + await save(); }, keep: async () => { if (gone) return; try { const head = await fetchBlobText(fileURLFor(opts.apiBase, opts.path)); if (gone || head.kind !== "text") return; - const cur = current(); - const e = textEdit(cur, head.text); - saved = head.text; - rebase(head.sha); - if (e) { - if (collab.text.length || hubHoldsIt) { - collab.doc.transact(() => { - collab.text.delete(e.from, e.to - e.from); - collab.text.insert(e.from, e.insert); - }); - } else opts.soloApply?.(e); + adopt(head.text, head.sha); + applyText(head.text); + asking = null; + /* Socket down: the refused update had already reached the room's + document (the hub applies before it snapshots), so the room holds + the shrunk text. Putting the bytes back is an edit the room must + get — over HTTP now, or by the retry, pagehide or destroy() if + this attempt fails. */ + if (hubHoldsIt && !live) { + await flushOffline(false); + if (gone) return; + setState(offlineAckedSeq >= offlineEditSeq && !localDirtyInRoom ? "clean" : "dirty"); + return; + } + // Live, the socket carries the restoration; staging or solo, the + // file already holds these bytes. Nothing queued either way. + offlineAckedSeq = offlineEditSeq; + if (pending) { + pending = 0; + opts.onPending?.(0); } + roomCaughtUp(); setState("clean"); } catch { setState("error"); @@ -279,323 +743,556 @@ export function openSharedFile(opts: { }, SAVE_IDLE_MS); }; - /* rebaseOnLostRace turns a refused save into a retried one, ONCE, when the - refusal was a race rather than a disagreement. - - Two ways a refusal is a race rather than a disagreement, and BOTH have - to be handled — shipping only the first is what produced conflict copies - that were subsets of the files they sat beside: - - ours contains theirs -> our write is the superset; rebase and retry - theirs contains ours -> the file is ahead; drop the write entirely - - Returns true when there is nothing left to do. Deliberately not a loop: - if neither containment holds, the path is genuinely contended by someone - outside the room and a conflict copy is the honest answer. */ - const rebaseOnLostRace = async (text: string): Promise => { + /* Somebody else's write landed on this path while we were editing, and the + two versions cannot be reconciled — merge3 found the same words changed + two different ways. So neither version is dropped: theirs is the file, + ours goes beside it as `.bdrive-conflict--`, which the + reader already knows how to explain (lib/conflict.ts, ConflictBanner). */ + const preserve = async ( + text: string, + theirs: string, + copy = mintConflictPath(), + ): Promise<{ err: unknown } | null> => { + const seq = ++conflictSeq; + conflictPuts.set(copy, text); + // A newer park started since this one (a join's, over newer typing), or + // the room took the buffer: such a landing settles nothing about `saved`. try { - const head = await fetchBlobText(fileURLFor(opts.apiBase, opts.path)); - if (head.kind !== "text" || !head.sha) return false; - - /* THE FILE IS AHEAD OF US. - - Our text holds nothing the file lacks — a peer saved a newer state of - the document we share while our save was in flight, so what we were - writing is simply out of date. There is nothing to write and nothing - to preserve: parking it beside the file produces a conflict copy that - is a SUBSET of the file it sits next to, which is what shipped in the - first version of this fix and what put four more copies in a project - minutes after it deployed. - - Record where the file is and go clean. Our own document catches up - over the websocket like everyone else's. */ - const oursToTheirs = textEdit(text, head.text); - if (!oursToTheirs || oursToTheirs.from === oursToTheirs.to) { - saved = head.text; - rebase(head.sha); + await putText(contentURL(copy), text); // unconditional: a new path + if (seq === conflictSeq && !hubHoldsIt) { + saved = text; + savedSha = undefined; + if (theirs) base = theirs; setState("clean"); - return true; } + opts.onConflictCopy?.(copy); + return null; + } catch (e) { + // Could not even park it. Stay dirty and loud rather than pretend. + if (seq === conflictSeq && !hubHoldsIt) setState("error"); + return { err: e }; + } finally { + if (conflictPuts.get(copy) === text) conflictPuts.delete(copy); + } + }; - // Their text must be contained in ours, or we would be erasing work - // this document never saw. Same test merge() uses, same reason. - const theirsToOurs = textEdit(head.text, text); - if (theirsToOurs && theirsToOurs.from !== theirsToOurs.to) return false; - rebase(head.sha); - const out = await putText(contentURL(opts.path), text, base); - saved = text; - if (out.sha) base = out.sha; - setState("clean"); - opts.onSaved?.(text); - return true; - } catch { - return false; // fall through to the conflict copy + /* Edits made while a held room's socket is down live only in this tab's + Y.Doc. If the socket stays away, hand them to the hub as a Yjs update: + applying it to the room is idempotent, so the reconnect that eventually + comes adds nothing twice, and a tab closed in the meantime loses nothing. */ + const offlineAcked = (targetSeq: number, sentRoomSeq: number) => { + offlineAckedSeq = Math.max(offlineAckedSeq, targetSeq); + roomHandedOver(sentRoomSeq); + if (gone || live) return; + pending = offlineEditSeq - offlineAckedSeq; + opts.onPending?.(pending); + }; + /* Refused or unwritten (a 503 while another process has not written it + yet, quota, storage): the edits are still queued in the document and + `pending` still counts them. The socket, the next edit, or this timer + retries — the last so a tab that stays offline and idle does not wait + forever for a nudge. */ + const retryOffline = () => { + if (gone || live || asking || offlineTimer) return; + offlineTimer = setTimeout(() => { + offlineTimer = null; + if (!live && !gone) void flushOffline(false); + }, OFFLINE_FLUSH_MS); + }; + /* A keepalive flush (the page is going) fires at once and rejects when it + fails, so the exit path can offer it again. Any other is single-flight: + concurrent callers share one loop, which sends until the hub has + acknowledged every edit made so far. */ + const flushOffline = (keepalive: boolean): Promise => { + clearTimeout(offlineTimer ?? undefined); + offlineTimer = null; + if (keepalive) { + if (offlineAckedSeq >= offlineEditSeq) return Promise.resolve(); + const targetSeq = offlineEditSeq; + const sentRoomSeq = localRoomSeq; + return syncCollab(syncURL, { update: collab.encodeState(), base }, true).then((out) => { + rebase(out.sha); + offlineAcked(targetSeq, sentRoomSeq); + }); } + if (offlineFlushing) return offlineFlushing; + const run = (async () => { + try { + while (!live && !gone && !asking && offlineAckedSeq < offlineEditSeq) { + const targetSeq = offlineEditSeq; + const sentRoomSeq = localRoomSeq; + let out: { sha: string }; + try { + out = await syncCollab(syncURL, { update: collab.encodeState(), base }, false); + } catch (e) { + /* Refused for sharply shrinking the file: no retry can land it + until the user agrees, so ask now — Done waits on the answer. */ + if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) { + clearTimeout(shrinkTimer ?? undefined); + shrinkTimer = null; + askShrink(current()); + if (asking) return; + } + retryOffline(); + return; + } + rebase(out.sha); + offlineAcked(targetSeq, sentRoomSeq); + } + } finally { + offlineFlushing = null; + } + })(); + offlineFlushing = run; + return run; }; - /* Somebody else's write landed on this path while we were editing, and the - two versions cannot be reconciled here — if they could, merge() would - already have done it, because a save only happens when this buffer has - changes of its own. - - So neither version is dropped. Theirs is the file (it got there first); - ours goes beside it under the same name the sync path has used since the - beginning, `.bdrive-conflict--`, which the reader already - knows how to explain (lib/conflict.ts, ConflictBanner). - - The alternative is what this door did until now: take the body wholesale - and erase their work silently. Two browsers holding different documents — - one that had lost the co-editing relay — did exactly that to each other - every few seconds, with nothing anywhere to say so. */ - const preserve = async (text: string, e: HttpError) => { - let theirs = ""; - try { - theirs = (JSON.parse(e.body) as { sha?: string }).sha ?? ""; - } catch { - /* an older hub, or a body we cannot read: the copy still matters */ + /* The first sync: the hub's document has arrived. Whatever was typed into a + staging buffer in the meantime is merged in three ways — (what it started + from, what the room holds, what it holds now) — and spliced into the + shared document as minimal hunks. A checkpoint that already reached the + room is in both and lands once. + + When the same words changed two ways the buffer is parked beside the file + as a conflict copy — and the editor stays on that buffer until the copy + is durably on the hub. Swapping onto the shared document first would + unmount the only place those words exist: a failed park would then lose + them outright. A transient failure (5xx, 429, no answer) is retried on + the save backoff; destroy() parks the buffer on the way out. */ + const finishJoin = (then?: () => void) => { + pendingJoin = false; + parkedName = null; + parkedText = null; + joinAttempt = 0; + clearTimeout(joinTimer ?? undefined); + joinTimer = null; + roomNeedsFlush = false; + hubHoldsIt = true; + seeRoomText(collab.text.toString()); + then?.(); + if (readyWaiting) { + readyWaiting = false; + opts.onReady(collab); } - const copy = conflictName(opts.path, opts.who || "browser", new Date()); + }; + const join = async (): Promise => { + if (gone || hubHoldsIt || joining || waitingToJoin) return; + clearTimeout(joinTimer ?? undefined); + joinTimer = null; + if (timer) clearTimeout(timer); + timer = null; + /* A staging checkpoint still on the wire is part of what the room will + hold. Read the buffer and the room before it lands and the merge sees + its lines as typing the room lacks, splices them in, and the room's + own copy of them arrives after: every checkpointed line twice. So wait + for it — the loop sends no further checkpoint meanwhile — and let it + hand its items to the document first (sendRoom). */ + if (saving) { + waitingToJoin = true; + try { + while (saving) await saving; + } finally { + waitingToJoin = false; + } + if (gone || hubHoldsIt) return; + if (!live) { + // The socket dropped while we waited: staging again, and the typing + // the loop held back still has to reach the room. + if (current() !== saved) scheduleSave(); + return; + } + } + /* A checkpoint that failed after the hub may already have put it into + the room (a 5xx, a 422, an answer that never came back) leaves the + room's content unknown: its items may still be on their way down the + socket. Merging from `saved` now would splice its lines in a second + time under fresh item IDs — and when the room's own copy arrives, + every one of them twice. So ask the room first (a peek writes + nothing), take its items into the document, and if it holds the + checkpoint, rebase the buffer over it before the join reads either. */ + if (ambiguousRoomCheckpoint !== null && !noRoomHttp) { + let peek: { sha: string; text: string; update?: string }; + waitingToJoin = true; // no checkpoint goes out while the room is read + try { + peek = await syncCollab(syncURL, { peek: true }); + } catch { + if (gone || hubHoldsIt) return; + const delay = SAVE_RETRY_MS[Math.min(joinAttempt, SAVE_RETRY_MS.length - 1)]; + joinAttempt++; + joinTimer = setTimeout(() => { + joinTimer = null; + void join(); + }, delay); + return; + } finally { + waitingToJoin = false; + } + if (gone || hubHoldsIt) return; + applyAmbiguousPeek(peek); + if (!live) { + if (current() !== saved || roomNeedsFlush) scheduleSave(); + return; + } + } + const local = opts.soloText?.(); + if (local === undefined || local === saved) return finishJoin(); + const hub = collab.text.toString(); + const res = merge3(saved, hub, local); + if (res.ok) return finishJoin(() => collab.applySplices(diffSplices(hub, res.text))); + pendingJoin = true; + // One name for every attempt at the same text: a retry re-writes the same + // copy, never a second. Newer text — or a staging park still on the wire — + // gets a freshly minted name, so an older PUT never lands over it. + if (parkedName === null || parkedText !== local) { + parkedName = mintConflictPath(); + parkedText = local; + } + joining = true; + let failed: { err: unknown } | null; try { - await putText(contentURL(copy), text); // unconditional: a new path - saved = text; - base = theirs; - setState("clean"); - opts.onConflictCopy?.(copy); - } catch { - // Could not even park it. Stay dirty and loud rather than pretend. - setState("error"); + failed = await preserve(local, base ?? "", parkedName); + } finally { + joining = false; + } + if (gone) return; // destroy() parked the buffer itself + if (!failed) { + // Typing that landed in the buffer while the copy was on the wire is + // not in it: go round again from what was parked. + if (opts.soloText?.() !== local) { + parkedName = null; + parkedText = null; + return join(); + } + // Parked: the editor now shows the room's text, which is what it is built on. + return finishJoin(() => { + saved = collab.text.toString(); + }); } + const e = failed.err; + if (e instanceof HttpError && !(e.status >= 500 || e.status === 429)) return; // waits for the next edit + const delay = SAVE_RETRY_MS[Math.min(joinAttempt, SAVE_RETRY_MS.length - 1)]; + joinAttempt++; + joinTimer = setTimeout(() => { + joinTimer = null; + void join(); + }, delay); }; - /* Whether the hub holds this document. - - Once it does, the hub is the ONLY writer (ycollab.go, watchRoom): it sees - every update and writes the file once per pause. This client's own save - timer used to run beside that — and beside every other co-editor's — and - N writers racing for one file is what turned a lost race into a conflict - copy of the file against itself. So the moment the room is live the - timer here stops being armed, and stays stopped: the hub is now the one - that knows the file's version, and a client that reconnects after a blip - writing "its" version is exactly the race coming back. - - Never live means solo — an older hub, a proxy that will not upgrade — - and then this client saves exactly as it always did. */ - let hubHoldsIt = false; - let gone = false; - // Whether the socket is up right now, and how many local edits were made - // while it was not. - let live = false; - let pending = 0; - const collab = new CollabDoc( opts.apiBase + "ycollab?path=" + encodeURIComponent(opts.path), (s) => { - if (s === "live") { - hubHoldsIt = true; + live = s === "live"; + if (s === "solo") solo = true; + if (live) { + if (offlineTimer) clearTimeout(offlineTimer); + offlineTimer = null; + cancelRetry(); // the room holds the buffer now, and the hub writes it + if (!hubHoldsIt) void join(); + offlineAckedSeq = offlineEditSeq; if (pending) { pending = 0; opts.onPending?.(0); } } - live = s === "live"; opts.onCollab?.(s); }, - () => opts.onReady(collab), - () => opts.onSolo(), + // The editor moves onto the shared document only once the join is done: + // a buffer still waiting for its conflict copy to land stays mounted. + () => { + if (hubHoldsIt) opts.onReady(collab); + else readyWaiting = true; + }, + () => { + if (!gone && !hubHoldsIt) opts.onStalled?.(); + }, opts.me, ); - /* MY changes restart the idle timer. A peer's do not. - - This used to be "any change, mine or a peer's — whoever stops typing last - writes the file", on the reasoning that the content is identical for - everyone so a second writer is a harmless no-op put. It is not harmless. - In a room of N editors, 700ms after the last keystroke by ANYONE, all N - clients PUT the identical full body: N uploads of the same text, and a - History feed that grows N versions every time the room goes quiet. That - is the "too many change histories" report, and four co-editors made it - four of everything (docs/hub-load-prd.md Stage 4). - - Dropping to one writer loses nothing. Every copy is identical by - construction — that is what the CRDT is for — and the hub snapshots the - room itself when the last editor leaves (ycollab.go, OnLastPeer), so the - closed-laptop case never depended on a bystander saving on the typist's - behalf either. - - Seeding is a remote change too, which is a second thing this fixes: the - document arriving from the hub used to mark the buffer dirty and schedule - a save of bytes the file already contained. */ + /* MY changes restart the idle timer. A peer's do not — and in a held room + nothing here writes at all: N clients saving one shared document is N + identical PUTs and N history entries every time the room goes quiet + (docs/hub-load-prd.md Stage 4). The hub writes it, once. */ const onDocChange = (_e: unknown, tx: { origin?: unknown }) => { + const roomText = hubHoldsIt ? collab.text.toString() : null; + if (roomText !== null) seeRoomText(roomText); if (collab.isRemote(tx?.origin)) return; setState("dirty"); - if (hubHoldsIt && !live) opts.onPending?.(++pending); - if (hubHoldsIt) watchShrink(); - // The hub writes for a live room; "dirty" clears when its write comes - // back through the change stream and merge() finds the file equal to the - // document. Honest, rather than "saved" the moment a key is pressed. - if (hubHoldsIt) return; - if (timer) clearTimeout(timer); - timer = setTimeout(() => save(collab.text.toString()), SAVE_IDLE_MS); + if (hubHoldsIt) { + localDirtyInRoom = true; + lastLocalRoomText = roomText; + localRoomSeq += 1; + if (!live) { + // Counted whether or not the caller shows it (VisualEdit passes no + // onPending): `pending` is what tells flushOffline there is anything + // to hand over on the offline timer and on destroy(). + offlineEditSeq += 1; + pending = offlineEditSeq - offlineAckedSeq; + opts.onPending?.(pending); + clearTimeout(offlineTimer ?? undefined); + offlineTimer = setTimeout(() => { + offlineTimer = null; + if (!live && !gone) void flushOffline(false); + }, OFFLINE_FLUSH_MS); + } + // "dirty" clears when the hub's write comes back through the change + // stream and merge() finds the file equal to the document. + watchShrink(); + return; + } + scheduleSave(); }; collab.text.observe(onDocChange); const onPeerChange = () => opts.onPeers?.(collab.peerCount()); collab.awareness.on("change", onPeerChange); - /* Solo is decided once and kept: CollabDoc.stop() has already ended the - transport by the time onSolo runs, so `hubHoldsIt` can never flip under - a solo surface and every save from here on is this client's own, - If-Match and all. A server with no room route goes straight there; the - callback is deferred because the caller's own handle to this file is - not assigned until this returns. */ + /* A server with no room route goes straight to solo; a route that is slow + is retried for as long as this file is open (CollabDoc.connect). The + callback is deferred because the caller's own handle to this file is not + assigned until this returns. */ if (hasCollabRoute(opts.apiBase)) collab.connect(); else queueMicrotask(() => { if (gone) return; + solo = true; collab.stop(); opts.onSolo(); }); - // Whichever surface is live holds the truth: the CRDT when the relay - // answered, the surface's own buffer when it never did. - const current = () => - collab.text.length ? collab.text.toString() : (opts.soloText?.() ?? ""); - - /* Somebody wrote this file while it was open here. - - The editor deliberately does not re-seed itself from the server — that - would reset the document under a typist's cursor — so this is the other - way the change gets in: as the one splice that turns what we have into - what the file says, leaving every untouched character (and so every - cursor and every remote caret) exactly where it was. + // The shared document once the hub has it; before that (or without a room + // at all) the caller's own buffer — except a solo surface that keeps its + // text in the Y.Text anyway (VisualEdit). + const current = () => { + if (finalText !== null) return finalText; + if (onShared()) return collab.text.toString(); + return opts.soloText?.() ?? ""; + }; + /* Is the shared document the buffer? Once the hub holds it, yes — and for + a solo surface that keeps its text in the Y.Text (VisualEdit). Never + while staging or joining: the document then holds the ROOM's text (the + socket's, or a checkpoint's answer, sendRoom) while the editor is still + on the caller's own buffer, which is the only copy of the typing. */ + const onShared = () => hubHoldsIt || (solo && collab.text.length > 0); - It refuses in the two cases where a splice would destroy something, and - the refusal is the caller's banner. */ /* The file's current sha, learned from somewhere other than our own write. - - `base` is the If-Match this editor saves against, and until now the ONLY - thing that moved it was a successful save of our own. That is fine alone - and wrong in a room: a co-editor's save moves the file's head, every other - member keeps the sha from before it, and their next save is a 409 against - a file that already contains their work. - - The hub is right to refuse it — a stale base is exactly what If-Match is - for — and the conflict copy that followed was right for the writer it was - designed for, an agent or a device outside the room. It was nonsense - between two people in one document: the CRDT had already merged them, so - the "conflict" was a copy of the file against itself. - - So whoever learns the new sha tells us. Nothing about the CONTENT is - assumed here; the caller has just read this path from the hub. */ + A co-editor's save moves the head; whoever learns the new sha tells us, + so our next save is not refused for a conflict that does not exist. */ const rebase = (sha?: string) => { if (sha) base = sha; }; const merge = (next: string, nextSha?: string, how?: { held?: boolean }): MergeResult => { if (how?.held) { - saved = next; - rebase(nextSha); + adopt(next, nextSha); return "same"; } - // The file is at the content we last knew about: our own write coming - // back through the change stream, or nothing new at all. `inFlight` - // covers the common case that `saved` cannot — the frame announcing our - // own write arriving before that write's own response does. - /* Adopting the sha is NOT the same decision as accepting the content — - see the two-questions note below. It never happens here, though: at - this point we have not yet read the buffer, so we cannot know whether - their bytes are already in it. */ - if (next === saved || inFlight.has(next)) { + // Our own write coming back (possibly before its response), or nothing new. + if (next === saved || next === inFlightSentText) { rebase(nextSha); return "same"; } const cur = current(); // Already in the buffer: a co-editor snapshotted the document we share. - // Recording it is what keeps the check above true for the rest of the - // session, so their next save is not mistaken for an outsider's. if (next === cur) { - saved = next; - rebase(nextSha); + adopt(next, nextSha); // For a live room this IS the save landing — the hub's write, back // through the stream — so this is where "dirty" honestly ends. - if (hubHoldsIt) setState("clean"); + if (hubHoldsIt) { + roomCaughtUp(); + setState("clean"); + } return "same"; } - /* Two different questions, which used to be one. - - "Can we splice their write into the buffer?" and "is their VERSION a - valid base for our next write?" are not the same question, and - answering only the first is what put a co-editing session into a loop - of conflict copies. - - In a room everyone shares one document, so a peer's save is a PAST - STATE of the text we are holding: their bytes are already in our CRDT, - arriving over the websocket rather than through this function. We must - not splice it (it is already applied, and splicing would apply it - twice) — but their sha is exactly the right base for our next save, - because our text is theirs plus whatever we have typed since. - - Not assumed, checked. Turning their text into ours deletes nothing iff - ours is a strict superset of theirs, which is precisely the condition - that makes their version a safe base. An outsider's write — an agent, - the CLI, another device — fails that test, keeps the old base, and is - still refused with a conflict copy, which is what If-Match is for. */ - const theirsToOurs = textEdit(next, cur); - const oursContainsTheirs = !theirsToOurs || theirsToOurs.from === theirsToOurs.to; - - // Unsaved local edits: not ours to resolve. Splicing over a half-typed - // sentence is the one thing this must never do. - if (cur !== saved) { - if (oursContainsTheirs) rebase(nextSha); - return "blocked"; - } - // A co-editor in the room: they are looking at the same stale document - // and would compute the same splice, and two identical splices into one - // CRDT is the change applied twice. - if (collab.peerCount() > 0) { - if (oursContainsTheirs) rebase(nextSha); - return "blocked"; - } - const e = textEdit(cur, next); - if (!e) return "same"; + + if (hubHoldsIt) { + /* In a room a peer's save — or the hub's own snapshot — is a PAST STATE + of the shared document: its bytes are already in our CRDT, and the + room has moved on since (peers kept typing, or deleting). Splicing it + would apply it twice; refusing it would raise a banner over nothing. + It is the file now, so it is the base the next write builds on. */ + const prevSaved = saved; + const roomAlreadyHasIt = seenRoomTexts.includes(next) || retainsChanges(prevSaved, next, cur); + if (roomAlreadyHasIt) { + adopt(next, nextSha); + if ( + localDirtyInRoom && + (lastLocalRoomText === null || + next === lastLocalRoomText || + retainsChanges(prevSaved, lastLocalRoomText, next)) + ) { + roomCaughtUp(); + setState("clean"); + } + return "same"; + } + /* An outsider's write that never went through the room (an + unconditional PUT): with unsaved typing or company it is the caller's + banner; alone and clean it simply becomes the document. */ + if (cur !== saved || collab.peerCount() > 0) return "blocked"; + adopt(next, nextSha); + applyText(next); + roomCaughtUp(); + return "merged"; + } + + /* Solo or staging: three ways. Our unsaved typing is (cur − saved), their + write is (next − saved); both survive unless they changed the same + words differently, and only then is this the caller's banner. */ if (!collab.text.length && !opts.soloApply) return "blocked"; - // Before the splice, not after: the document change it causes schedules a - // save, and this is what makes that save a no-op instead of a write-back - // of what we just read. - saved = next; - rebase(nextSha); - if (collab.text.length) { - // One transaction, so a peer sees a replacement rather than a delete - // followed by a moment of missing text. - collab.doc.transact(() => { - collab.text.delete(e.from, e.to - e.from); - collab.text.insert(e.from, e.insert); - }); + const res = merge3(saved, next, cur); + if (!res.ok) return "blocked"; + if (inFlightSentText !== null) disturbed = true; + adopt(next, nextSha); + applyText(res.text); + // What is left over is our own typing, rebased: it still needs saving. + if (res.text !== next) scheduleSave(); + else if (inFlightSentText === null) setState("clean"); + return res.text === cur ? "same" : "merged"; + }; + + /* An explicit save (Done, Mod-s). In a live room idle typing never writes + anything from here — the hub snapshots the room — but a user who asked to + save and leave must not leave on a snapshot still pending: the room's + state goes to the hub, which answers only once storage holds it. Clean, + or a bystander: nothing to send. Concurrent calls share one request. */ + let liveFlushing: Promise | null = null; + const saveNow = (): Promise => { + if (!hubHoldsIt) return save(); + if (asking || gone) return Promise.resolve(); + if (!live) return pending > 0 ? flushOffline(false) : Promise.resolve(); + if (!localDirtyInRoom) return Promise.resolve(); + if (liveFlushing) return liveFlushing; + const sentRoomSeq = localRoomSeq; + setState("saving"); + const run = (async () => { + try { + const out = await syncCollab(syncURL, { update: collab.encodeState() }); + if (gone) return; + if (out.update) collab.applyRemoteUpdate(out.update); + adopt(out.text, out.sha); + // Typing that landed while this was out is not in it. + roomHandedOver(sentRoomSeq); + setState(localDirtyInRoom ? "dirty" : "clean"); + opts.onSaved?.(saved); + } catch (e) { + if (gone) return; + /* The hub refused to write a document this much smaller than the + file without a word from the user: ask now (the caller stays put + until it is answered), rather than wait for the idle check. */ + if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) { + clearTimeout(shrinkTimer ?? undefined); + shrinkTimer = null; + askShrink(current()); + if (asking) return; + } + // The room still holds every edit and the hub still snapshots it. + setState(localDirtyInRoom ? "dirty" : "clean"); + } finally { + liveFlushing = null; + } + })(); + liveFlushing = run; + return run; + }; + + /* Leaving mid-word must not lose the word — a raw tab close or reload + (pagehide) or the surface unmounting (destroy), whichever comes first. + Every request is keepalive so it outlives the page, and the second of the + two finds the same state already on the wire and sends nothing. Nothing + counts as handed over until the hub answers: a failed request, or a page + restored from the back/forward cache (pageshow), may send it again. + - held and live: an edit no snapshot is known to carry goes to the hub + as the room's state; clean or a bystander sends nothing. + - held, socket down: the queued update goes over HTTP. + - staging: the buffer goes to the room as text. + - joining, or a staging checkpoint the room refused for a clash, its + conflict copy not yet landed: the buffer goes to that copy — the room + already holds the file's other side. + - solo: an unloading page PUTs with If-Match; an unmount runs the save + loop (or, mid-flight, it sends it next). + An unanswered shrink question means the user has not agreed to write + this text, so it is not written on the way out either. */ + let exitSent: string | null = null; + // A request that failed releases its key, so the state can be offered again. + const exitFailed = (key: string) => () => { + if (exitSent === key) exitSent = null; + }; + const flushExit = (text: string, unloading: boolean) => { + if (asking) return; + if (hubHoldsIt) { + const offline = !live && pending > 0; + if (!offline && !(live && localDirtyInRoom)) return; + const key = "room\u0000" + collab.text.toString(); + if (exitSent === key) return; + exitSent = key; + const sentRoomSeq = localRoomSeq; + const req = offline + ? flushOffline(true) + : syncCollab(syncURL, { update: collab.encodeState() }, true).then((out) => rebase(out.sha)); + req.then(() => roomHandedOver(sentRoomSeq), exitFailed(key)); + return; + } + if (pendingJoin || stagingConflict) { + const key = "park\u0000" + text; + if (exitSent === key) return; + exitSent = key; + // The same words as a park already named reuse its name (writing the + // same bytes twice is harmless); newer words get a freshly minted + // one, so no older park still on the wire can land over them. + let copy = parkedName !== null && parkedText === text ? parkedName : null; + for (const [path, held] of conflictPuts) if (copy === null && held === text) copy = path; + copy ??= mintConflictPath(); + void putText(contentURL(copy), text, undefined, false, true).catch(exitFailed(key)); + return; + } + if (!text || text === saved) return; + const key = "text\u0000" + text; + if (exitSent === key) return; + if ((solo || noRoomHttp) && !unloading) { + void save(); + return; + } + exitSent = key; + if (solo || noRoomHttp) { + void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true).catch(exitFailed(key)); } else { - opts.soloApply!(e); + void syncCollab(syncURL, roomPayload(text), true).catch(exitFailed(key)); } - return "merged"; }; + const onPageHide = () => { + if (!gone) flushExit(current(), true); + }; + // Back from the back/forward cache: the page lives on, and whatever it + // sent on the way "out" is no reason to send nothing on the next exit. + const onPageShow = () => { + exitSent = null; + }; + if (typeof window !== "undefined") { + window.addEventListener("pagehide", onPageHide); + window.addEventListener("pageshow", onPageShow); + } return { collab, current, merge, rebase, - // An explicit save from a live room is a request to the hub, and the - // hub is already going to; there is nothing for this client to send. - saveNow: () => (hubHoldsIt ? Promise.resolve() : save(current())), + saveNow, + askingShrink: () => asking !== null, destroy() { - if (timer) clearTimeout(timer); - if (shrinkTimer) clearTimeout(shrinkTimer); - gone = true; - // Closing the tab mid-word must not lose the word. For a live room - // the hub has the word — it writes on last peer, and on the debounce - // for everyone still there — and a parting write from here would be - // one more racer against it. - // An unanswered shrink question means the user has not agreed to write - // this text, so it is not written on the way out either. + if (typeof window !== "undefined") { + window.removeEventListener("pagehide", onPageHide); + window.removeEventListener("pageshow", onPageShow); + } + clearTimeout(timer ?? undefined); + clearTimeout(shrinkTimer ?? undefined); + cancelRetry(); + clearTimeout(joinTimer ?? undefined); + joinTimer = null; const text = current(); + gone = true; + finalText = text; if (asking) opts.onShrinkWithdrawn?.(asking); - else if (!hubHoldsIt && text && text !== saved) void save(text); + else flushExit(text, false); + clearTimeout(offlineTimer ?? undefined); collab.awareness.off("change", onPeerChange); collab.text.unobserve(onDocChange); collab.destroy(); diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts new file mode 100644 index 00000000..44f6c869 --- /dev/null +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -0,0 +1,1549 @@ +/* A text this tab once wrote can legitimately come back: History restores + B to A. It must merge like any other outside write, not be dismissed as a + late echo of something already moved past. + + Run with `npm test` (node's built-in runner), or alone: + node --test src/lib/sharedfile_restore.test.ts + Excluded from tsconfig's include — it imports node: builtins, which the + app's DOM-only lib set does not know about. */ + +import { test, mock } from "node:test"; +import assert from "node:assert/strict"; +import { createRequire, registerHooks } from "node:module"; +import { existsSync, readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import type { SharedFile, ShrinkAsk } from "./sharedfile.ts"; + +/* The modules under test are app code: extensionless imports, and TypeScript + node cannot strip on its own (collab.ts's parameter properties). So every + file under src/ is resolved the way the bundler does and transpiled with + the project's own TypeScript; analytics is a no-op, as in the bundle's + tests it has always been. Registered before anything under test loads. */ +const SRC = new URL("../", import.meta.url).href; +const ts = createRequire(import.meta.url)("typescript"); +registerHooks({ + resolve(specifier, context, nextResolve) { + const parent = context.parentURL; + if (parent?.startsWith(SRC) && /^\.\.?\//.test(specifier) && !/\.[cm]?[jt]sx?$/.test(specifier)) { + for (const ext of [".ts", ".tsx", "/index.ts"]) { + const url = new URL(specifier + ext, parent); + if (!existsSync(fileURLToPath(url))) continue; + if (url.href === SRC + "analytics.ts") { + return { url: "data:text/javascript,export function track() {}", shortCircuit: true }; + } + return { url: url.href, shortCircuit: true }; + } + } + return nextResolve(specifier, context); + }, + load(url, context, nextLoad) { + if (url.startsWith(SRC) && /\.tsx?$/.test(url)) { + const fileName = fileURLToPath(url); + const out = ts.transpileModule(readFileSync(fileName, "utf8"), { + fileName, + compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX }, + }); + return { format: "module", source: out.outputText, shortCircuit: true }; + } + return nextLoad(url, context); + }, +}); + +// Dynamic, not static: static imports are linked before the hooks above exist. +const { CollabDoc } = await import("./collab.ts"); +const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); +const { parseConflict } = await import("./conflict.ts"); +const { merge3 } = await import("./merge3.ts"); + +/* toEqual's semantics: a property that is undefined is a property that is + absent. Only plain objects and arrays are rebuilt; anything else (a + CollabDoc) is compared as itself. */ +function plain(v: unknown): unknown { + if (Array.isArray(v)) return v.map(plain); + if (v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) { + return Object.fromEntries( + Object.entries(v) + .filter(([, x]) => x !== undefined) + .map(([k, x]) => [k, plain(x)]), + ); + } + return v; +} +function same(actual: unknown, expected: unknown) { + assert.deepEqual(plain(actual), plain(expected)); +} + +/* Fake timers: node's mock clock, plus the due time of every pending timer, + so advance() runs them one at a time in order and lets the promises each + one starts settle before the next — a retry armed by a failed request + lands at exactly its delay, not at the end of a coarse tick. */ +const realTimerFns = { + setTimeout: globalThis.setTimeout, + clearTimeout: globalThis.clearTimeout, + setInterval: globalThis.setInterval, + clearInterval: globalThis.clearInterval, +}; +const dues = new Map(); +function fakeTimers() { + mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: Date.now() }); + const st = globalThis.setTimeout; + const ct = globalThis.clearTimeout; + const si = globalThis.setInterval; + const ci = globalThis.clearInterval; + globalThis.setTimeout = ((fn: (...a: unknown[]) => void, ms = 0, ...args: unknown[]) => { + const id = st(() => { + dues.delete(id); + fn(...args); + }, ms); + dues.set(id, { due: Date.now() + Math.max(0, ms) }); + return id; + }) as typeof setTimeout; + globalThis.clearTimeout = ((id?: unknown) => { + dues.delete(id); + if (id != null) ct(id as Parameters[0]); + }) as typeof clearTimeout; + globalThis.setInterval = ((fn: (...a: unknown[]) => void, ms = 0, ...args: unknown[]) => { + const every = Math.max(1, ms); + const id = si(() => { + const d = dues.get(id); + if (d) d.due += every; + fn(...args); + }, every); + dues.set(id, { due: Date.now() + every, every }); + return id; + }) as typeof setInterval; + globalThis.clearInterval = ((id?: unknown) => { + dues.delete(id); + if (id != null) ci(id as Parameters[0]); + }) as typeof clearInterval; +} +function realTimers() { + mock.timers.reset(); + dues.clear(); + Object.assign(globalThis, realTimerFns); +} +function setSystemTime(d: Date) { + mock.timers.setTime(d.getTime()); +} +async function settle() { + for (let i = 0; i < 10; i++) await new Promise((r) => setImmediate(r)); +} +async function advance(ms: number) { + const target = Date.now() + ms; + await settle(); + for (let guard = 0; ; guard++) { + if (guard > 100_000) throw new Error("advance: timers never settle"); + let next = Infinity; + for (const d of dues.values()) next = Math.min(next, d.due); + if (next > target) break; + mock.timers.tick(Math.max(0, next - Date.now())); + await settle(); + } + if (target > Date.now()) mock.timers.tick(target - Date.now()); + await settle(); +} +async function waitFor(check: () => void) { + for (let i = 0; ; i++) { + try { + check(); + return; + } catch (e) { + if (i > 1_000) throw e; + } + await new Promise((r) => setImmediate(r)); + } +} + +test("A -> save B -> outside restore to A merges A back into the buffer", async () => { + const puts: Array<{ body: string; ifMatch?: string }> = []; + globalThis.fetch = (async (_url: RequestInfo | URL, init?: RequestInit) => { + const headers = (init?.headers ?? {}) as Record; + puts.push({ body: String(init?.body), ifMatch: headers["If-Match"] }); + return new Response(JSON.stringify({ sha: "sha-b" }), { status: 200 }); + }) as typeof fetch; + + let buffer = "A\n"; + let solo = false; + const file = openSharedFile({ + apiBase: "/api/", // no co-editing route: solo, saved with If-Match + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "B\n"; + await file.saveNow(); + same(puts, [{ body: "B\n", ifMatch: "sha-a" }]); + + // Somebody restores the earlier version from History. + assert.equal(file.merge("A\n", "sha-a2"), "merged"); + assert.equal(buffer, "A\n"); + assert.equal(file.current(), "A\n"); + + // And it is now the version the buffer is built on: nothing left to save. + await file.saveNow(); + assert.equal(puts.length, 1); + + // The save's own echo while it is in flight is still recognised as ours. + buffer = "C\n"; + const gate = Promise.withResolvers(); + globalThis.fetch = (async (_url: RequestInfo | URL, init?: RequestInit) => { + puts.push({ body: String(init?.body) }); + await gate.promise; + return new Response(JSON.stringify({ sha: "sha-c" }), { status: 200 }); + }) as typeof fetch; + const saving = file.saveNow(); + await waitFor(() => assert.equal(puts.length, 2)); + assert.equal(file.merge("C\n", "sha-c"), "same"); + gate.resolve(); + await saving; + assert.equal(buffer, "C\n"); + file.destroy(); +}); + +/* A staging checkpoint the hub answers 503 (a write it could not land yet) + is re-sent on its own once the typing has stopped: nothing else would + ever send it. A permanent refusal is not retried. */ +test("staging checkpoint refused 503 once is retried until it saves", async () => { + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + fakeTimers(); + try { + const sent: string[] = []; + let answer = 503; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + sent.push(String(url)); + const body = JSON.parse(String(init?.body)) as { text: string }; + if (answer !== 200) return new Response(JSON.stringify({ error: "the edit is not written yet", retry: true }), { status: answer }); + return new Response(JSON.stringify({ sha: "sha-b", text: body.text }), { status: 200 }); + }) as typeof fetch; + + let buffer = "A\n"; + const states: string[] = []; + const savedTexts: string[] = []; + const file = openSharedFile({ + apiBase: "/api/p/proj/", // a hub with a room route: staging until live + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => {}, + onState: (s) => states.push(s), + onSaved: (t) => savedTexts.push(t), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + assert.ok(connect.mock.callCount() > 0); + + buffer = "B\n"; + await file.saveNow(); + assert.equal(sent.length, 1); + assert.ok(sent[0].includes("ycollab/sync")); + assert.equal(states.at(-1), "error"); + same(savedTexts, []); + + // The typing has stopped; nothing else asks. The endpoint recovers. + answer = 200; + await advance(SAVE_RETRY_MS[0]); + assert.equal(sent.length, 2); + same(savedTexts, ["B\n"]); + assert.equal(states.at(-1), "clean"); + + // Saved: no further attempts. + await advance(60_000); + assert.equal(sent.length, 2); + + // A permanent refusal is not looped on. + answer = 403; + buffer = "C\n"; + await file.saveNow(); + assert.equal(sent.length, 3); + await advance(60_000); + assert.equal(sent.length, 3); + + // A transient one keeps backing off, and destroy() ends it. + answer = 503; + await file.saveNow(); + assert.equal(sent.length, 4); + await advance(SAVE_RETRY_MS[0]); + assert.equal(sent.length, 5); + await advance(SAVE_RETRY_MS[1] - 1); + assert.equal(sent.length, 5); + await advance(1); + assert.equal(sent.length, 6); + file.destroy(); // sends the buffer once more, keepalive + const atDestroy = sent.length; + await advance(60_000); + assert.equal(sent.length, atDestroy); + } finally { + realTimers(); + connect.mock.restore(); + } +}); + +/* A PUT refused 409 rebases onto the file it lost to. When that read fails + for a moment, the stopped typing must still be saved once the hub + recovers: the retry timer is what sends it, not a next keystroke. */ +test("PUT 409 -> GET /file 503 -> stopped typing is retried and saved", async () => { + fakeTimers(); + try { + const log: string[] = []; + let getAnswer = 503; + let head = "A\nX\n"; + let headSha = "sha-x"; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = String(url); + const method = init?.method ?? "GET"; + log.push(method + " " + u); + if (method === "GET") { + if (getAnswer !== 200) return new Response("unavailable", { status: getAnswer }); + return new Response(head, { status: 200, headers: { ETag: `"${headSha}"` } }); + } + const headers = (init?.headers ?? {}) as Record; + if (headers["If-Match"] !== headSha) { + return new Response(JSON.stringify({ error: "changed", sha: headSha }), { status: 409 }); + } + head = String(init?.body); + headSha = "sha-saved"; + return new Response(JSON.stringify({ sha: headSha }), { status: 200 }); + }) as typeof fetch; + + let buffer = "A\n"; + let solo = false; + const states: string[] = []; + const savedTexts: string[] = []; + const file = openSharedFile({ + apiBase: "/api/", // no co-editing route: solo, saved with If-Match + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onState: (s) => states.push(s), + onSaved: (t) => savedTexts.push(t), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "B\n"; + await file.saveNow(); + // PUT refused 409, then the head read failed: nothing written, unsaved. + assert.equal((log.filter((l) => l.startsWith("PUT"))).length, 1); + assert.equal((log.filter((l) => l.startsWith("GET"))).length, 1); + assert.equal(states.at(-1), "error"); + same(savedTexts, []); + + // The typing has stopped. The hub recovers; the retry alone saves. + getAnswer = 200; + await advance(SAVE_RETRY_MS[0]); + assert.equal(head, "B\nX\n"); + assert.equal(buffer, "B\nX\n"); + assert.equal(savedTexts.at(-1), "B\nX\n"); + assert.equal(states.at(-1), "clean"); + + // Saved: no further attempts. + const settled = log.length; + await advance(60_000); + assert.equal(log.length, settled); + file.destroy(); + } finally { + realTimers(); + } +}); + +/* A buffer typed while the room's socket stalled, joining a room whose text + changed the same words another way, is parked as a conflict copy — and the + editor stays on that buffer until the copy has actually landed. A 503 on + the park is retried on the save backoff; only a stored copy swaps the + editor onto the shared document. */ +function joinHarness(who = "tester") { + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + const puts: Array<{ url: string; body: string; keepalive?: boolean }> = []; + const posts: string[] = []; + const net = { putAnswer: 503 }; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = String(url); + if (init?.method === "PUT") { + puts.push({ url: u, body: String(init.body), keepalive: init.keepalive }); + if (net.putAnswer !== 200) return new Response("unavailable", { status: net.putAnswer }); + return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + } + posts.push(u); + return new Response(JSON.stringify({ sha: "sha-room", text: "" }), { status: 200 }); + }) as typeof fetch; + + const state = { buffer: "the cat sat\n" }; + const ready: unknown[] = []; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/p/proj/", // a hub with a room route: staging until live + path: "notes.md", + seed: "the cat sat\n", + baseSha: "sha-a", + who, + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: (c) => ready.push(c), + onSolo: () => {}, + onConflictCopy: (c) => copies.push(c), + soloText: () => state.buffer, + soloApply: (e) => { + state.buffer = state.buffer.slice(0, e.from) + e.insert + state.buffer.slice(e.to); + }, + }); + // The room's document arrives over the socket: a remote-origin update. + const sock = { destroy() {} }; + const syncRoom = (text: string) => { + const c = file.collab as unknown as { + ws: unknown; + onStatus: (s: string) => void; + onReady: () => void; + }; + c.ws = sock; + file.collab.doc.transact(() => file.collab.text.insert(0, text), sock); + c.onStatus("live"); + c.onReady(); + }; + return { connect, puts, posts, net, state, ready, copies, file, syncRoom }; +} + +test("late join conflict: staging is kept until the conflict copy durably lands", async () => { + fakeTimers(); + const h = joinHarness(); + try { + // Socket stalled: the user types in staging, changing the same word. + h.state.buffer = "the dog sat\n"; + h.syncRoom("the bird sat\n"); + await advance(0); + + // merge3 cannot reconcile; the park was refused 503. + assert.equal(h.puts.length, 1); + assert.ok(h.puts[0].url.includes("upload/content?path=")); + assert.ok((decodeURIComponent(h.puts[0].url)).includes("notes.md.bdrive-conflict-tester-")); + assert.equal(h.puts[0].body, "the dog sat\n"); + // Still on the staging buffer: nothing swapped, nothing lost. + same(h.ready, []); + same(h.copies, []); + assert.equal(h.state.buffer, "the dog sat\n"); + assert.equal(h.file.current(), "the dog sat\n"); + // A save nudge while waiting writes nothing of its own to the room. + await advance(SAVE_RETRY_MS[0] - 1); + assert.equal(h.puts.length, 1); + same(h.posts, []); + + // The hub recovers: the retry parks the same copy and only then swaps. + h.net.putAnswer = 200; + await advance(1); + assert.equal(h.puts.length, 2); + assert.equal(h.puts[1].url, h.puts[0].url); + assert.equal(h.puts[1].body, "the dog sat\n"); + same(h.copies, [decodeURIComponent(h.puts[0].url.split("path=")[1])]); + same(h.ready, [h.file.collab]); + assert.equal(h.file.current(), "the bird sat\n"); + + // Joined: no further attempts. + await advance(60_000); + assert.equal(h.puts.length, 2); + same(h.posts, []); + h.file.destroy(); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("late join conflict: closing before the copy lands parks the buffer keepalive", async () => { + fakeTimers(); + const h = joinHarness(); + try { + h.state.buffer = "the dog sat\n"; + h.syncRoom("the bird sat\n"); + await advance(0); + assert.equal(h.puts.length, 1); + same(h.ready, []); + + h.file.destroy(); + assert.equal(h.puts.length, 2); + same(h.puts[1], { url: h.puts[0].url, body: "the dog sat\n", keepalive: true }); + // destroy() ended the retry. + await advance(60_000); + assert.equal(h.puts.length, 2); + same(h.ready, []); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +/* A park still on the wire when the tab closes with newer text: the slow PUT + may land AFTER the teardown keepalive. It must never overwrite the newer + words, so the teardown writes a name of its own — one second later, under + the user's own device name, for EVERY device name (a 32-character name + ending in "-close" is the one a suffix scheme would collide on). */ +for (const who of ["tester", "abcdefghijklmnopqrstuvwxyz-close"]) { + test(`late join conflict: a slow in-flight park never overwrites the teardown copy (who=${who})`, async () => { + fakeTimers(); + setSystemTime(new Date("2026-11-11T10:20:30.400Z")); + const h = joinHarness(who); + try { + const server = new Map(); + const order: string[] = []; + const slow = Promise.withResolvers(); + let first = true; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = decodeURIComponent(String(url)); + if (init?.method === "PUT") { + const body = String(init.body); + h.puts.push({ url: u, body, keepalive: init.keepalive }); + if (first) { + first = false; + await slow.promise; // PUT #1 hangs on the wire + } + server.set(u, body); + order.push(body); + return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + } + h.posts.push(u); + return new Response(JSON.stringify({ sha: "sha-room", text: "" }), { status: 200 }); + }) as typeof fetch; + + h.state.buffer = "v1 dog\n"; + h.syncRoom("v0 bird\n"); + await advance(0); + assert.equal(h.puts.length, 1); + assert.equal(h.puts[0].body, "v1 dog\n"); + + // The user keeps typing, then closes the tab in the SAME second while + // PUT #1 is in flight. + h.state.buffer = "v2 cat\n"; + h.file.destroy(); + await advance(0); + assert.equal(h.puts.length, 2); + assert.equal(h.puts[1].body, "v2 cat\n"); + assert.equal(h.puts[1].keepalive, true); + assert.notEqual(h.puts[1].url, h.puts[0].url); + same(order, ["v2 cat\n"]); + + // The slow PUT #1 lands after the teardown copy. + slow.resolve(); + await advance(0); + same(order, ["v2 cat\n", "v1 dog\n"]); + assert.equal(server.get(h.puts[1].url), "v2 cat\n"); + assert.equal(server.get(h.puts[0].url), "v1 dog\n"); + + // Both are well-formed copies under the user's own device name; the + // teardown one is stamped one second after the park. + const park = parseConflict(h.puts[0].url.split("path=")[1]); + const close = parseConflict(h.puts[1].url.split("path=")[1]); + assert.equal(park?.device, who); + assert.equal(close?.device, who); + assert.equal(park?.original, "notes.md"); + assert.equal(close?.original, "notes.md"); + assert.equal(close!.when.getTime() - park!.when.getTime(), 1000); + } finally { + realTimers(); + h.connect.mock.restore(); + } + }); +} + +/* Go textmerge.Merge parity: two different insertions at one anchor are both + kept (a log line appended again is a second line, not a retry), and over + an empty ancestor two different bodies are two documents: a conflict. */ +test("merge3 keeps both same-anchor insertions, matching textmerge.Merge", () => { + same(merge3("log\n", "log\nx\n", "log\nx\nx\n"), { ok: true, text: "log\nx\nx\nx\n" }); + same(merge3("log\n", "log\nx\nx\n", "log\nx\n"), { ok: true, text: "log\nx\nx\nx\n" }); + same(merge3("log\n", "log\nb\n", "log\na\n"), { ok: true, text: "log\na\nb\n" }); + same(merge3("log\n", "log\nx\n", "log\nx\n"), { ok: true, text: "log\nx\n" }); + same(merge3("", "x\n", "y\n"), { ok: false }); + same(merge3("", "y\n", "x\n"), { ok: false }); + same(merge3("", "x\n", "x\ny\n"), { ok: true, text: "x\ny\n" }); + same(merge3("", "x\ny\n", "x\n"), { ok: true, text: "x\ny\n" }); +}); + +/* Unterminated last lines are lines too: textmerge.Merge splits on "\n" and + decides the final newline on its own, so an appended line never glues onto + an unterminated one — in either argument order. */ +test("merge3 keeps an unterminated same-anchor insertion its own line, matching textmerge.Merge", () => { + same(merge3("log\n", "log\nx", "log\nx\nx"), { ok: true, text: "log\nx\nx\nx" }); + same(merge3("log\n", "log\nx\nx", "log\nx"), { ok: true, text: "log\nx\nx\nx" }); + same(merge3("log\n", "log\nx", "log\ny\n"), { ok: true, text: "log\nx\ny" }); + same(merge3("log\n", "log\ny\n", "log\nx"), { ok: true, text: "log\nx\ny" }); + same(merge3("a\nb\n", "a\nb", "a\nb\nc\n"), { ok: true, text: "a\nb\nc" }); + same(merge3("a\nb\n", "a\nb\nc\n", "a\nb"), { ok: true, text: "a\nb\nc" }); +}); + +/* A staging checkpoint the room refuses 409 while newer typing waits behind + it (its idle timer already fired into the in-flight loop). The refusal is + settled for the buffer as it is NOW: the conflict copy carries the newer + words, typing that lands while the copy is on the wire goes to the room + next, and a tab closed mid-park parks the newest words keepalive. */ +function stagingConflictHarness() { + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + const posts: { base_text?: string; text?: string }[] = []; + const puts: { url: string; body: string; keepalive?: boolean }[] = []; + const roomAnswers: Array> = []; + const putAnswers: Array> = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + puts.push({ url: decodeURIComponent(String(url)), body: String(init.body), keepalive: init.keepalive }); + const d = Promise.withResolvers(); + putAnswers.push(d); + return d.promise; + } + posts.push(JSON.parse(String(init?.body)) as { base_text?: string; text?: string }); + const d = Promise.withResolvers(); + roomAnswers.push(d); + return d.promise; + }) as typeof fetch; + const state = { buffer: "v0\n" }; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/p/proj/", + path: "notes.md", + seed: "v0\n", + baseSha: "sha-0", + who: "tester", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => {}, + onConflictCopy: (c) => copies.push(c), + soloText: () => state.buffer, + soloApply: (e) => { + state.buffer = state.buffer.slice(0, e.from) + e.insert + state.buffer.slice(e.to); + }, + }); + const clash = () => + new Response(JSON.stringify({ error: "the same lines changed in the live document", sha: "sha-room", text: "v1 theirs\n" }), { + status: 409, + }); + const ok = (body: object) => new Response(JSON.stringify(body), { status: 200 }); + return { connect, posts, puts, roomAnswers, putAnswers, state, copies, file, clash, ok }; +} + +test("staging 409 parks the NEWER buffer typed while the checkpoint was out, never the stale one", async () => { + fakeTimers(); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v1 conflict\n"; + void h.file.saveNow(); + await advance(0); + same(h.posts, [{ base: "sha-0", base_text: "v0\n", text: "v1 conflict\n" }]); + + // Typing continues and its idle timer fires while checkpoint #1 is out. + h.state.buffer = "v1 conflict + more important notes\n"; + void h.file.saveNow(); + await advance(700); + assert.equal(h.posts.length, 1); // single-flight + + // #1 is refused: the room changed the same line. + h.roomAnswers[0].resolve(h.clash()); + await advance(0); + assert.equal(h.puts.length, 1); + assert.equal(h.puts[0].body, "v1 conflict + more important notes\n"); + assert.ok(h.puts[0].url.includes("notes.md.bdrive-conflict-tester-")); + + // Even more typing lands while the copy is on the wire. + h.state.buffer = "v1 conflict + more important notes + p.s.\n"; + h.putAnswers[0].resolve(h.ok({ sha: "sha-copy" })); + await advance(0); + assert.equal(h.copies.length, 1); + // ...so it is not stranded: it goes to the room, built on what was parked. + assert.equal(h.posts.length, 2); + same(h.posts[1], { + base: "sha-room", + base_text: "v1 conflict + more important notes\n", + text: "v1 conflict + more important notes + p.s.\n", + }); + h.roomAnswers[1].resolve(h.ok({ sha: "sha-room-2", text: "v1 theirs + p.s.\n" })); + await advance(0); + assert.equal(h.posts.length, 2); + assert.equal(h.puts.length, 1); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("staging 409 whose newer typing clears the clash is rebased onto the room, not parked", async () => { + fakeTimers(); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v1 conflict\n"; + void h.file.saveNow(); + await advance(0); + // The user puts the line back and writes below it instead. + h.state.buffer = "v0\nnew line\n"; + void h.file.saveNow(); + h.roomAnswers[0].resolve(h.clash()); + await advance(0); + same(h.puts, []); + assert.equal(h.state.buffer, "v1 theirs\nnew line\n"); + same(h.posts[1], { base: "sha-room", base_text: "v1 theirs\n", text: "v1 theirs\nnew line\n" }); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("staging 409: closing the tab before the conflict copy lands parks the newest words keepalive", async () => { + fakeTimers(); + setSystemTime(new Date("2026-11-11T10:20:30.400Z")); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v1 conflict\n"; + void h.file.saveNow(); + await advance(0); + h.state.buffer = "v1 conflict + more important notes\n"; + void h.file.saveNow(); + await advance(700); + h.roomAnswers[0].resolve(h.clash()); + await advance(0); + assert.equal(h.puts.length, 1); // the park, on the wire + + // Typed more, then closed, while the park still hangs. + h.state.buffer = "v1 conflict + more important notes + last word\n"; + h.file.destroy(); + assert.equal(h.posts.length, 1); // not sent to the room to be refused again + assert.equal(h.puts.length, 2); + assert.equal(h.puts[1].body, "v1 conflict + more important notes + last word\n"); + assert.equal(h.puts[1].keepalive, true); + assert.ok(h.puts[1].url.includes("notes.md.bdrive-conflict-tester-")); + assert.notEqual(h.puts[1].url, h.puts[0].url); + + h.putAnswers[0].resolve(h.ok({ sha: "sha-copy" })); + h.putAnswers[1].resolve(h.ok({ sha: "sha-copy-2" })); + await advance(60_000); + assert.equal(h.posts.length, 1); + assert.equal(h.puts.length, 2); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +/* R10: a staging checkpoint refused 409 starts a slow park of "v1"; the user + types "v2" in the SAME second and the socket syncs, so join() parks "v2" + too. They must never share a name: conflictName stamps whole seconds, and + a "v1" PUT landing last on the same path would put the older words back + over the newer copy. (The join waits for the staging park — it is part of + the save loop the join lets finish first, R11 — so the two land in order, + but their names still differ.) */ +test("staging 409 park and join park in the same second never share a conflict path", async () => { + fakeTimers(); + setSystemTime(new Date("2026-11-11T10:20:30.400Z")); + const h = stagingConflictHarness(); + try { + const sock = { destroy() {} }; + const syncRoom = (text: string) => { + const c = h.file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + c.ws = sock; + h.file.collab.doc.transact(() => h.file.collab.text.insert(0, text), sock); + c.onStatus("live"); + c.onReady(); + }; + const server = new Map(); + const land = async (i: number) => { + server.set(h.puts[i].url, h.puts[i].body); + h.putAnswers[i].resolve(h.ok({ sha: `sha-copy-${i}` })); + await advance(0); + }; + + h.state.buffer = "v1\n"; + void h.file.saveNow(); + await advance(0); + assert.equal(h.posts.length, 1); + h.roomAnswers[0].resolve(h.clash()); + await advance(0); + // PUT #1: the staging park of "v1", slow. + assert.equal(h.puts.length, 1); + assert.equal(h.puts[0].body, "v1\n"); + + // Same second: the user types, and the room's document arrives. + h.state.buffer = "v2\n"; + // (The room changed the very word "v1" became, so "v2" clashes with it + // even built on the parked "v1".) + syncRoom("v9 theirs\n"); + await advance(0); + // The join waits for the staging park on the wire. + assert.equal(h.puts.length, 1); + + // PUT #1 lands; PUT #2: join() parks the newer buffer, under a new name. + await land(0); + assert.equal(h.puts.length, 2); + assert.equal(h.puts[1].body, "v2\n"); + assert.notEqual(h.puts[1].url, h.puts[0].url); + await land(1); + + assert.equal(server.get(h.puts[1].url), "v2\n"); + assert.equal(server.get(h.puts[0].url), "v1\n"); + const p1 = parseConflict(h.puts[0].url.split("path=")[1]); + const p2 = parseConflict(h.puts[1].url.split("path=")[1]); + assert.equal(p1?.original, "notes.md"); + assert.equal(p2?.original, "notes.md"); + assert.equal(p1?.device, "tester"); + assert.equal(p2?.device, "tester"); + assert.ok((p2!.when.getTime()) > p1!.when.getTime()); + same(h.copies.sort(), [h.puts[0].url, h.puts[1].url].map((u) => u.split("path=")[1]).sort()); + + // The room holds the buffer now; the late "v1" landing settled nothing: + // no further writes, and closing the tab writes nothing either. + assert.equal(h.file.current(), "v9 theirs\n"); + await advance(60_000); + assert.equal(h.posts.length, 1); + assert.equal(h.puts.length, 2); + h.file.destroy(); + assert.equal(h.puts.length, 2); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +/* R11: the socket syncs while a staging checkpoint is still on the wire. The + room applies the checkpoint (its own item IDs), and the same items reach + this tab twice — in the HTTP answer's `update` and on the socket. The join + must wait for the checkpoint, take its items, and splice only the typing + past it: two x lines, never three, and no second checkpoint. */ +for (const { frameFirst, name } of [ + { frameFirst: false, name: "socket frame after the HTTP answer" }, + { frameFirst: true, name: "socket frame before the HTTP answer" }, +]) test(`join waits for an in-flight staging checkpoint and lands it once (${name})`, async () => { + const Y = await import("yjs"); + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + fakeTimers(); + try { + const b64 = (u8: Uint8Array) => btoa(String.fromCharCode(...u8)); + // The hub's room, holding the file as it was. + const room = new Y.Doc(); + room.getText("body").insert(0, "log\n"); + const beforeCheckpoint = Y.encodeStateAsUpdate(room); + + const posts: Array<{ base_text?: string; text?: string }> = []; + const puts: string[] = []; + const gate = Promise.withResolvers(); + let applied: Uint8Array | null = null; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + puts.push(String(url)); + return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + } + const body = JSON.parse(String(init?.body)) as { base_text?: string; text?: string }; + posts.push(body); + // The room applies the checkpoint (handleYCollabSync's splice) the + // moment the request arrives; the answer is held back. + const before = Y.encodeStateVector(room); + const t = room.getText("body"); + t.delete(0, t.length); + t.insert(0, body.text ?? ""); + applied = Y.encodeStateAsUpdate(room, before); + await gate.promise; + return new Response( + JSON.stringify({ ok: true, sha: "sha-room", text: t.toString(), update: b64(Y.encodeStateAsUpdate(room)) }), + { status: 200 }, + ); + }) as typeof fetch; + + let buffer = "log\n"; + const ready: unknown[] = []; + const file = openSharedFile({ + apiBase: "/api/p/proj/", // a hub with a room route: staging until live + path: "notes.md", + seed: "log\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: (c) => ready.push(c), + onSolo: () => {}, + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + assert.ok(connect.mock.callCount() > 0); + + // Staging: a checkpoint of the first line goes out and hangs. + buffer = "log\nx\n"; + const saving = file.saveNow(); + await advance(0); + same(posts, [{ base_text: "log\n", text: "log\nx\n", base: "sha-a" }]); + + // The user keeps typing; its idle timer asks for a save while one is out. + buffer = "log\nx\nx\n"; + void file.saveNow(); + + // The socket syncs with the room as it was BEFORE the checkpoint. + const sock = { destroy() {} }; + const c = file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + c.ws = sock; + Y.applyUpdate(file.collab.doc, beforeCheckpoint, sock); + c.onStatus("live"); + c.onReady(); + await advance(0); + // The join is waiting on the checkpoint: nothing merged, nothing ready. + same(ready, []); + + const frame = () => Y.applyUpdate(file.collab.doc, applied!, sock); + if (frameFirst) frame(); + gate.resolve(); + await saving; + await advance(0); + // Joined on the HTTP answer alone: the document already holds the + // checkpoint (the room's items) and the typing past it, once each. + same(ready, [file.collab]); + assert.equal(file.collab.text.toString(), "log\nx\nx\n"); + if (!frameFirst) frame(); + + same(ready, [file.collab]); + assert.equal(file.collab.text.toString(), "log\nx\nx\n"); + assert.equal(file.current(), "log\nx\nx\n"); + // The room's state and this tab's converge on the same two lines. + Y.applyUpdate(room, Y.encodeStateAsUpdate(file.collab.doc)); + assert.equal(room.getText("body").toString(), "log\nx\nx\n"); + + // One checkpoint, ever: the join handed over the rest, the hub writes it. + await advance(60_000); + assert.equal(posts.length, 1); + same(puts, []); + file.destroy(); + } finally { + realTimers(); + connect.mock.restore(); + } +}); + +/* R12: a staging checkpoint fails AMBIGUOUSLY — a 502 the hub sends after it + already put the text into the room (its snapshot failed), or no answer at + all. Its items may still be on their way down the socket, which syncs a + stale room first. The join must ask the room (a read-only peek) before it + merges: if the room holds the checkpoint, only the typing past it is + spliced; if not, the whole buffer is. Two x lines either way, never three. */ +for (const { mode, name } of [ + { mode: "landed", name: "502 after the room applied it, plus a peer edit" }, + { mode: "dropped", name: "request never reached the hub" }, + { mode: "peekRetry", name: "502 after the room applied it, peek 503 once" }, +] as const) test(`ambiguous staging checkpoint is peeked before the join (${name})`, async () => { + const Y = await import("yjs"); + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + fakeTimers(); + try { + const b64 = (u8: Uint8Array) => btoa(String.fromCharCode(...u8)); + const room = new Y.Doc(); + room.getText("body").insert(0, "log\n"); + const beforeCheckpoint = Y.encodeStateAsUpdate(room); + + const posts: Array<{ base_text?: string; text?: string }> = []; + const peeks: number[] = []; + const puts: string[] = []; + let peekAnswer = mode === "peekRetry" ? 503 : 200; + let applied: Uint8Array | null = null; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + puts.push(String(url)); + return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + } + const body = JSON.parse(String(init?.body)) as { base_text?: string; text?: string; peek?: boolean }; + const t = room.getText("body"); + if (body.peek) { + peeks.push(peekAnswer); + if (peekAnswer !== 200) return new Response(JSON.stringify({ error: "busy", retry: true }), { status: peekAnswer }); + return new Response( + JSON.stringify({ ok: true, sha: "sha-a", text: t.toString(), update: b64(Y.encodeStateAsUpdate(room)) }), + { status: 200 }, + ); + } + posts.push(body); + if (mode === "dropped") throw new TypeError("Failed to fetch"); + // The room applies the checkpoint, then its snapshot fails: 502. + const before = Y.encodeStateVector(room); + t.delete(0, t.length); + t.insert(0, body.text ?? ""); + if (mode === "landed") t.insert(0, "peer\n"); // a co-editor, at the top + applied = Y.encodeStateAsUpdate(room, before); + return new Response("co-editing: storage unavailable", { status: 502 }); + }) as typeof fetch; + + let buffer = "log\n"; + const ready: unknown[] = []; + const file = openSharedFile({ + apiBase: "/api/p/proj/", // a hub with a room route: staging until live + path: "notes.md", + seed: "log\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: (c) => ready.push(c), + onSolo: () => {}, + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + assert.ok(connect.mock.callCount() > 0); + + buffer = "log\nx\n"; + await file.saveNow(); + assert.equal(posts.length, 1); + // The user keeps typing past the failed checkpoint. + buffer = "log\nx\nx\n"; + + // The socket syncs with the room as it was BEFORE the checkpoint; the + // frame carrying the checkpoint's items is still in flight. + const sock = { destroy() {} }; + const c = file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + c.ws = sock; + Y.applyUpdate(file.collab.doc, beforeCheckpoint, sock); + c.onStatus("live"); + c.onReady(); + await advance(0); + + if (mode === "peekRetry") { + // The peek failed: nothing merged, the editor stays on the buffer. + same(peeks, [503]); + same(ready, []); + assert.equal(file.collab.text.toString(), "log\n"); + peekAnswer = 200; + await advance(SAVE_RETRY_MS[0] - 1); + same(ready, []); + await advance(1); + same(peeks, [503, 200]); + } else { + same(peeks, [200]); + } + const want = mode === "landed" ? "peer\nlog\nx\nx\n" : "log\nx\nx\n"; + same(ready, [file.collab]); + assert.equal(file.collab.text.toString(), want); + + // The delayed frame arrives: the same item IDs, a no-op. + if (applied) Y.applyUpdate(file.collab.doc, applied, sock); + assert.equal(file.collab.text.toString(), want); + assert.equal(file.current(), want); + Y.applyUpdate(room, Y.encodeStateAsUpdate(file.collab.doc)); + assert.equal(room.getText("body").toString(), want); + + // No second checkpoint, no conflict copy: the hub writes the room. + await advance(60_000); + assert.equal(posts.length, 1); + same(puts, []); + file.destroy(); + } finally { + realTimers(); + connect.mock.restore(); + } +}); + +/* A file whose room the hub holds: the socket has synced `seed` and the join + is done. Every request is recorded; sync answers with the room's text. + `net` holds requests back (`hold`) or answers them with an error. */ +type Req = { url: string; method: string; body: string; keepalive?: boolean; ifMatch?: string }; +async function heldRoom(o: { apiBase?: string } = {}) { + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + Reflect.set(globalThis, "window", new EventTarget()); // what pagehide is dispatched on + const reqs: Req[] = []; + const ref: { file: SharedFile | null } = { file: null }; + // `head`: what a read of the file answers (Keep puts these bytes back). + const net: { hold: Promise | null; status: number; error: string; head: string } = { + hold: null, + status: 200, + error: "", + head: "a\nb\nc\n", + }; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const headers = (init?.headers ?? {}) as Record; + const method = init?.method ?? "GET"; + reqs.push({ url: String(url), method, body: String(init?.body ?? ""), keepalive: init?.keepalive, ifMatch: headers["If-Match"] }); + const sha = `sha-${reqs.length}`; + if (method === "GET") return new Response(net.head, { status: 200, headers: { ETag: '"sha-head"' } }); + const { status, error, hold } = net; + if (hold) await hold; + if (status !== 200) return new Response(error, { status }); + if (method === "PUT") return new Response(JSON.stringify({ sha }), { status: 200 }); + const body = JSON.parse(String(init?.body ?? "{}")) as { text?: string }; + let room = ""; + try { + room = ref.file?.collab.text.toString() ?? ""; + } catch { + // destroyed + } + return new Response(JSON.stringify({ ok: true, path: "notes.md", sha, text: body.text ?? room, merged: false }), { + status: 200, + }); + }) as typeof fetch; + + const seed = "a\nb\nc\n"; + const state = { buffer: seed }; + const states: string[] = []; + const pendings: number[] = []; + const asks: unknown[] = []; + const saved: string[] = []; + const file = openSharedFile({ + apiBase: o.apiBase ?? "/api/p/proj/", + path: "notes.md", + seed, + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => {}, + onState: (s) => states.push(s), + onSaved: (t) => saved.push(t), + onPending: (n) => pendings.push(n), + onShrinkRefused: (a) => asks.push(a), + soloText: () => state.buffer, + soloApply: (e) => { + state.buffer = state.buffer.slice(0, e.from) + e.insert + state.buffer.slice(e.to); + }, + }); + ref.file = file; + const sock = { destroy() {} }; + const c = file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + const goLive = async () => { + c.ws = sock; + file.collab.doc.transact(() => file.collab.text.insert(0, seed), sock); + c.onStatus("live"); + c.onReady(); + await advance(0); + }; + type Text = InstanceType["text"]; + const peerEdit = (fn: (t: Text) => void) => file.collab.doc.transact(() => fn(file.collab.text), sock); + const localEdit = (fn: (t: Text) => void) => file.collab.doc.transact(() => fn(file.collab.text)); + const addPeer = () => file.collab.awareness.states.set(4242, { user: { name: "peer" } }); + let destroyed = false; + const destroy = () => { + if (destroyed) return; + destroyed = true; + file.destroy(); + }; + const done = () => { + destroy(); + connect.mock.restore(); + Reflect.deleteProperty(globalThis, "window"); + }; + return { file, reqs, net, state, states, pendings, asks, saved, c, goLive, peerEdit, localEdit, addPeer, destroy, done }; +} + +const occurrences = (hay: string, needle: string) => hay.split(needle).length - 1; + +/* Eight people in one meeting note: every snapshot the hub writes is behind + the room by the time it comes back through the change stream — peers kept + typing, and deleting. It is this room's own past, so it is never the + "someone else changed this file" banner; it is the file now, so `saved` and + `base` move to it; and once it carries this tab's typing, "dirty" ends. An + outsider's rewrite that never went through the room still is the banner. */ +test("8 peers: a room snapshot behind newer edits is our past, never an outside write", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.addPeer(); + h.localEdit((t) => t.insert(t.length, "L\n")); + const withL = h.file.current(); + assert.equal(h.states.at(-1), "dirty"); + + // Peers type past it — more changes than the room's texts remembered — + // and one deletes a line. + for (let i = 0; i < 40; i++) h.peerEdit((t) => t.insert(0, `p${i}\n`)); + h.peerEdit((t) => t.delete(t.toString().indexOf("b\n"), 2)); + const roomNow = h.file.current(); + + // The hub's snapshot from before all that arrives late. + assert.equal(h.file.merge(withL, "sha-1"), "same"); + assert.equal(h.states.at(-1), "clean"); + assert.equal(h.file.current(), roomNow); // nothing spliced back in + assert.equal(occurrences(h.file.current(), "L\n"), 1); + assert.equal(occurrences(h.file.current(), "b\n"), 0); + + // Typing past a snapshot stays dirty until a snapshot carries it. + const beforeM = h.file.current(); + h.localEdit((t) => t.insert(t.length, "M\n")); + const withM = h.file.current(); + h.peerEdit((t) => t.insert(0, "q\n")); + assert.equal(h.file.merge(beforeM, "sha-2"), "same"); + assert.equal(h.states.at(-1), "dirty"); + assert.equal(h.file.merge(withM, "sha-3"), "same"); + assert.equal(h.states.at(-1), "clean"); + const now = h.file.current(); + assert.equal(now, "q\n" + withM); + + // None of it went over HTTP: in a live room the hub writes the file. + await advance(60_000); + same(h.reqs, []); + + // An unconditional outside rewrite over unsaved typing is still refused. + h.localEdit((t) => t.insert(t.length, "Z\n")); + assert.equal(h.file.merge("rewritten by a CLI\n", "sha-x"), "blocked"); + assert.equal(h.file.current(), now + "Z\n"); + + // `base` moved with the snapshots: the next write is built on sha-3. + h.c.onStatus("offline"); + h.localEdit((t) => t.insert(t.length, "O\n")); + await h.file.saveNow(); + assert.equal(h.reqs.length, 1); + assert.ok(h.reqs[0].url.includes("ycollab/sync?path=notes.md")); + const body = JSON.parse(h.reqs[0].body) as { base?: string; update?: string }; + assert.equal(body.base, "sha-3"); + assert.equal(typeof body.update, "string"); + } finally { + h.done(); + realTimers(); + } +}); + +/* Done and Mod-s are an explicit save. In a live room that hands the hub the + room's state — answered once storage holds it — but only when this tab has + typing no snapshot carries yet: clean, or a bystander, sends nothing. */ +test("saveNow in a live room sends the room's state only when there is typing to hand over", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + await h.file.saveNow(); + h.addPeer(); + h.peerEdit((t) => t.insert(0, "peer\n")); + await h.file.saveNow(); + same(h.reqs, []); + + h.localEdit((t) => t.insert(t.length, "mine\n")); + assert.equal(h.states.at(-1), "dirty"); + // Done and Mod-s at once: one request. + const a = h.file.saveNow(); + const b = h.file.saveNow(); + await Promise.all([a, b]); + assert.equal(h.reqs.length, 1); + assert.equal(h.reqs[0].method, "POST"); + assert.ok(h.reqs[0].url.includes("ycollab/sync?path=notes.md")); + assert.ok(!h.reqs[0].keepalive); + same(Object.keys(JSON.parse(h.reqs[0].body) as object), ["update"]); + same(h.states.slice(-2), ["saving", "clean"]); + assert.equal(h.saved.at(-1), h.file.current()); + + // Saved: a second Done sends nothing, and idle typing never writes. + await h.file.saveNow(); + assert.equal(h.reqs.length, 1); + h.localEdit((t) => t.insert(t.length, "more\n")); + await advance(60_000); + assert.equal(h.reqs.length, 1); + + // Leaving after Done sends nothing more either. + await h.file.saveNow(); + assert.equal(h.reqs.length, 2); + h.destroy(); + assert.equal(h.reqs.length, 2); + } finally { + h.done(); + realTimers(); + } +}); + +/* Closing the tab or reloading — no Done, no unmount — must not lose the + last words: pagehide sends what this tab alone holds, keepalive, and the + unmount that may follow finds it already sent. Nothing to hand over, + nothing sent. */ +for (const { mode, dirty } of [ + { mode: "live", dirty: true }, + { mode: "live", dirty: false }, + { mode: "offline", dirty: true }, + { mode: "offline", dirty: false }, + { mode: "staging", dirty: true }, + { mode: "staging", dirty: false }, + { mode: "solo", dirty: true }, + { mode: "solo", dirty: false }, +] as const) test(`pagehide flushes keepalive exactly once (${mode}, dirty=${dirty})`, async () => { + fakeTimers(); + const h = await heldRoom(mode === "solo" ? { apiBase: "/api/" } : {}); + try { + if (mode === "solo") await advance(0); // no room route: solo + if (mode === "live" || mode === "offline") { + await h.goLive(); + h.addPeer(); + h.peerEdit((t) => t.insert(0, "peer\n")); // a bystander's view moves too + } + if (mode === "offline") h.c.onStatus("offline"); + if (dirty) { + if (mode === "live" || mode === "offline") h.localEdit((t) => t.insert(t.length, "last words\n")); + else h.state.buffer += "last words\n"; + } + + window.dispatchEvent(new Event("pagehide")); + if (!dirty) { + same(h.reqs, []); + } else { + assert.equal(h.reqs.length, 1); + const r = h.reqs[0]; + assert.equal(r.keepalive, true); + if (mode === "solo") { + assert.equal(r.method, "PUT"); + assert.ok(r.url.includes("upload/content?path=notes.md")); + assert.equal(r.ifMatch, "sha-a"); + assert.equal(r.body, "a\nb\nc\nlast words\n"); + } else { + assert.equal(r.method, "POST"); + assert.ok(r.url.includes("ycollab/sync?path=notes.md")); + const body = JSON.parse(r.body) as { update?: string; text?: string }; + if (mode === "staging") assert.equal(body.text, "a\nb\nc\nlast words\n"); + else assert.equal(typeof body.update, "string"); + } + } + + // The unmount that follows does not send it again. + h.destroy(); + await advance(0); + assert.equal(h.reqs.length, dirty ? 1 : 0); + } finally { + h.done(); + realTimers(); + } +}); + +/* Offline edits are acknowledged by watermark. Two saves while one flush is + on the wire share it, and the loop sends once more for the typing that + came after — so `pending` walks 1, 2, 1, 0 and never goes below what is + really unsent, however the answers interleave. */ +test("offline flushes are single-flight and acknowledged by watermark, never subtracted twice", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.c.onStatus("offline"); + const gate = Promise.withResolvers(); + h.net.hold = gate.promise; + h.localEdit((t) => t.insert(t.length, "x\n")); + const a = h.file.saveNow(); + await advance(0); + assert.equal(h.reqs.length, 1); + h.localEdit((t) => t.insert(t.length, "y\n")); + const b = h.file.saveNow(); // Done while the first is out: the same loop + h.net.hold = null; + await advance(0); + assert.equal(h.reqs.length, 1); + + gate.resolve(); + await Promise.all([a, b]); + assert.equal(h.reqs.length, 2); + same(h.pendings, [1, 2, 1, 0]); + + // Everything acknowledged: the offline timer and the exit send nothing. + await advance(60_000); + h.destroy(); + assert.equal(h.reqs.length, 2); + } finally { + h.done(); + realTimers(); + } +}); + +/* The typing counts as handed over only once the hub answers. A pagehide + whose keepalive failed — the page then restored from the back/forward + cache — still has it to send on Done; one still on the wire is not sent + twice in the same unload, but a page shown again may send it on its next + exit. */ +test("a failed or bfcache-restored pagehide flush leaves the typing to be sent again", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.localEdit((t) => t.insert(t.length, "last words\n")); + h.net.status = 503; + window.dispatchEvent(new Event("pagehide")); + await advance(0); + assert.equal(h.reqs.length, 1); + assert.equal(h.reqs[0].keepalive, true); + + // The page stayed: Done still sends it. + h.net.status = 200; + await h.file.saveNow(); + assert.equal(h.reqs.length, 2); + assert.ok(!h.reqs[1].keepalive); + assert.equal(h.states.at(-1), "clean"); + + h.localEdit((t) => t.insert(t.length, "more\n")); + const gate = Promise.withResolvers(); + h.net.hold = gate.promise; + window.dispatchEvent(new Event("pagehide")); + window.dispatchEvent(new Event("pagehide")); // the same state is on the wire + assert.equal(h.reqs.length, 3); + window.dispatchEvent(new Event("pageshow")); // back from the bfcache + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.reqs.length, 4); + + h.net.hold = null; + gate.resolve(); + await advance(0); + // Landed: nothing left for Done or the unmount. + await h.file.saveNow(); + h.destroy(); + assert.equal(h.reqs.length, 4); + } finally { + h.done(); + realTimers(); + } +}); + +/* Done in a live room the hub refuses for emptying the file: the user is + asked at once (the caller stays on the editor), a second Done sends + nothing while the question is open, and confirming writes it. */ +test("an explicit live save refused for a sharp shrink asks the user and waits", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.localEdit((t) => t.delete(0, t.length)); + h.net.status = 422; + h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); + await h.file.saveNow(); + assert.equal(h.reqs.length, 1); + assert.equal(h.asks.length, 1); + assert.equal(h.file.askingShrink(), true); + assert.equal(h.states.at(-1), "error"); + + await h.file.saveNow(); + await advance(60_000); // nor does the idle check stack a second dialog + assert.equal(h.reqs.length, 1); + assert.equal(h.asks.length, 1); + + h.net.status = 200; + await (h.asks[0] as ShrinkAsk).confirm(); + assert.equal(h.reqs.length, 2); + const body = JSON.parse(h.reqs[1].body) as { confirm_shrink?: boolean }; + assert.equal(body.confirm_shrink, true); + assert.equal(h.file.askingShrink(), false); + assert.equal(h.states.at(-1), "clean"); + } finally { + h.done(); + realTimers(); + } +}); + +/* The room's remembered past starts after `saved`. Once a snapshot with "d" + is the file, a restore to the text from before "d" — made outside the + room, over unsaved typing — is not this room's history: it is refused. */ +test("a restore to a state older than `saved` is an outside write, not the room's past", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.localEdit((t) => t.insert(t.length, "d\n")); + assert.equal(h.file.merge(h.file.current(), "sha-1"), "same"); + h.localEdit((t) => t.insert(t.length, "e\n")); + assert.equal(h.file.merge("a\nb\nc\n", "sha-r"), "blocked"); + assert.equal(h.file.current(), "a\nb\nc\nd\ne\n"); + } finally { + h.done(); + realTimers(); + } +}); + +/* The same refusal with the socket down: Done's offline flush is answered + 422. No retry can land an unconfirmed shrink, so the user is asked at once + and nothing is re-sent while the question is open; confirming hands the + queued edits over and leaves nothing pending. */ +test("an offline explicit save refused for a sharp shrink asks at once and never retries unconfirmed", async () => { + fakeTimers(); + const h = await heldRoom(); + try { + await h.goLive(); + h.c.onStatus("offline"); + h.localEdit((t) => t.delete(0, t.length)); + h.net.status = 422; + h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); + await h.file.saveNow(); + assert.equal(h.reqs.length, 1); + assert.equal(h.file.askingShrink(), true); + assert.equal(h.asks.length, 1); + assert.equal(h.pendings.at(-1), 1); + + await advance(60_000); // the offline timer and the idle check stay quiet + assert.equal(h.reqs.length, 1); + assert.equal(h.asks.length, 1); + + h.net.status = 200; + await (h.asks[0] as ShrinkAsk).confirm(); + assert.equal(h.reqs.length, 2); + const body = JSON.parse(h.reqs[1].body) as { confirm_shrink?: boolean; update?: string }; + assert.equal(body.confirm_shrink, true); + assert.equal(typeof body.update, "string"); + assert.equal(h.file.askingShrink(), false); + assert.equal(h.pendings.at(-1), 0); + assert.equal(h.states.at(-1), "clean"); + + await advance(60_000); + h.destroy(); + assert.equal(h.reqs.length, 2); + } finally { + h.done(); + realTimers(); + } +}); + +/* Keep, with the socket down, after the offline flush was refused for a + sharp shrink: that refused update had already reached the room's document, + so the room holds the shrunk text. Putting the file's bytes back is an edit + the room must get — over HTTP at once, or, if that fails, still queued for + the retry, pagehide and the unmount. */ +for (const keepAnswer of [200, 503]) { + test(`offline Keep after a shrink refusal hands the restored text to the room (answer ${keepAnswer})`, async () => { + const Y = await import("yjs"); + const roomText = (b64: string) => { + const d = new Y.Doc(); + Y.applyUpdate(d, Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))); + return d.getText("body").toString(); + }; + fakeTimers(); + const h = await heldRoom(); + const posts = () => h.reqs.filter((r) => r.method === "POST"); + try { + await h.goLive(); + h.c.onStatus("offline"); + h.localEdit((t) => t.delete(0, t.length)); + h.net.status = 422; + h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); + await h.file.saveNow(); + assert.equal(posts().length, 1); + assert.equal(h.file.askingShrink(), true); + + h.net.status = keepAnswer; + h.net.error = "unavailable"; + await (h.asks[0] as ShrinkAsk).keep(); + assert.equal(h.file.askingShrink(), false); + assert.equal(h.file.current(), "a\nb\nc\n"); + assert.equal(posts().length, 2); + const sent = JSON.parse(posts()[1].body) as { update?: string; confirm_shrink?: boolean }; + assert.equal(sent.confirm_shrink, undefined); + assert.equal(roomText(sent.update ?? ""), "a\nb\nc\n"); + + if (keepAnswer === 200) { + assert.equal(h.pendings.at(-1), 0); + assert.equal(h.states.at(-1), "clean"); + await advance(60_000); + h.destroy(); + assert.equal(posts().length, 2); + } else { + // Not handed over: still queued, and a closing tab still sends it. + assert.ok((h.pendings.at(-1) ?? 0) > 0); + assert.equal(h.states.at(-1), "dirty"); + window.dispatchEvent(new Event("pagehide")); + assert.equal(posts().length, 3); + assert.equal(posts()[2].keepalive, true); + const exit = JSON.parse(posts()[2].body) as { update?: string }; + assert.equal(roomText(exit.update ?? ""), "a\nb\nc\n"); + } + } finally { + h.done(); + realTimers(); + } + }); +} diff --git a/internal/webapp/mcp.go b/internal/webapp/mcp.go index ab744f11..4bbff392 100644 --- a/internal/webapp/mcp.go +++ b/internal/webapp/mcp.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -1458,7 +1459,15 @@ func (s *Server) mcpWrite(ctx context.Context, in writeIn) (string, error) { // version rides along as the upload's If-Match, so a write that lands // between the two is caught where the op is appended. if base, err = s.checkStale(ctx, project, rest, in.SHA, in.Path); err != nil { - return "", err + // Moved on since the agent read it: the version it read is still + // the base, and the upload door merges this content with what + // landed since, three ways. Only the same lines rewritten two + // ways come back as stale. + var st *staleShaError + if !errors.As(err, &st) { + return "", err + } + base = st.base } } msg, err := s.putFile(ctx, project, rest, []byte(in.Content), "wrote", base) @@ -1498,15 +1507,29 @@ func (s *Server) checkStale(ctx context.Context, project, rest, want, shown stri // false and unrecoverable: the retry reads, gets the same current sha, // and fails again the same way. restore already discriminates; this is // the same question, asked before the accusation. - if _, err := s.resolveSHA(ctx, project, rest, want); err != nil { + full, err := s.resolveSHA(ctx, project, rest, want) + if err != nil { return "", err } - return "", fmt.Errorf("stale: %s has changed since you read it (now sha %s). Read it again, then retry", - shown, short(fi.Blob)) + return "", &staleShaError{ + msg: fmt.Sprintf("stale: %s has changed since you read it (now sha %s). Read it again, then retry", + shown, short(fi.Blob)), + base: full, + } } return fi.Blob, nil } +// staleShaError is checkStale's refusal for a sha that names a real, older +// version of the file. base is that version in full, so a writer can merge +// from it instead of failing. +type staleShaError struct { + msg string + base string +} + +func (e *staleShaError) Error() string { return e.msg } + // putFile is the one write path, shared by write/edit/move/restore-as-copy: // a single-shot relay upload to the hub's own endpoint. Everything that makes // a write safe — the read-only check, path validation, folder permissions, @@ -1580,9 +1603,18 @@ func (s *Server) mcpEdit(ctx context.Context, in editIn) (string, error) { // putFile below), so of two concurrent edits replacing the one occurrence // of a token, the second is refused as stale instead of both reporting // "1 replacement(s)". + // A sha the file has moved on from is not refused outright: the edit is + // made on the version the agent read, and the upload door merges it with + // what landed since. Only the same lines changed two ways stay stale. + var staleBase string + var staleErr error if in.SHA != "" { if _, err := s.checkStale(ctx, project, rest, in.SHA, in.Path); err != nil { - return "", err + var st *staleShaError + if !errors.As(err, &st) { + return "", err + } + staleBase, staleErr = st.base, err } } _, v, err := s.projectVolume(project) @@ -1601,10 +1633,21 @@ func (s *Server) mcpEdit(ctx context.Context, in editIn) (string, error) { if isBinary(data) { return "", fmt.Errorf("%s is a binary file; edit only works on text", in.Path) } + putBase := fi.Blob + if staleBase != "" { + was, ok := s.blobText(ctx, project, staleBase) + if !ok || len(was) > maxReadBytes || isBinary([]byte(was)) { + return "", staleErr + } + data, putBase = []byte(was), staleBase + } body := string(data) n := strings.Count(body, in.OldString) switch { case n == 0: + if staleErr != nil { + return "", staleErr + } return "", fmt.Errorf("old_string not found in %s", in.Path) case n > 1 && !in.ReplaceAll: return "", fmt.Errorf("old_string appears %d times in %s; pass replace_all or include more context", n, in.Path) @@ -1619,10 +1662,11 @@ func (s *Server) mcpEdit(ctx context.Context, in editIn) (string, error) { } else { body = strings.Replace(body, in.OldString, in.NewString, 1) } - // Held to fi, the version the substitution was made on, whether or not the - // agent named one: an edit is a read-modify-write, and a write that lands - // after the read must refuse it rather than be overwritten by it. - msg, err := s.putFile(ctx, project, rest, []byte(body), "edited", fi.Blob) + // Held to the version the substitution was made on — fi, or the older + // one the agent read — whether or not the agent named one: an edit is a + // read-modify-write, and a write that lands after the read is merged + // with it or refuses it, never overwritten by it. + msg, err := s.putFile(ctx, project, rest, []byte(body), "edited", putBase) if err != nil { return "", err } diff --git a/internal/webapp/server.go b/internal/webapp/server.go index f82565c2..34e3d242 100644 --- a/internal/webapp/server.go +++ b/internal/webapp/server.go @@ -1703,6 +1703,9 @@ func (s *Server) Handler() http.Handler { // overwrites it with the name the hub derives — but the route has to // match for the request to reach the place that overwrites it. mux.HandleFunc("GET "+prefix+"ycollab/{room...}", resolve(PermRead, s.handleYCollab)) + // A client's state merged into the live room over plain HTTP (no + // socket, or a shrink to confirm). It writes, so it needs write. + mux.HandleFunc("POST "+prefix+"ycollab/sync", resolve(PermWrite, s.handleYCollabSync)) mux.HandleFunc("POST "+prefix+"upload/init", resolve(PermWrite, s.handleUploadInit)) mux.HandleFunc("PUT "+prefix+"upload/content", resolve(PermWrite, s.handleUploadContent)) mux.HandleFunc("POST "+prefix+"upload/commit", resolve(PermWrite, s.handleUploadCommit)) diff --git a/internal/webapp/static/assets/Editor-m3pwH2dA.js b/internal/webapp/static/assets/Editor-CUvVSG63.js similarity index 72% rename from internal/webapp/static/assets/Editor-m3pwH2dA.js rename to internal/webapp/static/assets/Editor-CUvVSG63.js index 659fa61a..35abb1be 100644 --- a/internal/webapp/static/assets/Editor-m3pwH2dA.js +++ b/internal/webapp/static/assets/Editor-CUvVSG63.js @@ -1,30 +1,30 @@ -import{s as ir,b as Ir,o as PO,p as Wh,c as vO,r as oe,d as TO,f as CO,e as ZO,g as XO,j as kn,t as kl,w as AO,a as RO}from"./index-Bnuge9vv.js";import{r as wl,b as Ni,a as Xs,c as As,d as $l,m as MO,e as jO,f as Nr,t as wn,g as $n,U as LO,S as YO,o as EO}from"./sharedfile-nk3qnjVG.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Rs=[],Vh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Vh[i])e=i+1;else return!0;if(e==t)return!1}}function Pl(n){return n>=127462&&n<=127487}const vl=8205;function _O(n,e,t=!0,i=!0){return(t?Bh:WO)(n,e,i)}function Bh(n,e,t){if(e==n.length)return e;e&&qh(n.charCodeAt(e))&&Dh(n.charCodeAt(e-1))&&e--;let i=Gr(n,e);for(e+=Tl(i);e=0&&Pl(Gr(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function WO(n,e,t){for(;e>1;){let i=Bh(n,e-2,t);if(i=56320&&n<57344}function Dh(n){return n>=55296&&n<56320}function Tl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),tt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),tt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new zi(this),s=new zi(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new zi(this,e)}iterRange(e,t=this.length){return new Ih(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Nh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):tt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=VO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new BO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Cl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=In(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=In(this.text,In(i.text,Cl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):tt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` -`){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class tt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new tt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof tt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof tt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:tt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new tt(l,t)}}_.empty=new ie([""],0);function VO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function In(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Ih{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new zi(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Nh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},zi.prototype[Symbol.iterator]=Ih.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=function(){return this});let BO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return _O(n,e,t,i)}function qO(n){return n>=56320&&n<57344}function DO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!DO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return qO(i)?(t-55296<<10)+(i-56320)+65536:t}function IO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const Ms=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class ot{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new ot(e)}static create(e){return new ot(e)}}class re extends ot{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return js(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ls(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||Ms)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ls(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Gi(n),l=new Gi(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Gi{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Uh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Xo=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Xo++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ao),!!e.static,e.enables)}of(e){return new Nn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Nn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Nn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ao(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Nn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Xo++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Ys(f,c)){let O=i(f);if(l?!Zl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=rr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof _e?u.field(g,!1)==f.field(g,!1):!0)||(l?Zl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Zl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Pn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(Pn),o=r.facet(Pn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,Pn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ti(n){return e=>new Fh(e,n)}const Nt={highest:Ti(Yt.highest),high:Ti(Yt.high),default:Ti(Yt.default),low:Ti(Yt.low),lowest:Ti(Yt.lowest)};class Fh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class fn{of(e){return new Es(this,e)}reconfigure(e){return fn.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Es{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class nr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of GO(e,t,o))u instanceof _e?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ao(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>NO(g,d,O))}}let f=h.map(u=>u(l));return new nr(e,o,f,l,a,s)}}function GO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof Es&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof Es){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Fh)s(o.inner,o.prec);else if(o instanceof _e)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Nn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function _i(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function rr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Hh=Z.define(),zs=Z.define({combine:n=>n.some(e=>e),static:!0}),Kh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),Jh=Z.define(),ec=Z.define(),tc=Z.define(),ic=Z.define({combine:n=>n.length?n[0]:!1});class Ie{constructor(e,t){this.type=e,this.value=t}static define(){return new UO}}class UO{of(e){return new Ie(this,e)}}class FO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new FO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Uh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ie.define();ne.userEvent=Ie.define();ne.addToHistory=Ie.define();ne.remote=Ie.define();function HO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=rc(e,ri(s),!1)}return n}function JO(n){let e=n.startState,t=e.facet(tc),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=nc(i,_s(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const ed=[];function ri(n){return n==null?ed:Array.isArray(n)?n:[n]}var pt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(pt||(pt={}));const td=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Ws;try{Ws=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function id(n){if(Ws)return Ws.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||td.test(t)))return!0}return!1}function nd(n){return e=>{if(!/\S/.test(e))return pt.Space;if(id(e))return pt.Word;for(let t=0;t-1)return pt.Word;return pt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=nr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(zs)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=nr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||Ms)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Uh(r,i.length),t.staticFacet(zs)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` -`}get readOnly(){return this.facet(ic)}phrase(e,...t){for(let i of this.facet(W.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?i:t[s-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let s of this.facet(Hh))for(let o of s(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return nd(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=fe(t,o,!1);if(s(t.slice(a,o))!=pt.Word)break;o=a}for(;ln.length?n[0]:4});W.lineSeparator=Kh;W.readOnly=ic;W.phrases=Z.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(r=>n[r]==e[r])}});W.languageData=Hh;W.changeFilter=Jh;W.transactionFilter=ec;W.transactionExtender=tc;fn.reconfigure=V.define();function Xr(n,e,t={}){let i={};for(let r of n)for(let s of Object.keys(r)){let o=r[s],l=i[s];if(l===void 0)i[s]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,s))i[s]=t[s](l,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}class vt{eq(e){return this==e}range(e,t=e){return Vs.create(e,t,this)}}vt.prototype.startSide=vt.prototype.endSide=0;vt.prototype.point=!1;vt.prototype.mapMode=me.TrackDel;function Ro(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let Vs=class sc{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new sc(e,t,i)}};function Bs(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class Mo{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return Ht(this.to)}findIndex(e,t,i,r=0){let s=i?this.to:this.from;for(let o=r,l=s.length;;){if(o==l)return o;let a=o+l>>1,h=s[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,s);sg||p==g&&u.startSide>0&&u.endSide<=0)continue;if(!((g-p||u.endSide-u.startSide)<0))if(h<0&&(h=p),u.point&&(c=Math.max(c,g-p)),(p-i||u.startSide-r)>=0)o.push(u),l.push(p-h),a.push(g-h),i=g,r=u.endSide;else{if(p==g)for(let S=o.length;S>0;S--){if((p-(a[S-1]+h)||u.startSide-o[S-1].endSide)>=0){o.splice(S,0,u),l.splice(S,0,p-h),a.splice(S,0,g-h);continue e}if((p-(l[S-1]+h)||u.endSide-o[S-1].startSide)>0)break}s(p,g,u)}}return{mapped:o.length?new Mo(l,a,o,c):null,pos:h}}}class E{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new E(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Bs)),this.isEmpty)return t.length?E.of(t):this;let l=new oc(this,null,-1).goto(0),a=0,h=[],c=new si;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value,!1)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||sl.to||s{s||(s=new si),s.addRange(a,h,c,!1)};for(let a=0;a=s&&e<=s+o.length&&o.between(s,e-s,t-s,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Ui.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Ui.from(e).goto(t)}static compare(e,t,i,r,s=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=s),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=s),a=Xl(o,l,i),h=new Ci(o,a,s),c=new Ci(l,a,s);i.iterGaps((f,u,O)=>Al(h,f,c,u,O,r)),i.empty&&i.length==0&&Al(h,0,c,0,0,r)}static eq(e,t,i=0,r){r==null&&(r=999999999);let s=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let l=Xl(s,o),a=new Ci(s,l,0).goto(i),h=new Ci(o,l,0).goto(i);for(;;){if(a.to!=h.to||!qs(a.active,h.active)||a.point&&(!h.point||!Ro(a.point,h.point)))return!1;if(a.to>r)return!0;a.next(),h.next()}}static spans(e,t,i,r,s=-1){let o=new Ci(e,null,s).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroml&&(r.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new si;for(let r of e instanceof Vs?[e]:t?rd(e):e)i.add(r.from,r.to,r.value);return i.finish()}static join(e){if(!e.length)return E.empty;let t=Ht(e);for(let i=e.length-2;i>=0;i--)for(let r=e[i];r!=E.empty;r=r.nextLayer)t=new E(r.chunkPos,r.chunk,t,Math.max(r.maxPoint,t.maxPoint));return t}}E.empty=new E([],[],null,-1);function Ht(n){return n[n.length-1]}function rd(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Bs);e=i}return n}E.empty.nextLayer=E.empty;class si{finishChunk(e){this.chunks.push(new Mo(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addRange(e,t,i,!0)}addRange(e,t,i,r){this.addInner(e,t,i,r)||(this.nextLayer||(this.nextLayer=new si)).addRange(e,t,i,r)}addInner(e,t,i,r){let s=e-this.lastTo||i.startSide-this.last.endSide;if(r&&s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(E.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=E.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function Xl(n,e,t){let i=new Map;for(let s of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&r.push(new oc(o,t,i,s));return r.length==1?r[0]:new Ui(r)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Ur(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Ur(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Ur(this.heap,0)}}}function Ur(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let r=n[i];if(i+1=0&&(r=n[i+1],i++),t.compare(r)<0)break;n[i]=t,n[e]=r,e=i}}class Ci{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Ui.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){vn(this.active,e),vn(this.activeTo,e),vn(this.activeRank,e),this.minActive=Rl(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:r,rank:s}=this.cursor;for(;t0;)t++;Tn(this.active,t,i),Tn(this.activeTo,t,r),Tn(this.activeRank,t,s),e&&Tn(e,t,this.cursor.from),this.minActive=Rl(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),i&&vn(i,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[r]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Al(n,e,t,i,r,s){n.goto(e),t.goto(i);let o=i+r,l=i,a=i-e,h=!!s.boundChange;for(let c=!1;;){let f=n.to+a-t.to,u=f||n.endSide-t.endSide,O=u<0?n.to+a:t.to,d=Math.min(O,o);if(n.point||t.point?(n.point&&t.point&&Ro(n.point,t.point)&&qs(n.activeForPoint(n.to),t.activeForPoint(t.to))||s.comparePoint(l,d,n.point,t.point),c=!1):(c&&s.boundChange(l),d>l&&!qs(n.active,t.active)&&s.compareRange(l,d,n.active,t.active),h&&do)break;l=O,u<=0&&n.next(),u>=0&&t.next()}}function qs(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function Rl(n,e){let t=-1,i=1e9;for(let r=0;r=e)return r;if(r==n.length)break;s+=n.charCodeAt(r)==9?t-s%t:1,r=fe(n,r)}return n.length}const Ds="ͼ",Ml=typeof Symbol>"u"?"__"+Ds:Symbol.for(Ds),Is=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),jl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class Tt{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let O in l){let d=l[O];if(/&/.test(O))s(O.split(/,\s*/).map(p=>o.map(g=>p.replace(/&/,g))).reduce((p,g)=>p.concat(g)),d,a);else if(d&&typeof d=="object"){if(!f)throw new RangeError("The value of a property ("+O+") should be a primitive value.");s(r(O),d,c,u)}else d!=null&&c.push(O.replace(/_.*/,"").replace(/[A-Z]/g,p=>"-"+p.toLowerCase())+": "+d+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` -`)}static newName(){let e=jl[Ml]||1;return jl[Ml]=e+1,Ds+e.toString(36)}static mount(e,t,i){let r=e[Is],s=i&&i.nonce;r?s&&r.setNonce(s):r=new od(e,s),r.mount(Array.isArray(t)?t:[t],e)}}let Ll=new Map;class od{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let s=Ll.get(i);if(s)return e[Is]=s;this.sheet=new r.CSSStyleSheet,Ll.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Is]=this}mount(e,t){let i=this.sheet,r=0,s=0;for(let o=0;o-1&&(this.modules.splice(a,1),s--,a=-1),a==-1){if(this.modules.splice(s++,0,l),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},ld=typeof navigator<"u"&&/Mac/.test(navigator.platform),ad=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var he=0;he<10;he++)Ct[48+he]=Ct[96+he]=String(he);for(var he=1;he<=24;he++)Ct[he+111]="F"+he;for(var he=65;he<=90;he++)Ct[he]=String.fromCharCode(he+32),Fi[he]=String.fromCharCode(he);for(var Fr in Ct)Fi.hasOwnProperty(Fr)||(Fi[Fr]=Ct[Fr]);function hd(n){var e=ld&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||ad&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Fi:Ct)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}let pe=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Ns=typeof document<"u"?document:{documentElement:{style:{}}};const Gs=/Edge\/(\d+)/.exec(pe.userAgent),lc=/MSIE \d/.test(pe.userAgent),Us=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pe.userAgent),Ar=!!(lc||Us||Gs),Yl=!Ar&&/gecko\/(\d+)/i.test(pe.userAgent),Hr=!Ar&&/Chrome\/(\d+)/.exec(pe.userAgent),El="webkitFontSmoothing"in Ns.documentElement.style,Fs=!Ar&&/Apple Computer/.test(pe.vendor),zl=Fs&&(/Mobile\/\w+/.test(pe.userAgent)||pe.maxTouchPoints>2);var P={mac:zl||/Mac/.test(pe.platform),windows:/Win/.test(pe.platform),linux:/Linux|X11/.test(pe.platform),ie:Ar,ie_version:lc?Ns.documentMode||6:Us?+Us[1]:Gs?+Gs[1]:0,gecko:Yl,gecko_version:Yl?+(/Firefox\/(\d+)/.exec(pe.userAgent)||[0,0])[1]:0,chrome:!!Hr,chrome_version:Hr?+Hr[1]:0,ios:zl,android:/Android\b/.test(pe.userAgent),webkit:El,webkit_version:El?+(/\bAppleWebKit\/(\d+)/.exec(pe.userAgent)||[0,0])[1]:0,safari:Fs,safari_version:Fs?+(/\bVersion\/(\d+(\.\d+)?)/.exec(pe.userAgent)||[0,0])[1]:0,tabSize:Ns.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function jo(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const sr=Object.create(null);function Lo(n,e,t){if(n==e)return!0;n||(n=sr),e||(e=sr);let i=Object.keys(n),r=Object.keys(e);if(i.length-0!=r.length-0)return!1;for(let s of i)if(s!=t&&(r.indexOf(s)==-1||n[s]!==e[s]))return!1;return!0}function cd(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function _l(n,e,t){let i=!1;if(e)for(let r in e)t&&r in t||(i=!0,r=="style"?n.style.cssText="":n.removeAttribute(r));if(t)for(let r in t)e&&e[r]==t[r]||(i=!0,r=="style"?n.style.cssText=t[r]:n.setAttribute(r,t[r]));return i}function fd(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Vt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,r;if(e.isBlockGap)i=-5e8,r=4e8;else{let{start:s,end:o}=ac(e,t);i=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new Vt(e,i,r,t,e.widget||null,!0)}static line(e){return new On(e)}static set(e,t=!1){return E.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}M.none=E.empty;class un extends M{constructor(e){let{start:t,end:i}=ac(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?jo(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||sr}eq(e){return this==e||e instanceof un&&this.tagName==e.tagName&&Lo(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}un.prototype.point=!1;class On extends M{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof On&&this.spec.class==e.spec.class&&Lo(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}On.prototype.mapMode=me.TrackBefore;On.prototype.point=!0;class Vt extends M{constructor(e,t,i,r,s,o){super(t,i,s,e),this.block=r,this.isReplace=o,this.mapMode=r?t<=0?me.TrackBefore:me.TrackAfter:me.TrackDel}get type(){return this.startSide!=this.endSide?Pe.WidgetRange:this.startSide<=0?Pe.WidgetBefore:Pe.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Vt&&ud(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Vt.prototype.point=!0;function ac(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function ud(n,e){return n==e||!!(n&&e&&n.compare(e))}function oi(n,e,t,i=0){let r=t.length-1;r>=0&&t[r]+i>=n?t[r]=Math.max(t[r],e):t.push(n,e)}class Hi extends vt{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof Hi&&this.tagName==e.tagName&&Lo(this.attributes,e.attributes)}static create(e){return new Hi(e.tagName,e.attributes||sr,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return E.of(e,t)}}Hi.prototype.startSide=Hi.prototype.endSide=-1;function Ki(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Hs(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Wi(n,e){if(!e.anchorNode)return!1;try{return Hs(n,e.anchorNode)}catch{return!1}}function Gn(n){return n.nodeType==3?Ji(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Vi(n,e,t,i){return t?Wl(n,e,t,i,-1)||Wl(n,e,t,i,1):!1}function Zt(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function or(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function Wl(n,e,t,i,r){for(;;){if(n==t&&e==i)return!0;if(e==(r<0?0:bt(n))){if(n.nodeName=="DIV")return!1;let s=n.parentNode;if(!s||s.nodeType!=1)return!1;e=Zt(n)+(r<0?0:1),n=s}else if(n.nodeType==1){if(n=n.childNodes[e+(r<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=r<0?bt(n):0}else return!1}}function bt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function lr(n,e){let{left:t,right:i}=n;if(t==i)return n;let r=e?t:i;return{left:r,right:r,top:n.top,bottom:n.bottom}}function Od(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function hc(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function dd(n,e,t,i,r,s,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let c=n,f=!1;c&&!f;)if(c.nodeType==1){let u,O=c==a.body,d=1,p=1;if(O)u=Od(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(f=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let b=c.getBoundingClientRect();({scaleX:d,scaleY:p}=hc(c,b)),u={left:b.left,right:b.left+c.clientWidth*d,top:b.top,bottom:b.top+c.clientHeight*p}}let g=0,S=0;if(r=="nearest")e.top0&&e.bottom>u.bottom+S&&(S=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(S=e.bottom-u.bottom+o,t<0&&e.top-S0&&e.right>u.right+g&&(g=e.right-u.right+s)):e.right>u.right-s&&(g=e.right-u.right+s,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function cc(n,e=!0){let t=n.ownerDocument,i=null,r=null;for(let s=n.parentNode;s&&!(s==t.body||(!e||i)&&r);)if(s.nodeType==1)!r&&s.scrollHeight>s.clientHeight&&(r=s),e&&!i&&s.scrollWidth>s.clientWidth&&(i=s),s=s.assignedSlot||s.parentNode;else if(s.nodeType==11)s=s.host;else break;return{x:i,y:r}}class pd{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?bt(t):0),i,Math.min(e.focusOffset,i?bt(i):0))}set(e,t,i,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=r}}function fc(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function uc(n,e=!0){for(let{node:t,left:i,top:r}of n)e&&t.scrollTop!=r&&(t.scrollTop=r),t.scrollLeft!=i&&(t.scrollLeft=i)}let Lt=null;P.safari&&P.safari_version>=26&&(Lt=!1);function Oc(n){if(n.setActive)return n.setActive();if(Lt)return n.focus(Lt);let e=fc(n);n.focus(Lt==null?{get preventScroll(){return Lt={preventScroll:!0},!0}}:void 0),Lt||(Lt=!1,uc(e))}let Vl;function Ji(n,e,t=e){let i=Vl||(Vl=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function li(n,e,t,i){let r={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:r.altKey,ctrlKey:r.ctrlKey,shiftKey:r.shiftKey,metaKey:r.metaKey}=i);let s=new KeyboardEvent("keydown",r);s.synthetic=!0,n.dispatchEvent(s);let o=new KeyboardEvent("keyup",r);return o.synthetic=!0,n.dispatchEvent(o),s.defaultPrevented||o.defaultPrevented}function md(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function gd(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,bt(t));;)if(i){if(t.nodeType!=1)return!1;let r=t.childNodes[i-1];r.contentEditable=="false"?i--:(t=r,i=bt(t))}else{if(t==n)return!0;i=Zt(t),t=t.parentNode}}function dc(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function pc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=bt(t)}else if(t.parentNode&&!or(t))i=Zt(t),t=t.parentNode;else return null}}function mc(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(s<0||(r!=0?r<0?l.fromt:e[s].level>l.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}}function bc(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;p-=3)if(He[p+1]==-O){let g=He[p+2],S=g&2?r:g&4?g&1?s:r:0;S&&(G[f]=G[He[p]]=S),l=p;break}}else{if(He.length==189)break;He[l++]=f,He[l++]=u,He[l++]=a}else if((d=G[f])==2||d==1){let p=d==r;a=p?0:1;for(let g=l-3;g>=0;g-=3){let S=He[g+2];if(S&2)break;if(p)He[g+2]|=2;else{if(S&4)break;He[g+2]|=4}}}}}function kd(n,e,t,i){for(let r=0,s=i;r<=t.length;r++){let o=r?t[r-1].to:n,l=ra;)d==g&&(d=t[--p].from,g=p?t[p-1].to:n),G[--d]=O;a=c}else s=h,a++}}}function Js(n,e,t,i,r,s,o){let l=i%2?2:1;if(i%2==r%2)for(let a=e,h=0;aa&&o.push(new nt(a,p.from,O));let g=p.direction==Bt!=!(O%2);eo(n,g?i+1:i,r,p.inner,p.from,p.to,o),a=p.to}d=p.to}else{if(d==t||(c?G[d]!=l:G[d]==l))break;d++}u?Js(n,a,d,i+1,r,u,o):ae;){let c=!0,f=!1;if(!h||a>s[h-1].to){let p=G[a-1];p!=l&&(c=!1,f=p==16)}let u=!c&&l==1?[]:null,O=c?i:i+1,d=a;e:for(;;)if(h&&d==s[h-1].to){if(f)break e;let p=s[--h];if(!c)for(let g=p.from,S=h;;){if(g==e)break e;if(S&&s[S-1].to==g)g=s[--S].from;else{if(G[g-1]==l)break e;break}}if(u)u.push(p);else{p.toG.length;)G[G.length]=256;let i=[],r=e==Bt?0:1;return eo(n,r,r,t,0,n.length,i),i}function Qc(n){return[new nt(0,n,0)]}let yc="";function $d(n,e,t,i,r){var s;let o=i.head-n.from,l=nt.find(e,o,(s=i.bidiLevel)!==null&&s!==void 0?s:-1,i.assoc),a=e[l],h=a.side(r,t);if(o==h){let u=l+=r?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!r,t),h=a.side(r,t)}let c=fe(n.text,o,a.forward(r,t));(ca.to)&&(c=h),yc=n.text.slice(Math.min(o,c),Math.max(o,c));let f=l==(r?e.length-1:0)?null:e[l+(r?1:-1)];return f&&c==h&&f.level+(r?0:1)n.some(e=>e)}),vd=Z.define({combine:n=>n.some(e=>e)}),Cc=Z.define();class ai{constructor(e,t,i,r,s,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=r,this.xMargin=s,this.isSnapshot=o}map(e){return e.empty?this:new ai(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new ai(y.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Cn=V.define({map:(n,e)=>n.map(e)}),Zc=V.define();function Ae(n,e,t){let i=n.facet($c);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const dt=Z.define({combine:n=>n.length?n[0]:!0});let Td=0;const ei=Z.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(Rr.of(h=>{let c=h.plugin(l);return c?o(c):M.none})),s&&a.push(s(l)),a})}static fromClass(e,t){return Se.define((i,r)=>new e(i,r),t)}}class Kr{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(Ae(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){Ae(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){Ae(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const Xc=Z.define(),_o=Z.define(),Rr=Z.define(),Ac=Z.define(),Wo=Z.define(),dn=Z.define(),Rc=Z.define();function Bl(n,e){let t=n.state.facet(Rc);if(!t.length)return t;let i=t.map(s=>s instanceof Function?s(n):s),r=[];return E.spans(i,e.from,e.to,{point(){},span(s,o,l,a){let h=s-e.from,c=o-e.from,f=r;for(let u=l.length-1;u>=0;u--,a--){let O=l[u].spec.bidiIsolate,d;if(O==null&&(O=Pd(e.text,h,c)),a>0&&f.length&&(d=f[f.length-1]).to==h&&d.direction==O)d.to=c,f=d.inner;else{let p={from:h,to:c,direction:O,inner:[]};f.push(p),f=p.inner}}}}),r}const Mc=Z.define();function Vo(n){let e=0,t=0,i=0,r=0;for(let s of n.state.facet(Mc)){let o=s(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(r=Math.max(r,o.bottom)))}return{left:e,right:t,top:i,bottom:r}}const Li=Z.define();class je{constructor(e,t,i,r){this.fromA=e,this.toA=t,this.fromB=i,this.toB=r}join(e){return new je(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>i.toA)){if(r.toAr.push(new je(s,o,l,a))),this.changedRanges=r}static create(e,t,i){return new ar(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const Cd=[];class ee{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Cd}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&cd(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let r of this.children){if(r==e)return i;i+=r.length+r.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=Zt(this.dom),r=this.length?e>0:t>0;return new qe(this.parent.dom,i+(r?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof jr)return e;return null}static get(e){return e.cmTile}}class Mr extends ee{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,r,s=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,r=i?i.nextSibling:t.firstChild,s&&r!=l.dom&&(s.written=!0),l.dom.parentNode==t)for(;r&&r!=l.dom;)r=ql(r);else t.insertBefore(l.dom,r);i=l.dom}for(r=i?i.nextSibling:t.firstChild,s&&r&&(s.written=!0);r;)r=ql(r);this.length=o}}function ql(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class jr extends Mr{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=ee.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,r=0,s=0;;)if(r==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&s++,r=t.pop()}else{let o=i.children[r++];if(o instanceof mt)t.push(r),i=o,r=0;else{let l=s+o.length,a=e(o,s);if(a!==void 0)return a;s=l+o.breakAfter}}}resolveBlock(e,t){let i,r=-1,s,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!s||!l.isWidget()&&s.isWidget())&&(s=l,o=e-a)}}),!i&&!s)throw new Error("No tile at position "+e);return i&&t<0||!s?{tile:i,offset:r}:{tile:s,offset:o}}}class mt extends Mr{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new mt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class Oi extends Mr{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let r=new Oi(t||document.createElement("div"),e);return(!t||!i)&&(r.flags|=4),r}get domAttrs(){return this.attrs}resolveInline(e,t,i){let r=null,s=-1,o=null,l=-1;function a(c,f){for(let u=0,O=0;u=f&&(d.isComposite()?a(d,f-O):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Xd(o,d)))&&(p>f||d.flags&32&&t<=1)?(o=d,l=f-O):(O=-1)&&(r=d,s=f-O)),O=p}}a(this,e);let h=(t<0?r:o)||r||o;return h?{tile:h,offset:h==r?s:l}:null}coordsIn(e,t,i){let r=this.resolveInline(e,t,!0);return r?r.tile.coordsIn(Math.max(0,r.offset),t,i):Zd(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:r,offset:s}=i;if(this.dom.contains(r.dom))return r.isText()?new qe(r.dom,Math.min(r.dom.nodeValue.length,s)):r.domPosFor(s,r.flags&16?1:r.flags&32?-1:t);let o=i.tile.parent,l=!1;for(let a of o.children){if(l)return new qe(a.dom,0);a==i.tile&&(l=!0)}}return new qe(this.dom,0)}}function Zd(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=Gn(e);return t[t.length-1]||null}function Xd(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.topr&&(e=r);let s=e,o=e,l=0;e==0&&t<0||e==r&&t>=0?P.chrome||P.gecko||(e?(s--,l=1):o=0)?0:a.length-1];return P.safari&&!l&&h.width==0&&(h=Array.prototype.find.call(a,c=>c.width)||h),i==null?h:lr(h,(l?l>0:t<0)==i)}static of(e,t){let i=new zt(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class qt extends ee{constructor(e,t,i,r){super(e,t,r),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let r=this.widget.coordsAt(this.dom,e,t);if(r)return r;if(i)return lr(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let s=this.dom.getClientRects(),o=null;if(!s.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?s.length-1:0;o=s[a],!(e>0?a==0:a==s.length-1||o.top0==i)}}class Ad{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:r,index:s,beforeBreak:o,parents:l}=this;for(;e||t>0;)if(r.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(s==r.children.length){if(!e&&!l.length)break;i&&i.leave(r),o=!!r.breakAfter,{tile:r,index:s}=l.pop(),s++}else{let a=r.children[s],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=r.lastChild;if(h instanceof we&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM(Jr(a.dom)),r=h;else{if(this.cache.reused.get(a)){let f=ee.get(a.dom);f&&f.setDOM(Jr(a.dom))}let c=we.of(a.mark,a.dom);r.append(c),r=c}this.cache.reused.set(a,2)}let s=ee.get(e.text);s&&this.cache.reused.set(s,2);let o=new zt(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,r.append(o)}addInlineWidget(e,t,i){let r=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);r||this.flushBuffer();let s=this.ensureMarks(t,i);!r&&!(e.flags&16)&&s.append(this.getBuffer(1)),s.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=jc);let r=Oi.start(e,t||((i=this.cache.find(Oi))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=r)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let r=this.curLine;for(let s=e.length-1;s>=0;s--){let o=e[s],l;if(t>0&&(l=r.lastChild)&&l instanceof we&&l.mark.eq(o))r=l,t--;else{let a=we.of(o,(i=this.cache.find(we,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);r.append(a),r=a,t=0}}return r}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Dl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(P.ios&&Dl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(es,0,32)||new qt(es.toDOM(),0,es,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new Rd(e.from,e.to,e.value,t),r=this.wrappers.length;for(;r>0&&(this.wrappers[r-1].rank-i.rank||this.wrappers[r-1].to-i.to)<0;)r--;this.wrappers.splice(r,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let r=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(s),t=s}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(hr,void 0,1);return i&&(i.flags=t),i||new hr(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class jd{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:r,lineBreak:s,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=r;let l=this.textOff=Math.min(e,r.length);return s?null:r.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const cr=[qt,Oi,zt,we,hr,mt,jr];for(let n=0;n[]),this.index=cr.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let r=e.bucket,s=this.buckets[r],o=this.index[r];for(let l=0;l{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let r=0,s=0,o=0;;){let l=or){let h=a-r;this.preserve(h,!o,!l),r=a,s+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof we&&r.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?r.length&&(r.length=s=0):o instanceof we&&(r.shift(),s=Math.min(s,r.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,r=this.builder,s=-1,o=E.spans(this.decorations,e,t,{point:(l,a,h,c,f,u)=>{if(h instanceof Vt){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(s=c.length,f>c.length)r.continueWidget(a-l);else{let O=h.widget||(h.block?di.block:di.inline),d=Ed(h),p=this.cache.findWidget(O,a-l,d)||qt.of(O,this.view,a-l,d);h.block?(h.startSide>0&&r.addLineStartIfNotCovered(i),r.addBlockWidget(p)):(r.ensureLine(i),r.addInlineWidget(p,c,f))}i=null}else i=zd(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,c)=>{for(let f=l;f-1&&(this.openWidget=o>s),this.openWidget||r.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let r=e.parentNode;;r=r.parentNode){let s=ee.get(r);if(r==this.view.contentDOM)break;s instanceof we?t.push(s):s?.isLine()?i=s:s instanceof mt||(r.nodeName=="DIV"&&!i&&r!=this.view.contentDOM?i=new Oi(r,jc):i||t.push(we.of(new un({tagName:r.nodeName.toLowerCase(),attributes:fd(r)}),r)))}return{line:i,marks:t}}}function Dl(n,e){let t=i=>{for(let r of i.children)if((e?r.isText():r.length)||t(r))return!0;return!1};return t(n)}function Ed(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const jc={class:"cm-line"};function zd(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&jo(t,n),i&&(n.class+=" "+i)),n}function _d(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof we&&e.push(i.mark)}return e}function Jr(n){let e=ee.get(n);return e&&e.setDOM(n.cloneNode()),n}class di extends at{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}di.inline=new di("span");di.block=new di("div");const es=new class extends at{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Il{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=M.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new jr(e,e.contentDOM),this.updateInner([new je(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:c,toA:f})=>fthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let r=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?r=this.domChanged.newSel.head:!Ud(e.changes,this.hasComposition)&&!e.selectionSet&&(r=e.state.selection.main.head));let s=r>-1?Vd(this.view,e.changes,r):null;if(this.domChanged=null,this.hasComposition){let{from:c,to:f}=this.hasComposition;i=new je(c,f,e.changes.mapPos(c,-1),e.changes.mapPos(f,1)).addToSet(i.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(P.ie||P.chrome)&&!s&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=Dd(o,this.decorations,e.changes);a.length&&(i=je.extendWithRanges(i,a));let h=Nd(l,this.blockWrappers,e.changes);return h.length&&(i=je.extendWithRanges(i,h)),s&&!i.some(c=>c.fromA<=s.range.fromA&&c.toA>=s.range.toA)&&(i=s.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,s),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new Yd(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&ee.get(t.text)&&l.cache.reused.set(ee.get(t.text),2),this.tile=l.run(e,t),io(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let s=P.chrome||P.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(s),s&&(s.written||i.selectionRange.focusNode!=s.node||!this.tile.dom.contains(s.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let r=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Wi(i,this.view.observer.selectionRange)&&!(r&&i.contains(r));if(!(s||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,c;if(a.empty?c=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(c=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),P.gecko&&a.empty&&!this.hasComposition&&Wd(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=c=new qe(u,0),l=!0}let f=this.view.observer.selectionRange;(l||!f.focusNode||(!Vi(h.node,h.offset,f.anchorNode,f.anchorOffset)||!Vi(c.node,c.offset,f.focusNode,f.focusOffset))&&!this.suppressWidgetCursorChange(f,a))&&(this.view.observer.ignore(()=>{P.android&&P.chrome&&i.contains(f.focusNode)&&Gd(f.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=Ki(this.view.root);if(u)if(a.empty){if(P.gecko){let O=Bd(h.node,h.offset);if(O&&O!=3){let d=(O==1?pc:mc)(h.node,h.offset);d&&(h=new qe(d.node,d.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(c.node,c.offset)}catch{}}else{let O=document.createRange();a.anchor>a.head&&([h,c]=[c,h]),O.setEnd(c.node,c.offset),O.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(O)}o&&this.view.root.activeElement==i&&(i.blur(),r&&r.focus())}),this.view.observer.setSelectionRange(h,c)),this.impreciseAnchor=h.precise?null:new qe(f.anchorNode,f.anchorOffset),this.impreciseHead=c.precise?null:new qe(f.focusNode,f.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Vi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=Ki(e.root),{anchorNode:r,anchorOffset:s}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let f=e.observer.selectionRange;e.docView.posFromDOM(f.anchorNode,f.anchorOffset)!=t.from&&i.collapse(r,s)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let r=i.posAtStart;if(i.isComposite()){let s;if(e==i.dom)s=i.dom.childNodes[t];else{let o=bt(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?s=e:s=e.nextSibling}if(s==i.dom.firstChild)return r;for(;s&&!ee.get(s);)s=s.nextSibling;if(!s)return r+i.length;for(let o=0,l=r;;o++){let a=i.children[o];if(a.dom==s)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?r+t:r+(t?i.length:0):r}domAtPos(e,t){let{tile:i,offset:r}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(r,t):i.domIn(r,t)}inlineDOMNearPos(e,t){let i,r=-1,s=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,c)=>{if(h.isWidget()){if(h.flags&32&&c>=e)return!0;h.flags&16&&(s=!0)}else{let f=c+h.length;if(c<=e&&(i=h,r=e-c,s=f=e&&!o&&(o=h,l=e-c,a=c>e),c>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(s&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(r,t):o.domIn(l,t))}coordsAt(e,t,i){let{tile:r,offset:s}=this.tile.resolveBlock(e,t);return r.isWidget()?r.widget instanceof ts?null:r.coordsInWidget(s,t,!0):r.coordsIn(s,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function r(s,o){if(s.isComposite())for(let l of s.children){if(l.length>=o){let a=r(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(s.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==K.LTR,h=0,c=(f,u,O)=>{for(let d=0;dr);d++){let p=f.children[d],g=u+p.length,S=p.dom.getBoundingClientRect(),{height:b}=S;if(O&&!d&&(h+=S.top-O.top),p instanceof mt)g>i&&c(p,u,S);else if(u>=i&&(h>0&&t.push(-h),t.push(b+h),h=0,o)){let Q=p.dom.lastChild,w=Q?Gn(Q):[];if(w.length){let k=w[w.length-1],v=a?k.right-S.left:S.right-k.left;v>l&&(l=v,this.minWidth=s,this.minWidthFrom=u,this.minWidthTo=g)}}O&&d==f.children.length-1&&(h+=O.bottom-S.bottom),u=g+p.breakAfter}};return c(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?K.RTL:K.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let c=Gn(h.dom);if(c.length!=1)return;l+=c[0].width,a=c[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,r,s;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Gn(t.firstChild)[0];i=t.getBoundingClientRect().height,r=o&&o.width?o.width/27:7,s=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:r,textHeight:s}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,r=0;;r++){let s=r==t.viewports.length?null:t.viewports[r],o=s?s.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(M.replace({widget:new ts(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!s)break;i=s.to+1}return M.set(e)}updateDeco(){let e=1,t=this.view.state.facet(Rr).map(s=>(this.dynamicDecorationMap[e++]=typeof s=="function")?s(this.view):s),i=!1,r=this.view.state.facet(Wo).map((s,o)=>{let l=typeof s=="function";return l&&(i=!0),l?s(this.view):s});for(r.length&&(this.dynamicDecorationMap[e++]=i,t.push(E.join(r))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof s=="function"?s(this.view):s)}scrollIntoView(e){if(e.isSnapshot){let h=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=h.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let h of this.view.state.facet(Cc))try{if(h(this.view,e.range,e))return!0}catch(c){Ae(this.view.state,c,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),r;if(!i)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)});let s=Vo(this.view),o={left:i.left-s.left,top:i.top-s.top,right:i.right+s.right,bottom:i.bottom+s.bottom},{offsetWidth:l,offsetHeight:a}=this.view.scrollDOM;if(dd(this.view.scrollDOM,o,t.head1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){io(this.tile)}}function io(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)io(i,e)}}function Wd(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function Lc(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=pc(t.focusNode,t.focusOffset),r=mc(t.focusNode,t.focusOffset),s=i||r;if(r&&i&&r.node!=i.node){let l=ee.get(r.node);if(!l||l.isText()&&l.text!=r.node.nodeValue)s=r;else if(n.docView.lastCompositionAfterCursor){let a=ee.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(s=r)}}if(n.docView.lastCompositionAfterCursor=s!=i,!s)return null;let o=e-s.offset;return{from:o,to:o+s.node.nodeValue.length,node:s.node}}function Vd(n,e,t){let i=Lc(n,t);if(!i)return null;let{node:r,from:s,to:o}=i,l=r.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new je(a.mapPos(s),a.mapPos(o),s,o),text:r}}function Bd(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}class ts extends at{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function Fd(n,e,t=1){let i=n.charCategorizer(e),r=n.doc.lineAt(e),s=e-r.from;if(r.length==0)return y.cursor(e);s==0?t=1:s==r.length&&(t=-1);let o=s,l=s;t<0?o=fe(r.text,s,!1):l=fe(r.text,s);let a=i(r.text.slice(o,l));for(;o>0;){let h=fe(r.text,o,!1);if(i(r.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((r-t.top-(n.defaultLineHeight-l)*.5)/l);s+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+sd(o,s,n.state.tabSize)}function Kd(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let r;for(let s of i.type){if(s.from>e)break;if(!(s.toe)return s;(!r||s.type==Pe.Text&&(r.type!=s.type||(t<0?s.frome)))&&(r=s)}}return r||i}return i}function Jd(n,e,t,i){let r=Kd(n,e.head,e.assoc||-1),s=!i||r.type!=Pe.Text||!(n.lineWrapping||r.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>r.from?e.head-1:e.head);if(s){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(r.from),a=n.posAtCoords({x:t==(l==K.LTR)?o.right-1:o.left+1,y:(s.top+s.bottom)/2});if(a!=null)return y.cursor(a,t?-1:1)}return y.cursor(t?r.to:r.from,t?-1:1)}function Nl(n,e,t,i){let r=n.state.doc.lineAt(e.head),s=n.bidiSpans(r),o=n.textDirectionAt(r.from);for(let l=e,a=null;;){let h=$d(r,s,o,l,t),c=yc;if(!h){if(r.number==(t?n.state.doc.lines:1))return l;c=` -`,r=n.state.doc.line(r.number+(t?1:-1)),s=n.bidiSpans(r),h=n.visualLineSide(r,!t)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function ep(n,e,t){let i=n.state.charCategorizer(e),r=i(t);return s=>{let o=i(s);return r==pt.Space&&(r=o),r==o}}function tp(n,e,t,i){let r=e.head,s=t?1:-1;if(r==(t?n.state.doc.length:0))return y.cursor(r,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(r,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),c=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=s<0?h.top:h.bottom;else{let d=n.viewState.lineBlockAt(r);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(r-d.from))),l=(s<0?d.top:d.bottom)+c}let f=a.left+o,u=n.viewState.heightOracle.textHeight>>1,O=i??u;for(let d=0;;d+=u){let p=l+(O+d)*s,g=no(n,{x:f,y:p},!1,s);if(t?p>a.bottom:pl:b{if(e>s&&er(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:y.cursor(i,in.viewState.docHeight)return new it(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==Pe.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+s:u.bottom>=a+s))break}let f=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+f:h.top-f}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==Pe.Text){let f=Hd(n,r,h,o,l);return new it(f,f==h.from?1:-1)}}if(h.type!=Pe.Text)return a<(h.top+h.bottom)/2?new it(h.from,1):new it(h.to,-1);let c=n.docView.lineAt(h.from,2);return(!c||c.length!=h.length)&&(c=n.docView.lineAt(h.from,-2)),new ip(n,o,l,n.textDirectionAt(h.from)).scanTile(c,h.from)}class ip{constructor(e,t,i,r){this.view=e,this.x=t,this.y=i,this.baseDir=r,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+r.from>1;t:if(o.has(p)){for(let b=1;b=s&&(Q-=d),!o.has(Q)){p=Q;break t}}break e}o.add(p);let g=t(p),S=0;if(g)for(let b=0;b1))if(Q.bottomthis.y)(!h||h.top>Q.top)&&(h=Q),S=-1;else{let w=Q.left>this.x?this.x-Q.left:Q.right(d+d+p)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(d+p+p)/3)return this.y=h.top+1,this.scan(e,t,!0)}let O=(l?this.dirAt(e[c],1):this.baseDir)==K.LTR;return{i:c,after:this.x>(u.left+u.right)/2==O}}scanText(e,t){let i=[];for(let s=0;s{let o=i[s]-t,l=i[s+1]-t;return Ji(e.dom,o,l).getClientRects()});return r.after?new it(i[r.i+1],-1):new it(i[r.i],1)}scanTile(e,t){if(!e.length)return new it(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:Ji(a.dom,0,a.length)).getClientRects()}),s=e.children[r.i],o=i[r.i];return s.isText()?this.scanText(s,o):s.isComposite()?this.scanTile(s,o):r.after?new it(i[r.i+1],-1):new it(o,1)}}const Kt="￿";class np{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(W.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Kt}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let r=e;;){this.findPointBefore(i,r);let s=this.text.length;this.readNode(r);let o=ee.get(r),l=r.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=ee.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:or(r))||or(l)&&(r.nodeName!="BR"||o?.isWidget())&&this.text.length>s)&&!sp(l,t)&&this.lineBreak(),r=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,l;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=r.exec(t))&&(s=l.index,o=l[0].length),this.append(t.slice(i,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=s+o}}readNode(e){let t=ee.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let r=i.iter();!r.next().done;)r.lineBreak?this.lineBreak():this.append(r.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(rp(e,i.node,i.offset)?t:0))}}function rp(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:s,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ec(e.docView.tile,t,i,0))){let a=s||o?[]:ap(e),h=new np(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=hp(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=s&&s.node==a.focusNode&&s.offset==a.focusOffset||!Hs(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),c=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!Hs(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),f=e.viewport;if((P.ios||P.chrome)&&h!=c&&Math.min(h,c)<=l.main.from&&Math.max(h,c)>=l.main.to&&(f.from>0||f.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(y.range(c,h));else if(e.lineWrapping&&c==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),O=0;u&&(O=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=y.create([y.cursor(h,O)])}else this.newSel=y.single(c,h)}}}function Ec(n,e,t,i){if(n.isComposite()){let r=-1,s=-1,o=-1,l=-1;for(let a=0,h=i,c=i;at)return Ec(f,e,t,h);if(u>=e&&r==-1&&(r=a,s=h),h>t&&f.dom.parentNode==n.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:s,to:l<0?i+n.length:l,startDOM:(r?n.children[r-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function zc(n,e){let t,{newSel:i}=e,{state:r}=n,s=r.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=s.from,c=null;(o===8||P.android&&e.text.length=l&&s.to<=a&&(e.typeOver||f!=e.text)&&f.slice(0,s.from-l)==e.text.slice(0,s.from-l)&&f.slice(s.to-l)==e.text.slice(u=e.text.length-(f.length-(s.to-l)))?t={from:s.from,to:s.to,insert:_.of(e.text.slice(s.from-l,u).split(Kt))}:(O=_c(f,e.text,h-l,c))&&(P.chrome&&o==13&&O.toB==O.from+2&&e.text.slice(O.from,O.toB)==Kt+Kt&&O.toB--,t={from:l+O.from,to:l+O.toA,insert:_.of(e.text.slice(O.from,O.toB).split(Kt))})}else i&&(!n.hasFocus&&r.facet(dt)||fr(i,s))&&(i=null);if(!t&&!i)return!1;if((P.mac||P.android)&&t&&t.from==t.to&&t.from==s.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=y.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:_.of([t.insert.toString().replace("."," ")])}):r.doc.lineAt(s.from).toDate.now()-50?t={from:s.from,to:s.to,insert:r.toText(n.inputState.insertingText)}:P.chrome&&t&&t.from==t.to&&t.from==s.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=y.single(i.main.anchor-1,i.main.head-1)),t={from:s.from,to:s.to,insert:_.of([" "])}),t)return Bo(n,t,i,o);if(i&&!fr(i,s)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Yc(r.facet(dn).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function Bo(n,e,t,i=-1){if(P.ios&&n.inputState.flushIOSKey(e))return!0;let r=n.state.selection.main;if(P.android&&(e.to==r.to&&(e.from==r.from||e.from==r.from-1&&n.state.sliceDoc(e.from,r.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&li(n.contentDOM,"Enter",13)||(e.from==r.from-1&&e.to==r.to&&e.insert.length==0||i==8&&e.insert.lengthr.head)&&li(n.contentDOM,"Backspace",8)||e.from==r.from&&e.to==r.to+1&&e.insert.length==0&&li(n.contentDOM,"Delete",46)))return!0;let s=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=lp(n,e,t));return n.state.facet(Pc).some(a=>a(n,e.from,e.to,s,l))||n.dispatch(l()),!0}function lp(n,e,t){let i,r=n.state,s=r.selection.main,o=-1;if(e.from==e.to&&e.froms.to){let a=e.fromf(n)),h,a);e.from==c&&(o=c)}if(o>-1)i={changes:e,selection:y.cursor(e.from+e.insert.length,-1)};else if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=s.frome.to?r.sliceDoc(e.to,s.to):"";i=r.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=r.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=s.to+10&&e.to>=s.to-10){let c=n.state.sliceDoc(e.from,e.to),f,u=t&&Lc(n,t.main.head);if(u){let d=e.insert.length-(e.to-e.from);f={from:u.from,to:u.to-d}}else f=n.state.doc.lineAt(s.head);let O=s.to-e.to;i=r.changeByRange(d=>{if(d.from==s.from&&d.to==s.to)return{changes:a,range:h||d.map(a)};let p=d.to-O,g=p-c.length;if(n.state.sliceDoc(g,p)!=c||p>=f.from&&g<=f.to)return{range:d};let S=r.changes({from:g,to:p,insert:e.insert}),b=d.to-s.to;return{changes:S,range:h?y.range(Math.max(0,h.anchor+b),Math.max(0,h.head+b)):d.map(S)}})}else i={changes:a,selection:h&&r.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:l,scrollIntoView:!0})}function _c(n,e,t,i){let r=Math.min(n.length,e.length),s=0;for(;s0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,s-Math.min(o,l));t-=o+a-s}if(o=o?s-t:0;s-=a,l=s+(l-o),o=s}else if(l=l?s-t:0;s-=a,o=s+(o-l),l=s}return{from:s,toA:o,toB:l}}function ap(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}=n.observer.selectionRange;return t&&(e.push(new Gl(t,i)),(r!=t||s!=i)&&e.push(new Gl(r,s))),e}function hp(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?y.single(t+e,i+e):null}function fr(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class cp{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,P.safari&&e.contentDOM.addEventListener("input",()=>null),P.gecko&&Pp(e.contentDOM.ownerDocument)}handleEvent(e){!bp(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=up(e),i=this.handlers,r=this.view.contentDOM;for(let s in t)if(s!="scroll"){let o=!t[s].handlers.length,l=i[s];l&&o!=!l.handlers.length&&(r.removeEventListener(s,this.handleEvent),l=null),l||r.addEventListener(s,this.handleEvent,{passive:o})}for(let s in i)s!="scroll"&&!t[s]&&r.removeEventListener(s,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Vc.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),P.android&&P.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(P.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(Wc.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||Op.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&P.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&fp(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),50),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||this.view.observer.pendingRecords().length||t.key=="Enter"&&e&&e.from0?!0:P.safari&&!P.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function fp(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Ul(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(r){Ae(t.state,r)}}}function up(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let r=i.spec,s=r&&r.plugin.domEventHandlers,o=r&&r.plugin.domEventObservers;if(s)for(let l in s){let a=s[l];a&&t(l).handlers.push(Ul(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(Ul(i.value,a))}}for(let i in De)t(i).handlers.push(De[i]);for(let i in be)t(i).observers.push(be[i]);return e}const Wc=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Op="dthko",Vc=[16,17,18,20,91,92,224,225],Zn=6;function Xn(n){return Math.max(0,n)*.7+8}function dp(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class pp{constructor(e,t,i,r){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=cc(e.contentDOM),this.atoms=e.state.facet(dn).map(o=>o(e));let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(W.allowMultipleSelections)&&mp(e,t),this.dragging=Sp(e,t)&&Dc(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&dp(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,r=0,s=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:r,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:s,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=Vo(this.view);e.clientX-a.left<=r+Zn?t=-Xn(r-e.clientX):e.clientX+a.right>=o-Zn&&(t=Xn(e.clientX-o)),e.clientY-a.top<=s+Zn?i=-Xn(s-e.clientY):e.clientY+a.bottom>=l-Zn&&(i=Xn(e.clientY-l)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=Yc(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function mp(n,e){let t=n.state.facet(xc);return t.length?t[0](e):P.mac?e.metaKey:e.ctrlKey}function gp(n,e){let t=n.state.facet(kc);return t.length?t[0](e):P.mac?!e.altKey:!e.ctrlKey}function Sp(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=Ki(n.root);if(!i||i.rangeCount==0)return!0;let r=i.getRangeAt(0).getClientRects();for(let s=0;s=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function bp(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=ee.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const De=Object.create(null),be=Object.create(null),Bc=P.ie&&P.ie_version<15||P.ios&&P.webkit_version<604;function Qp(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),qc(n,t.value)},50)}function Lr(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function qc(n,e){e=Lr(n.state,Eo,e);let{state:t}=n,i,r=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(ro!=null&&t.selection.ranges.every(a=>a.empty)&&ro==s.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?s.line(r++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:y.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=s.line(r++);return{changes:{from:a.from,to:a.to,insert:h.text},range:y.cursor(a.from+h.length)}}):i=t.replaceSelection(s);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}be.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,P.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};be.wheel=be.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};De.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);be.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};be.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};be.touchend=(n,e)=>{n.inputState.touchActive=!1};De.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(wc))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=xp(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new pp(n,e,t,i)),i&&n.observer.ignore(()=>{Oc(n.contentDOM);let s=n.root.activeElement;s&&!s.contains(n.contentDOM)&&s.blur()});let r=n.inputState.mouseSelection;if(r)return r.start(e),r.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Fl(n,e,t,i){if(i==1)return y.cursor(e,t);if(i==2)return Fd(n.state,e,t);{let r=n.docView.lineAt(e,t),s=n.state.doc.lineAt(r?r.posAtEnd:e),o=r?r.posAtStart:s.from,l=r?r.posAtEnd:s.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Kl+1)%3:1}function xp(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Dc(e),r=n.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),r=r.map(s.changes))},get(s,o,l){let a=n.posAndSideAtCoords({x:s.clientX,y:s.clientY},!1),h,c=Fl(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let f=Fl(n,t.pos,t.assoc,i),u=Math.min(f.from,c.from),O=Math.max(f.to,c.to);c=u1&&(h=kp(r,a.pos))?h:l?r.addRange(c):y.create([c])}}}function kp(n,e){for(let t=0;t=e)return y.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}De.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let r=n.docView.tile.nearest(e.target);if(r&&r.isWidget()){let s=r.posAtStart,o=s+r.length;(s>=t.to||o<=t.from)&&(t=y.undirectionalRange(s,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Lr(n.state,zo,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};De.dragend=n=>(n.inputState.draggedContent=null,!1);function ea(n,e,t,i){if(t=Lr(n.state,Eo,t),!t)return;let r=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:s}=n.inputState,o=i&&s&&gp(n,e)?{from:s.from,to:s.to}:null,l={from:r,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(r,-1),head:a.mapPos(r,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}De.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),r=0,s=()=>{++r==t.length&&ea(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),s()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return ea(n,e,i,!0),!0}return!1};De.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=Bc?null:e.clipboardData;return t?(qc(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Qp(n),!1)};function wp(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function $p(n){let e=[],t=[],i=!1;for(let r of n.selection.ranges)r.empty||(e.push(n.sliceDoc(r.from,r.to)),t.push(r));if(!e.length){let r=-1;for(let{from:s}of n.selection.ranges){let o=n.doc.lineAt(s);o.number>r&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),r=o.number}i=!0}return{text:Lr(n,zo,e.join(n.lineBreak)),ranges:t,linewise:i}}let ro=null;De.copy=De.cut=(n,e)=>{if(!Wi(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:r}=$p(n.state);if(!t&&!r)return!1;ro=r?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let s=Bc?null:e.clipboardData;return s?(s.clearData(),s.setData("text/plain",t),!0):(wp(n,t),!1)};const Ic=Ie.define();function Nc(n,e){let t=[];for(let i of n.facet(vc)){let r=i(n,e);r&&t.push(r)}return t.length?n.update({effects:t,annotations:Ic.of(!0)}):null}function Gc(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Nc(n.state,e);t?n.dispatch(t):n.update([])}},10)}be.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Gc(n)};be.blur=n=>{n.observer.clearSelectionRange(),Gc(n)};be.compositionstart=be.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};be.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,P.chrome&&P.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};be.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};De.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let s=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(s&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return Bo(n,{from:a,to:h,insert:n.state.toText(s)},null),!0}}let r;if(P.chrome&&P.android&&(r=Wc.find(s=>s.inputType==e.inputType))&&(n.observer.delayAndroidKey(r.key,r.keyCode),r.key=="Backspace"||r.key=="Delete")){let s=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>s+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return P.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),P.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>be.compositionend(n,e),20),!1};const ta=new Set;function Pp(n){ta.has(n)||(ta.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const ia=["pre-wrap","normal","pre-line","break-spaces"];let pi=!1;function na(){pi=!1}class vp{constructor(e){this.lineWrapping=e,this.doc=_.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return ia.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=r,this.lineLength=s,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Un&&(pi=!0),this.height=e)}replace(e,t,i){return ge.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,r){let s=this,o=i.doc;for(let l=r.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:c,toB:f}=r[l],u=s.lineAt(a,F.ByPosNoHeight,i.setDoc(t),0,0),O=u.to>=h?u:s.lineAt(h,F.ByPosNoHeight,i,0,0);for(f+=O.to-h,h=O.to;l>0&&u.from<=r[l-1].toA;)a=r[l-1].fromA,c=r[l-1].fromB,l--,as*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,r-=l.size}else if(s>r*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,s-=l.size}else break;else if(r=s&&o(this.lineAt(0,F.ByPos,i,r,s))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more&&this.setMeasuredHeight(r),this.outdated=!1,this}toString(){return`block(${this.length})`}}class Ce extends Uc{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new Be(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let r=i[0];return i.length==1&&(r instanceof Ce||r instanceof ae&&r.flags&4)&&Math.abs(this.length-r.length)<10?(r instanceof ae?r=new Ce(r.length,this.height,this.spaceAbove):r.height=this.height,this.outdated||(r.outdated=!1),r):ge.of(i)}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more?this.setMeasuredHeight(r):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class ae extends ge{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,s=r-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*s);o=a/s,this.length>s+1&&(l=(this.height-a)/(this.length-s-1))}else o=this.height/s;return{firstLine:i,lastLine:r,perLine:o,perChar:l}}blockAt(e,t,i,r){let{firstLine:s,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,r);if(t.lineWrapping){let h=r+(e0){let s=i[i.length-1];s instanceof ae?i[i.length-1]=new ae(s.length+r):i.push(null,new ae(r-1))}if(e>0){let s=i[0];s instanceof ae?i[0]=new ae(e+s.length):i.unshift(new ae(e-1),null)}return ge.of(i)}decomposeLeft(e,t){t.push(new ae(e-1),null)}decomposeRight(e,t){t.push(null,new ae(this.length-e-1))}updateHeight(e,t=0,i=!1,r){let s=t+this.length;if(r&&r.from<=t+this.length&&r.more){let o=[],l=Math.max(t,r.from),a=-1;for(r.from>t&&o.push(new ae(r.from-t-1).updateHeight(e,t));l<=s&&r.more;){let c=e.doc.lineAt(l).length;o.length&&o.push(null);let f=r.heights[r.index++],u=0;f<0&&(u=-f,f=r.heights[r.index++]),a==-1?a=f:Math.abs(f-a)>=Un&&(a=-2);let O=new Ce(c,f,u);O.outdated=!1,o.push(O),l+=c+1}l<=s&&o.push(null,new ae(s-l).updateHeight(e,l));let h=ge.of(o);return(a<0||Math.abs(h.height-this.height)>=Un||Math.abs(a-this.heightMetrics(e,t).perLine)>=Un)&&(pi=!0),ur(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Zp extends ge{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,r){let s=i+this.left.height;return el))return h;let c=t==F.ByPosNoHeight?F.ByPosNoHeight:F.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,r,s).join(h)}forEachLine(e,t,i,r,s,o){let l=r+this.left.height,a=s+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,F.ByPos,i,r,s);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let r=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,i));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let l of i)s.push(l);if(e>0&&ra(s,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,r=i+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e2*t.size||t.size>2*e.size?ge.of(this.break?[e,null,t]:[e,t]):(this.left=ur(this.left,e),this.right=ur(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,r){let{left:s,right:o}=this,l=t+s.length+this.break,a=null;return r&&r.from<=t+s.length&&r.more?a=s=s.updateHeight(e,t,i,r):s.updateHeight(e,t,i),r&&r.from<=l+o.length&&r.more?a=o=o.updateHeight(e,l,i,r):o.updateHeight(e,l,i),a?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function ra(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof ae&&(i=n[e+1])instanceof ae&&n.splice(e-1,3,new ae(t.length+1+i.length))}const Xp=5;class qo{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),r=this.nodes[this.nodes.length-1];r instanceof Ce?r.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new Ce(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=Xp)&&this.addLineDeco(r,s,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new Ce(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new ae(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Ce)return e;let t=new Ce(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let r=this.ensureLine();r.length+=i,r.collapsed+=i,r.widgetHeight=Math.max(r.widgetHeight,e),r.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof Ce)&&!this.isCovered?this.nodes.push(new Ce(0,-1,0)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();s=Math.max(s,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?r.innerHeight:a,u.bottom)}h=f.position=="absolute"||f.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function jp(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function Lp(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class ns{constructor(e,t,i,r){this.from=e,this.to=t,this.size=i,this.displaySize=r}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof r!="function"&&r.class=="cm-lineWrapping");this.heightOracle=new vp(i),this.stateDeco=la(t),this.heightMap=ge.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle.setDoc(t.doc),[new je(0,0,0,t.doc.length)]);for(let r=0;r<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());r++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=M.set(this.lineGaps.map(r=>r.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let r=i?t.head:t.anchor;if(!e.some(({from:s,to:o})=>r>=s&&r<=o)){let{from:s,to:o}=this.lineBlockAt(r);e.push(new An(s,o))}}return this.viewports=e.sort((i,r)=>i.from-r.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?oa:new Do(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Yi(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=la(this.state);let r=e.changedRanges,s=je.extendWithRanges(r,Ap(i,this.stateDeco,e?e.changes:re.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);na(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),(this.heightMap.height!=o||pi)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(vd)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),r=this.heightOracle,s=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?K.RTL:K.LTR;let o=this.heightOracle.mustRefreshForWrapping(s)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,c=0;if(l.width&&l.height){let{scaleX:k,scaleY:v}=hc(t,l);(k>.005&&Math.abs(this.scaleX-k)>.005||v>.005&&Math.abs(this.scaleY-v)>.005)&&(this.scaleX=k,this.scaleY=v,h|=16,o=a=!0)}let f=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let O=cc(this.view.contentDOM,!1).y;O!=this.scrollParent&&(this.scrollParent=O,this.scrollAnchorHeight=-1,this.scrollOffset=0);let d=this.getScrollOffset();this.scrollOffset!=d&&(this.scrollAnchorHeight=-1,this.scrollOffset=d),this.scrolledToBottom=dc(this.scrollParent||e.win);let p=(this.printing?Lp:Mp)(t,this.paddingTop),g=p.top-this.pixelViewport.top,S=p.bottom-this.pixelViewport.bottom;this.pixelViewport=p;let b=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(b!=this.inView&&(this.inView=b,b&&(a=!0)),!this.inView&&!this.scrollTarget&&!jp(e.dom))return 0;let Q=l.width;if((this.contentDOMWidth!=Q||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let k=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(k)&&(o=!0),o||r.lineWrapping&&Math.abs(Q-this.contentDOMWidth)>r.charWidth){let{lineHeight:v,charWidth:T,textHeight:L}=e.docView.measureTextSize();o=v>0&&r.refresh(s,v,T,L,Math.max(5,Q/T),k),o&&(e.docView.minWidth=0,h|=16)}g>0&&S>0?c=Math.max(g,S):g<0&&S<0&&(c=Math.min(g,S)),na();for(let v of this.viewports){let T=v.from==this.viewport.from?k:e.docView.measureVisibleLineHeights(v);this.heightMap=(o?ge.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle,[new je(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,o,new Tp(v.from,T))}pi&&(h|=2)}let w=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return w&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||w)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new An(r.lineAt(o-i*1e3,F.ByHeight,s,0,0).from,r.lineAt(l+(1-i)*1e3,F.ByHeight,s,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=r.lineAt(h,F.ByPos,s,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&r>o-2*1e3&&s>1,o=r<<1;if(this.defaultTextDirection!=K.LTR&&!i)return[];let l=[],a=(c,f,u,O)=>{if(f-cc&&SS.from>=u.from&&S.to<=u.to&&Math.abs(S.from-c)S.fromb));if(!g){if(fQ.from<=f&&Q.to>=f)){let Q=t.moveToLineBoundary(y.cursor(f),!1,!0).head;Q>c&&(f=Q)}let S=this.gapSize(u,c,f,O),b=i||S<2e6?S:2e6;g=new ns(c,f,S,b)}l.push(g)},h=c=>{if(c.length2e6)for(let v of e)v.from>=c.from&&v.fromc.from&&a(c.from,O,c,f),dt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];E.spans(t,this.viewport.from,this.viewport.to,{span(s,o){i.push({from:s,to:o})},point(){}},20);let r=0;if(i.length!=this.visibleRanges.length)r=12;else for(let s=0;s=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Yi(this.heightMap.lineAt(e,F.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Yi(this.heightMap.lineAt(this.scaler.fromDOM(e),F.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop*this.scaleY:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Yi(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class An{constructor(e,t){this.from=e,this.to=t}}function Ep(n,e,t){let i=[],r=n,s=0;return E.spans(t,n,e,{span(){},point(o,l){o>r&&(i.push({from:r,to:o}),s+=o-r),r=l}},20),r=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let r=0;;r++){let{from:s,to:o}=e[r],l=o-s;if(i<=l)return s+i;i-=l}}function Mn(n,e){let t=0;for(let{from:i,to:r}of n.ranges){if(e<=r){t+=e-i;break}t+=r-i}return t/n.total}function zp(n,e){for(let t of n)if(e(t))return t}const oa={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function la(n){let e=n.facet(Rr).filter(i=>typeof i!="function"),t=n.facet(Wo).filter(i=>typeof i!="function");return t.length&&e.push(E.join(t)),e}class Do{constructor(e,t,i){let r=0,s=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,F.ByPos,e,0,0).top,c=t.lineAt(a,F.ByPos,e,0,0).bottom;return r+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let l of this.viewports)l.domTop=o+(l.top-s)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),s=l.bottom}toDOM(e){for(let t=0,i=0,r=0;;t++){let s=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function Yi(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new Be(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(r=>Yi(r,e)):n._content)}const jn=Z.define({combine:n=>n.join(" ")}),so=Z.define({combine:n=>n.indexOf(!0)>-1}),oo=Tt.newName(),Fc=Tt.newName(),Hc=Tt.newName(),Kc={"&light":"."+Fc,"&dark":"."+Hc};function lo(n,e,t){return new Tt(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,r=>{if(r=="&")return n;if(!t||!t[r])throw new RangeError(`Unsupported selector: ${r}`);return t[r]}):n+" "+i}})}const _p=lo("."+oo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{background:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 0) no-repeat",backgroundSize:".4em",backgroundPosition:"calc(min(50%, 0px)) center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Kc),Wp={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},rs=P.ie&&P.ie_version<=11;class Vp{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new pd,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(P.ie&&P.ie_version<=11||P.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&P.android&&e.constructor.EDIT_CONTEXT!==!1&&!(P.chrome&&P.chrome_version<126)&&(this.editContext=new qp(e),e.state.facet(dt)&&(e.contentDOM.editContext=this.editContext.editContext)),rs&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,r=this.selectionRange;if(i.state.facet(dt)?i.root.activeElement!=this.dom:!Wi(this.dom,r))return;let s=r.anchorNode&&i.docView.tile.nearest(r.anchorNode);if(s&&s.isWidget()&&s.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(P.ie&&P.ie_version<=11||P.android&&P.chrome)&&!i.state.selection.main.empty&&r.focusNode&&Vi(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Ki(e.root);if(!t)return!1;let i=P.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&Bp(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let r=Wi(this.dom,i);return r&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=s.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&s.force&&li(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(r)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,r=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(r=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:r}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),r=this.selectionChanged&&Wi(this.dom,this.selectionRange);if(e<0&&!r)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new op(this.view,e,t,i);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,r=zc(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!fr(this.view.state.selection,t.newSel.main))&&this.view.update([]),r}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=aa(t,e.previousSibling||e.target.previousSibling,-1),r=aa(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(dt)!=e.state.facet(dt)&&(e.view.contentDOM.editContext=e.state.facet(dt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let r of this.scrollTargets)r.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function aa(n,e,t){for(;e;){let i=ee.get(e);if(i&&i.parent==n)return i;let r=e.parentNode;e=r!=n.dom?r:t>0?e.nextSibling:e.previousSibling}return null}function ha(n,e){let t=e.startContainer,i=e.startOffset,r=e.endContainer,s=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Vi(o.node,o.offset,r,s)&&([t,i,r,s]=[r,s,t,i]),{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}}function Bp(n,e){if(e.getComposedRanges){let r=e.getComposedRanges(n.root)[0];if(r)return ha(n,r)}let t=null;function i(r){r.preventDefault(),r.stopImmediatePropagation(),t=r.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?ha(n,t):null}class qp{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let r=e.state.selection.main,{anchor:s,head:o}=r,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&sthis.to&&(a=s);let c=_c(e.state.sliceDoc(l,a),i.text,(h?r.from:r.to)-l,h?"end":null);if(!c){let u=y.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));fr(u,r)||e.dispatch({selection:u,userEvent:"select"});return}let f={from:c.from+l,to:c.toA+l,insert:_.of(i.text.slice(c.from,c.toB).split(` -`))};if((P.mac||P.android)&&f.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(f={from:l,to:a,insert:_.of([i.text.replace("."," ")])}),this.pendingContextChange=f,!e.state.readOnly){let u=this.to-this.from+(f.to-f.from+f.insert.length);Bo(e,f,y.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),f.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let r=[],s=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let r=[];for(let s of i.getTextFormats()){let o=s.underlineStyle,l=s.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(s.rangeStart),h=this.toEditorPos(s.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let r=Ki(i.root);r&&r.rangeCount&&this.editContext.updateSelectionBounds(r.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,r=this.pendingContextChange;return e.changes.iterChanges((s,o,l,a,h)=>{if(i)return;let c=h.length-(o-s);if(r&&o>=r.to)if(r.from==s&&r.to==o&&r.insert.eq(h)){r=this.pendingContextChange=null,t+=c,this.to+=c;return}else r=null,this.revertPending(e.state);if(s+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(sthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(s),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),r&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(r=>!r.isUserEvent("input.type")&&r.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),r=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=r)&&this.editContext.updateSelection(i,r)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class C{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(r=>r.forEach(s=>i(s,this)))||(r=>this.update(r)),this.dispatch=this.dispatch.bind(this),this._root=e.root||md(e.parent)||document,this.viewState=new sa(this,e.state||W.create(e)),e.scrollTo&&e.scrollTo.is(Cn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(ei).map(r=>new Kr(r));for(let r of this.plugins)r.update(this);this.observer=new Vp(this),this.inputState=new cp(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Il(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof ne?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,r,s=this.state;for(let u of e){if(u.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=u.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Ic))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=Nc(s,o),a||(l=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(c=null)):this.observer.clear(),s.facet(W.phrases)!=this.state.facet(W.phrases))return this.setState(s);r=ar.create(this,s,e),r.flags|=l;let f=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(f&&(f=f.map(u.changes)),u.scrollIntoView){let{main:O}=u.state.selection,{x:d,y:p}=this.state.facet(C.cursorScrollMargin);f=new ai(O.empty?O:y.cursor(O.head,O.head>O.anchor?-1:1),"nearest","nearest",p,d)}for(let O of u.effects)O.is(Cn)&&(f=O.value.clip(this.state))}this.viewState.update(r,f),this.bidiCache=Or.update(this.bidiCache,r.changes),r.empty||(this.updatePlugins(r),this.inputState.update(r)),t=this.docView.update(r),this.state.facet(Li)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(r.startState.facet(jn)!=r.state.facet(jn)&&(this.viewState.mustMeasureContent=!0),(t||i||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!r.empty)for(let u of this.state.facet(to))try{u(r)}catch(O){Ae(this.state,O,"update listener")}(a||c)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),c&&!zc(this,c)&&h.force&&li(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new sa(this,e),this.plugins=e.facet(ei).map(i=>new Kr(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Il(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(ei),i=e.state.facet(ei);if(t!=i){let r=[];for(let s of i){let o=t.indexOf(s);if(o<0)r.push(new Kr(s));else{let l=this.plugins[o];l.mustUpdate=e,r.push(l)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let r of this.plugins)r.mustUpdate=e;for(let r=0;r-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,r=this.viewState.getScrollOffset(),{scrollAnchorPos:s,scrollAnchorHeight:o,scaleY:l}=this.viewState;Math.abs(r-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0){if(dc(i||this.win))s=-1,o=this.viewState.heightMap.height/this.viewState.scaleY;else{let d=this.viewState.scrollAnchorAt(r);s=d.from,o=d.top}l=this.viewState.scaleY}this.updateState=1;let h=this.viewState.measure();if(!h&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];h&4||([this.measureRequests,c]=[c,this.measureRequests]);let f=c.map(d=>{try{return d.read(this)}catch(p){return Ae(this.state,p),ca}}),u=ar.create(this,this.state,[]),O=!1;u.flags|=h,t?t.flags|=h:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),O=this.docView.update(u),O&&this.docViewUpdate());for(let d=0;d1||p<-1)&&!(P.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){r=r+p,i?s<0?i.scrollTop=i.scrollHeight:i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(to))a(t)}get themeClasses(){return oo+" "+(this.state.facet(so)?Hc:Fc)+" "+this.state.facet(jn)}updateAttrs(){let e=fa(this,Xc,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(dt)?"true":"false",class:"cm-content",style:`${P.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),fa(this,_o,t);let i=this.observer.ignore(()=>{let r=_l(this.contentDOM,this.contentAttrs,t),s=_l(this.dom,this.editorAttrs,e);return r||s});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let r of i.effects)if(r.is(C.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=r.value}}mountStyles(){this.styleModules=this.state.facet(Li);let e=this.state.facet(C.cspNonce);Tt.mount(this.root,this.styleModules.concat(_p).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return is(this,e,Nl(this,e,t,i))}moveByGroup(e,t){return is(this,e,Nl(this,e,t,i=>ep(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),r=this.textDirectionAt(e.from),s=i[t?i.length-1:0];return y.cursor(s.side(t,r)+e.from,s.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,i=!0){return Jd(this,e,t,i)}moveVertically(e,t,i){return is(this,e,tp(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=no(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),no(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),r=this.bidiSpans(i),s=r[nt.find(r,e-i.from,-1,t)];return this.docView.coordsAt(e,t,s.dir==K.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Tc)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Dp)return Qc(e.length);let t=this.textDirectionAt(e.from),i;for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t&&(s.fresh||bc(s.isolates,i=Bl(this,e))))return s.order;i||(i=Bl(this,e));let r=wd(e.text,t,i);return this.bidiCache.push(new Or(e.from,e.to,t,i,!0,r)),r}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||P.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Oc(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,r,s,o;return Cn.of(new ai(typeof e=="number"?y.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(r=t.x)!==null&&r!==void 0?r:"nearest",(s=t.yMargin)!==null&&s!==void 0?s:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Cn.of(new ai(y.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Se.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Se.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Tt.newName(),r=[jn.of(i),Li.of(lo(`.${i}`,e))];return t&&t.dark&&r.push(so.of(!0)),r}static baseTheme(e){return Nt.lowest(Li.of(lo("."+oo,e,Kc)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),r=i&&ee.get(i)||ee.get(e);return((t=r?.root)===null||t===void 0?void 0:t.view)||null}}C.styleModule=Li;C.inputHandler=Pc;C.clipboardInputFilter=Eo;C.clipboardOutputFilter=zo;C.scrollHandler=Cc;C.focusChangeEffect=vc;C.perLineTextDirection=Tc;C.exceptionSink=$c;C.updateListener=to;C.editable=dt;C.mouseSelectionStyle=wc;C.dragMovesSelection=kc;C.clickAddsSelectionRange=xc;C.decorations=Rr;C.blockWrappers=Ac;C.outerDecorations=Wo;C.atomicRanges=dn;C.bidiIsolatedRanges=Rc;C.cursorScrollMargin=Z.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});C.scrollMargins=Mc;C.darkTheme=so;C.cspNonce=Z.define({combine:n=>n.length?n[0]:""});C.contentAttributes=_o;C.editorAttributes=Xc;C.lineWrapping=C.contentAttributes.of({class:"cm-lineWrapping"});C.announce=V.define();const Dp=4096,ca={};class Or{constructor(e,t,i,r,s,o){this.from=e,this.to=t,this.dir=i,this.isolates=r,this.fresh=s,this.order=o}static update(e,t){if(t.empty&&!e.some(s=>s.fresh))return e;let i=[],r=e.length?e[e.length-1].dir:K.LTR;for(let s=Math.max(0,e.length-10);s=0;r--){let s=i[r],o=typeof s=="function"?s(n):s;o&&jo(o,t)}return t}const Ip=P.mac?"mac":P.windows?"win":P.linux?"linux":"key";function Np(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let r,s,o,l;for(let a=0;ai.concat(r),[]))),t}let $t=null;const Fp=4e3;function Hp(n,e=Ip){let t=Object.create(null),i=Object.create(null),r=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,l,a,h,c)=>{var f,u;let O=t[o]||(t[o]=Object.create(null)),d=l.split(/ (?!$)/).map(S=>Np(S,e));for(let S=1;S{let w=$t={view:Q,prefix:b,scope:o};return setTimeout(()=>{$t==w&&($t=null)},Fp),!0}]})}let p=d.join(" ");r(p,!1);let g=O[p]||(O[p]={preventDefault:!1,stopPropagation:!1,run:((u=(f=O._any)===null||f===void 0?void 0:f.run)===null||u===void 0?void 0:u.slice())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:f}=o;for(let u in c)c[u].run.push(O=>f(O,ao))}let a=o[e]||o.key;if(a)for(let h of l)s(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&s(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}let ao=null;function Kp(n,e,t,i){ao=e;let r=hd(e),s=jt(r,0),o=Ft(s)==r.length&&r!=" ",l="",a=!1,h=!1,c=!1;$t&&$t.view==t&&$t.scope==i&&(l=$t.prefix+" ",Vc.indexOf(e.keyCode)<0&&(h=!0,$t=null));let f=new Set,u=g=>{if(g){for(let S of g.run)if(!f.has(S)&&(f.add(S),S(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},O=n[i],d,p;return O&&(u(O[l+Ln(r,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(P.windows&&e.ctrlKey&&e.altKey)&&!(P.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(d=Ct[e.keyCode])&&d!=r?(u(O[l+Ln(d,e,!0)])||e.shiftKey&&(p=Fi[e.keyCode])!=r&&p!=d&&u(O[l+Ln(p,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(O[l+Ln(r,e,!0)])&&(a=!0),!a&&u(O._any)&&(a=!0)),h&&(a=!0),a&&c&&e.stopPropagation(),ao=null,a}function Jp(){return tm}const em=M.line({class:"cm-activeLine"}),tm=Se.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let r=n.lineBlockAt(i.head);r.from>e&&(t.push(em.range(r.from)),e=r.from)}return M.set(t)}},{decorations:n=>n.decorations}),Yn="-10000px";class im{constructor(e,t,i,r){this.facet=t,this.createTooltipView=i,this.removeTooltipView=r,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let s=null;this.tooltipViews=this.tooltips.map(o=>s=i(o,s))}update(e,t){var i;let r=e.state.facet(this.facet),s=r.filter(a=>a);if(r===this.input){for(let a of this.tooltipViews)a.update&&a.update(e);return!1}let o=[],l=t?[]:null;for(let a=0;at[h]=a),t.length=l.length),this.input=r,this.tooltips=s,this.tooltipViews=o,!0}}function nm(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const ss=Z.define({combine:n=>{var e,t,i;return{position:P.ios?"absolute":((e=n.find(r=>r.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(r=>r.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(r=>r.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||nm}}}),Oa=new WeakMap,Jc=Se.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(ss);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new im(n,ef,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(ss);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let r of this.manager.tooltipViews)r.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let r of this.manager.tooltipViews)this.container.appendChild(r.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let r=document.createElement("div");r.className="cm-tooltip-arrow",t.dom.appendChild(r)}return t.dom.style.position=this.position,t.dom.style.top=Yn,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:s}=this.manager.tooltipViews[0];if(P.safari){let o=s.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!s.offsetParent&&s.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let s=this.parent.getBoundingClientRect();s.width&&s.height&&(n=s.width/this.parent.offsetWidth,e=s.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),r=Vo(this.view);return{visible:{left:i.left+r.left,top:i.top+r.top,right:i.right-r.right,bottom:i.bottom-r.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((s,o)=>{let l=this.manager.tooltipViews[o];return l.getCoords?l.getCoords(s.pos):this.view.coordsAtPos(s.pos)}),size:this.manager.tooltipViews.map(({dom:s})=>s.getBoundingClientRect()),space:this.view.state.facet(ss).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:t,space:i,scaleX:r,scaleY:s}=n,o=[];for(let l=0;l=Math.min(t.bottom,i.bottom)||f.rightMath.min(t.right,i.right)+.1)){c.style.top=Yn;continue}let O=a.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,d=O?7:0,p=u.right-u.left,g=(e=Oa.get(h))!==null&&e!==void 0?e:u.bottom-u.top,S=h.offset||sm,b=this.view.textDirection==K.LTR,Q=u.width>i.right-i.left?b?i.left:i.right-u.width:b?Math.max(i.left,Math.min(f.left-(O?14:0)+S.x,i.right-p)):Math.min(Math.max(i.left,f.left-p+(O?14:0)-S.x),i.right-p),w=this.above[l];!a.strictSide&&(w?f.top-g-d-S.yi.bottom)&&w==i.bottom-f.bottom>f.top-i.top&&(w=this.above[l]=!w);let k=(w?f.top-i.top:i.bottom-f.bottom)-d;if(kQ&&L.topv&&(v=w?L.top-g-2-d:L.bottom+d+2);if(this.position=="absolute"?(c.style.top=(v-n.parent.top)/s+"px",da(c,(Q-n.parent.left)/r)):(c.style.top=v/s+"px",da(c,Q/r)),O){let L=f.left+(b?S.x:-S.x)-(Q+14-7);O.style.left=L/r+"px"}h.overlap!==!0&&o.push({left:Q,top:v,right:T,bottom:v+g}),c.classList.toggle("cm-tooltip-above",w),c.classList.toggle("cm-tooltip-below",!w),h.positioned&&h.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=Yn}},{eventObservers:{scroll(){this.maybeMeasure()}}});function da(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}const rm=C.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),sm={x:0,y:0},ef=Z.define({enables:[Jc,rm]});function tf(n,e){let t=n.plugin(Jc);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}class Dt extends vt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Dt.prototype.elementClass="";Dt.prototype.toDOM=void 0;Dt.prototype.mapMode=me.TrackBefore;Dt.prototype.startSide=Dt.prototype.endSide=-1;Dt.prototype.point=!0;const os=Z.define(),om=Z.define(),Fn=Z.define(),pa=Z.define({combine:n=>n.some(e=>e)});function lm(n){return[am]}const am=Se.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(Fn).map(e=>new ga(n,e)),this.fixed=!n.state.facet(pa);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(pa)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=E.iter(this.view.state.facet(os),this.view.viewport.from),i=[],r=this.gutters.map(s=>new hm(s,this.view.viewport,-this.view.documentPadding.top));for(let s of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(s.type)){let o=!0;for(let l of s.type)if(l.type==Pe.Text&&o){ho(t,i,l.from);for(let a of r)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of r)a.widget(this.view,l)}else if(s.type==Pe.Text){ho(t,i,s.from);for(let o of r)o.line(this.view,s,i)}else if(s.widget)for(let o of r)o.widget(this.view,s);for(let s of r)s.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(Fn),t=n.state.facet(Fn),i=n.docChanged||n.heightChanged||n.viewportChanged||!E.eq(n.startState.facet(os),n.state.facet(os),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let r of this.gutters)r.update(n)&&(i=!0);else{i=!0;let r=[];for(let s of t){let o=e.indexOf(s);o<0?r.push(new ga(this.view,s)):(this.gutters[o].update(n),r.push(this.gutters[o]))}for(let s of this.gutters)s.dom.remove(),r.indexOf(s)<0&&s.destroy();for(let s of r)s.config.side=="after"?this.getDOMAfter().appendChild(s.dom):this.dom.appendChild(s.dom);this.gutters=r}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>C.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,r=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==K.LTR?{left:i,right:r}:{right:i,left:r}})});function ma(n){return Array.isArray(n)?n:[n]}function ho(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class hm{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=E.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:r}=this,s=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==r.elements.length){let l=new nf(e,o,s,i);r.elements.push(l),r.dom.appendChild(l.dom)}else r.elements[this.i].update(e,o,s,i);this.height=t.bottom,this.i++}line(e,t,i){let r=[];ho(this.cursor,r,t.from),i.length&&(r=r.concat(i));let s=this.gutter.config.lineMarker(e,t,r);s&&r.unshift(s);let o=this.gutter;r.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,r)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),r=i?[i]:null;for(let s of e.state.facet(om)){let o=s(e,t.widget,t);o&&(r||(r=[])).push(o)}r&&this.addElement(e,t,r)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class ga{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,r=>{let s=r.target,o;if(s!=this.dom&&this.dom.contains(s)){for(;s.parentNode!=this.dom;)s=s.parentNode;let a=s.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=r.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,r)&&r.preventDefault()});this.markers=ma(t.markers(e)),t.initialSpacer&&(this.spacer=new nf(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=ma(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let r=this.config.updateSpacer(this.spacer.markers[0],e);r!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[r])}let i=e.view.viewport;return!E.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class nf{constructor(e,t,i,r){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,r)}update(e,t,i,r){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),cm(this.markers,r)||this.setMarkers(e,r)}setMarkers(e,t){let i="cm-gutterElement",r=this.dom.firstChild;for(let s=0,o=0;;){let l=o,a=ss(l,a,h)||o(l,a,h):o}return i}})}});class ls extends Dt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function as(n,e){return n.state.facet(ti).formatNumber(e,n.state)}const Om=Fn.compute([ti],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(fm)},lineMarker(e,t,i){return i.some(r=>r.toDOM)?null:new ls(as(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let r of e.state.facet(um)){let s=r(e,t,i);if(s)return s}return null},lineMarkerChange:e=>e.startState.facet(ti)!=e.state.facet(ti),initialSpacer(e){return new ls(as(e,Sa(e.state.doc.lines)))},updateSpacer(e,t){let i=as(t.view,Sa(t.view.state.doc.lines));return i==e.number?e:new ls(i)},domEventHandlers:n.facet(ti).domEventHandlers,side:"before"}));function dm(n={}){return[ti.of(n),lm(),Om]}function Sa(n){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=se.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}R.closedBy=new R({deserialize:n=>n.split(" ")});R.openedBy=new R({deserialize:n=>n.split(" ")});R.group=new R({deserialize:n=>n.split(" ")});R.isolate=new R({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});R.contextHash=new R({perNode:!0});R.lookAhead=new R({perNode:!0});R.mounted=new R({perNode:!0});class hi{constructor(e,t,i,r=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=r}static get(e){return e&&e.props&&e.props[R.mounted.id]}}const mm=Object.create(null);class se{constructor(e,t,i,r=0){this.name=e,this.props=t,this.id=i,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):mm,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),r=new se(e.name||"",t,e.id,i);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(r)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return r}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(R.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let r of i.split(" "))t[r]=e[i];return i=>{for(let r=i.prop(R.group),s=-1;s<(r?r.length:0);s++){let o=t[s<0?i.name:r[s]];if(o)return o}}}}se.none=new se("",Object.create(null),0,8);class mn{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|D.IncludeAnonymous);;){let h=!1;if(a.from<=s&&a.to>=r&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Go(se.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,r)=>new B(this.type,t,i,r,this.propValues),e.makeTree||((t,i,r)=>new B(se.none,t,i,r)))}static build(e){return Qm(e)}}B.empty=new B(se.none,[],[],0);class Io{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Io(this.buffer,this.index)}}class Xt{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return se.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let r=this.buffer,s=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function en(n,e,t,i){for(var r;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from,u;if(!(!(s&D.EnterBracketed&&c instanceof B&&(u=hi.get(c))&&!u.overlay&&u.bracketed&&i>=f&&i<=f+c.length)&&!sf(r,i,f,f+c.length))){if(c instanceof Xt){if(s&D.ExcludeBuffers)continue;let O=c.findChild(0,c.buffer.length,t,i-f,r);if(O>-1)return new rt(new gm(o,c,e,f),null,O)}else if(s&D.IncludeAnonymous||!c.type.isAnonymous||No(c)){let O;if(!(s&D.IgnoreMounts)&&(O=hi.get(c))&&!O.overlay)return new ue(O.tree,f,e,o);let d=new ue(c,f,e,o);return s&D.IncludeAnonymous||!d.type.isAnonymous?d:d.nextChild(t<0?c.children.length-1:0,t,i,r,s)}}}if(s&D.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let r;if(!(i&D.IgnoreOverlays)&&(r=hi.get(this._tree))&&r.overlay){let s=e-this.from,o=i&D.EnterBracketed&&r.bracketed;for(let{from:l,to:a}of r.overlay)if((t>0||o?l<=s:l=s:a>s))return new ue(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function Qa(n,e,t,i){let r=n.cursor(),s=[];if(!r.firstChild())return s;if(t!=null){for(let o=!1;!o;)if(o=r.type.is(t),!r.nextSibling())return s}for(;;){if(i!=null&&r.type.is(i))return s;if(r.type.is(e)&&s.push(r.node),!r.nextSibling())return i==null?s:[]}}function co(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class gm{constructor(e,t,i,r){this.parent=e,this.buffer=t,this.index=i,this.start=r}}class rt extends of{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,i);return s<0?null:new rt(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&D.ExcludeBuffers)return null;let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new rt(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new rt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new rt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,r=this.index+4,s=i.buffer[this.index+3];if(s>r){let o=i.buffer[this.index+1];e.push(i.slice(r,s,o)),t.push(0)}return new B(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function lf(n){if(!n.length)return null;let e=0,t=n[0];for(let s=1;st.from||o.to=e){let l=new ue(o.tree,o.overlay[0].from+s.from,-1,s);(r||(r=[i])).push(en(l,e,t,!1))}}return r?lf(r):i}class dr{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~D.EnterBracketed,e instanceof ue)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=i+r.buffer[e+1],this.to=i+r.buffer[e+2],!0}yield(e){return e?e instanceof ue?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:r}=this.buffer,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,i);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&D.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&D.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&D.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let r=i<0?0:this.stack[i]+4;if(this.index!=r)return this.yieldBuf(t.findChild(r,this.index,-1,0,4))}else{let r=t.buffer[this.index+3];if(r<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(r)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let s=t+e,o=e<0?-1:i._tree.children.length;s!=o;s+=e){let l=i._tree.children[s];if(this.mode&D.IncludeAnonymous||l instanceof Xt||!l.type.isAnonymous||No(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==r){if(r==this.index)return o;t=o,i=s+1;break e}r=this.stack[--s]}for(let r=i;r=0;s--){if(s<0)return co(this._tree,e,r);let o=i[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[r]&&e[r]!=o.name)return!1;r--}}return!0}}function No(n){return n.children.some(e=>e instanceof Xt||!e.type.isAnonymous||No(e))}function Qm(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:r=rf,reused:s=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new Io(t,t.length):t,a=i.types,h=0,c=0;function f(k,v,T,L,I,U){let{id:Y,start:A,end:q,size:N}=l,te=c,Ue=h;if(N<0)if(l.next(),N==-1){let Me=s[Y];T.push(Me),L.push(A-k);return}else if(N==-3){h=Y;return}else if(N==-4){c=Y;return}else throw new RangeError(`Unrecognized record size: ${N}`);let ht=a[Y],H,Fe,Gt=A-k;if(q-A<=r&&(Fe=g(l.pos-v,I))){let Me=new Uint16Array(Fe.size-Fe.skip),de=l.pos-Fe.size,Qe=Me.length;for(;l.pos>de;)Qe=S(Fe.start,Me,Qe);H=new Xt(Me,q-Fe.start,i),Gt=Fe.start-k}else{let Me=l.pos-N;l.next();let de=[],Qe=[],ct=Y>=o?Y:-1,Qt=0,Ut=q;for(;l.pos>Me;)ct>=0&&l.id==ct&&l.size>=0?(l.end<=Ut-r&&(d(de,Qe,A,Qt,l.end,Ut,ct,te,Ue),Qt=de.length,Ut=l.end),l.next()):U>2500?u(A,Me,de,Qe):f(A,Me,de,Qe,ct,U+1);if(ct>=0&&Qt>0&&Qt-1&&Qt>0){let ye=O(ht,Ue);H=Go(ht,de,Qe,0,de.length,0,q-A,ye,ye)}else H=p(ht,de,Qe,q-A,te-q,Ue)}T.push(H),L.push(Gt)}function u(k,v,T,L){let I=[],U=0,Y=-1;for(;l.pos>v;){let{id:A,start:q,end:N,size:te}=l;if(te>4)l.next();else{if(Y>-1&&q=0;N-=3)A[te++]=I[N],A[te++]=I[N+1]-q,A[te++]=I[N+2]-q,A[te++]=te;T.push(new Xt(A,I[2]-q,i)),L.push(q-k)}}function O(k,v){return(T,L,I)=>{let U=0,Y=T.length-1,A,q;if(Y>=0&&(A=T[Y])instanceof B){if(!Y&&A.type==k&&A.length==I)return A;(q=A.prop(R.lookAhead))&&(U=L[Y]+A.length+q)}return p(k,T,L,I,U,v)}}function d(k,v,T,L,I,U,Y,A,q){let N=[],te=[];for(;k.length>L;)N.push(k.pop()),te.push(v.pop()+T-I);k.push(p(i.types[Y],N,te,U-I,A-U,q)),v.push(I-T)}function p(k,v,T,L,I,U,Y){if(U){let A=[R.contextHash,U];Y=Y?[A].concat(Y):[A]}if(I>25){let A=[R.lookAhead,I];Y=Y?[A].concat(Y):[A]}return new B(k,v,T,L,Y)}function g(k,v){let T=l.fork(),L=0,I=0,U=0,Y=T.end-r,A={size:0,start:0,skip:0};e:for(let q=T.pos-k;T.pos>q;){let N=T.size;if(T.id==v&&N>=0){A.size=L,A.start=I,A.skip=U,U+=4,L+=4,T.next();continue}let te=T.pos-N;if(N<0||te=o?4:0,ht=T.start;for(T.next();T.pos>te;){if(T.size<0)if(T.size==-3||T.size==-4)Ue+=4;else break e;else T.id>=o&&(Ue+=4);T.next()}I=ht,L+=N,U+=Ue}return(v<0||L==k)&&(A.size=L,A.start=I,A.skip=U),A.size>4?A:void 0}function S(k,v,T){let{id:L,start:I,end:U,size:Y}=l;if(l.next(),Y>=0&&L4){let q=l.pos-(Y-4);for(;l.pos>q;)T=S(k,v,T)}v[--T]=A,v[--T]=U-k,v[--T]=I-k,v[--T]=L}else Y==-3?h=L:Y==-4&&(c=L);return T}let b=[],Q=[];for(;l.pos>0;)f(n.start||0,n.bufferStart||0,b,Q,-1,0);let w=(e=n.length)!==null&&e!==void 0?e:b.length?Q[0]+b[0].length:0;return new B(a[n.topID],b.reverse(),Q.reverse(),w)}const ya=new WeakMap;function Hn(n,e){if(!n.isAnonymous||e instanceof Xt||e.type!=n)return 1;let t=ya.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof B)){t=1;break}t+=Hn(n,i)}ya.set(e,t)}return t}function Go(n,e,t,i,r,s,o,l,a){let h=0;for(let d=i;d=c)break;v+=T}if(Q==w+1){if(v>c){let T=d[w];O(T.children,T.positions,0,T.children.length,p[w]+b);continue}f.push(d[w])}else{let T=p[Q-1]+d[Q-1].length-k;f.push(Go(n,d,p,w,Q,k,T,null,a))}u.push(k+b-s)}}return O(e,t,i,r,0),(l||a)(f,u,o)}class af{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let r=this.map.get(e);r||this.map.set(e,r=new Map),r.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof rt?this.setBuffer(e.context.buffer,e.index,t):e instanceof ue&&this.map.set(e.tree,t)}get(e){return e instanceof rt?this.getBuffer(e.context.buffer,e.index):e instanceof ue?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class gt{constructor(e,t,i,r,s=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=r,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let r=[new gt(0,e.length,e,0,!1,i)];for(let s of t)s.to>e.length&&r.push(s);return r}static applyChanges(e,t,i=128){if(!t.length)return e;let r=[],s=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let O=Math.max(u.from,a)-h,d=Math.min(u.to,f)-h;u=O>=d?null:new gt(O,d,u.tree,u.offset+h,l>0,!!c)}if(u&&r.push(u),o.to>f)break;o=snew Le(r.from,r.to)):[new Le(0,0)]:[new Le(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let r=this.startParse(e,t,i);for(;;){let s=r.advance();if(s)return s}}}class ym{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}function hf(n){return(e,t,i,r)=>new km(e,n,t,i,r)}class xa{constructor(e,t,i,r,s,o){this.parser=e,this.parse=t,this.overlay=i,this.bracketed=r,this.target=s,this.from=o}}function ka(n){if(!n.length||n.some(e=>e.from>=e.to))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(n))}class xm{constructor(e,t,i,r,s,o,l,a){this.parser=e,this.predicate=t,this.mounts=i,this.index=r,this.start=s,this.bracketed=o,this.target=l,this.prev=a,this.depth=0,this.ranges=[]}}const fo=new R({perNode:!0});class km{constructor(e,t,i,r,s){this.nest=t,this.input=i,this.fragments=r,this.ranges=s,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let i=this.baseParse.advance();if(!i)return null;if(this.baseParse=null,this.baseTree=i,this.startInner(),this.stoppedAt!=null)for(let r of this.inner)r.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let i=this.baseTree;return this.stoppedAt!=null&&(i=new B(i.type,i.children,i.positions,i.length,i.propValues.concat([[fo,this.stoppedAt]]))),i}let e=this.inner[this.innerDone],t=e.parse.advance();if(t){this.innerDone++;let i=Object.assign(Object.create(null),e.target.props);i[R.mounted.id]=new hi(t,e.overlay,e.parser,e.bracketed),e.target.props=i}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let t=this.innerDone;t=this.stoppedAt)l=!1;else if(e.hasNode(r)){if(t){let h=t.mounts.find(c=>c.frag.from<=r.from&&c.frag.to>=r.to&&c.mount.overlay);if(h)for(let c of h.mount.overlay){let f=c.from+h.pos,u=c.to+h.pos;f>=r.from&&u<=r.to&&!t.ranges.some(O=>O.fromf)&&t.ranges.push({from:f,to:u})}}l=!1}else if(i&&(o=wm(i.ranges,r.from,r.to)))l=o!=2;else if(!r.type.isAnonymous&&(s=this.nest(r,this.input))&&(r.fromnew Le(f.from-r.from,f.to-r.from)):null,!!s.bracketed,r.tree,c.length?c[0].from:r.from)),s.overlay?c.length&&(i={ranges:c,depth:0,prev:i}):l=!1}}else if(t&&(a=t.predicate(r))&&(a===!0&&(a=new Le(r.from,r.to)),a.from=0&&t.ranges[h].to==a.from?t.ranges[h]={from:t.ranges[h].from,to:a.to}:t.ranges.push(a)}if(l&&r.firstChild())t&&t.depth++,i&&i.depth++;else for(;!r.nextSibling();){if(!r.parent())break e;if(t&&!--t.depth){let h=Pa(this.ranges,t.ranges);h.length&&(ka(h),this.inner.splice(t.index,0,new xa(t.parser,t.parser.startParse(this.input,va(t.mounts,h),h),t.ranges.map(c=>new Le(c.from-t.start,c.to-t.start)),t.bracketed,t.target,h[0].from))),t=t.prev}i&&!--i.depth&&(i=i.prev)}}}}function wm(n,e,t){for(let i of n){if(i.from>=t)break;if(i.to>e)return i.from<=e&&i.to>=t?2:1}return 0}function wa(n,e,t,i,r,s){if(e=e&&t.enter(i,1,D.IgnoreOverlays|D.ExcludeBuffers)))if(t.to<=e)t.next(!1)||(this.done=!0);else break}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let t=this.cursor.tree;;){if(t==e.tree)return!0;if(t.children.length&&t.positions[0]==0&&t.children[0]instanceof B)t=t.children[0];else break}return!1}}let Pm=class{constructor(e){var t;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let i=this.curFrag=e[0];this.curTo=(t=i.tree.prop(fo))!==null&&t!==void 0?t:i.to,this.inner=new $a(i.tree,-i.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let t=this.curFrag=this.fragments[this.fragI];this.curTo=(e=t.tree.prop(fo))!==null&&e!==void 0?e:t.to,this.inner=new $a(t.tree,-t.offset)}}findMounts(e,t){var i;let r=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let s=this.inner.cursor.node;s;s=s.parent){let o=(i=s.tree)===null||i===void 0?void 0:i.prop(R.mounted);if(o&&o.parser==t)for(let l=this.fragI;l=s.to)break;a.tree==this.curFrag.tree&&r.push({frag:a,pos:s.from-a.offset,mount:o})}}}return r}};function Pa(n,e){let t=null,i=e;for(let r=1,s=0;r=l)break;a.to<=o||(t||(i=t=e.slice()),a.froml&&t.splice(s+1,0,new Le(l,a.to))):a.to>l?t[s--]=new Le(l,a.to):t.splice(s--,1))}}return i}function vm(n,e,t,i){let r=0,s=0,o=!1,l=!1,a=-1e9,h=[];for(;;){let c=r==n.length?1e9:o?n[r].to:n[r].from,f=s==e.length?1e9:l?e[s].to:e[s].from;if(o!=l){let u=Math.max(a,t),O=Math.min(c,f,i);unew Le(u.from+i,u.to+i)),f=vm(e,c,a,h);for(let u=0,O=a;;u++){let d=u==f.length,p=d?h:f[u].from;if(p>O&&t.push(new gt(O,p,r.tree,-o,s.from>=O||s.openStart,s.to<=p||s.openEnd)),d)break;O=f[u].to}}else t.push(new gt(a,h,r.tree,-o,s.from>=o||s.openStart,s.to<=l||s.openEnd))}return t}let Tm=0;class Xe{constructor(e,t,i,r){this.name=e,this.set=t,this.base=i,this.modified=r,this.id=Tm++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof Xe&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let r=new Xe(i,[],null,[]);if(r.set.push(r),t)for(let s of t.set)r.set.push(s);return r}static defineModifier(e){let t=new pr(e);return i=>i.modified.indexOf(t)>-1?i:pr.get(i.base||i,i.modified.concat(t).sort((r,s)=>r.id-s.id))}}let Cm=0;class pr{constructor(e){this.name=e,this.instances=[],this.id=Cm++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Zm(t,l.modified));if(i)return i;let r=[],s=new Xe(e.name,r,e,t);for(let l of t)l.instances.push(s);let o=Xm(t);for(let l of e.set)if(!l.modified.length)for(let a of o)r.push(pr.get(l,a));return s}}function Zm(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function Xm(n){let e=[[]];for(let t=0;ti.length-t.length)}function xi(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let r of t.split(" "))if(r){let s=[],o=2,l=r;for(let f=0;;){if(l=="..."&&f>0&&f+3==r.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+r);if(s.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==r.length)break;let O=r[f++];if(f==r.length&&O=="!"){o=0;break}if(O!="/")throw new RangeError("Invalid path: "+r);l=r.slice(f)}let a=s.length-1,h=s[a];if(!h)throw new RangeError("Invalid path: "+r);let c=new tn(i,o,a>0?s.slice(0,a):null);e[h]=c.sort(e[h])}}return cf.add(e)}const cf=new R({combine(n,e){let t,i,r;for(;n||e;){if(!n||e&&n.depth>=e.depth?(r=e,e=e.next):(r=n,n=n.next),t&&t.mode==r.mode&&!r.context&&!t.context)continue;let s=new tn(r.tags,r.mode,r.context);t?t.next=s:i=s,t=s}return i}});class tn{constructor(e,t,i,r){this.tags=e,this.mode=t,this.context=i,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=r;for(let l of s)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Am(n,e){let t=null;for(let i of n){let r=i.style(e);r&&(t=t?t+" "+r:r)}return t}function Rm(n,e,t,i=0,r=n.length){let s=new Mm(i,Array.isArray(e)?e:[e],t);s.highlightRange(n.cursor(),i,r,"",s.highlighters),s.flush(r)}class Mm{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,r,s){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(s=this.highlighters.filter(O=>!O.scope||O.scope(o)));let h=r,c=jm(e)||tn.empty,f=Am(s,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(r+=(r?" ":"")+f)),this.startSpan(Math.max(t,l),h),c.opaque)return;let u=e.tree&&e.tree.prop(R.mounted);if(u&&u.overlay){let O=e.node.enter(u.overlay[0].from+l,1),d=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),p=e.firstChild();for(let g=0,S=l;;g++){let b=g=Q||!e.nextSibling())););if(!b||Q>i)break;S=b.to+l,S>t&&(this.highlightRange(O.cursor(),Math.max(t,b.from+l),Math.min(i,S),"",d),this.startSpan(Math.min(i,S),h))}p&&e.parent()}else if(e.firstChild()){u&&(r="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,r,s),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}}function jm(n){let e=n.type.prop(cf);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const $=Xe.define,zn=$(),xt=$(),Ta=$(xt),Ca=$(xt),kt=$(),_n=$(kt),hs=$(kt),et=$(),Rt=$(et),Ke=$(),Je=$(),uo=$(),Zi=$(uo),Wn=$(),m={comment:zn,lineComment:$(zn),blockComment:$(zn),docComment:$(zn),name:xt,variableName:$(xt),typeName:Ta,tagName:$(Ta),propertyName:Ca,attributeName:$(Ca),className:$(xt),labelName:$(xt),namespace:$(xt),macroName:$(xt),literal:kt,string:_n,docString:$(_n),character:$(_n),attributeValue:$(_n),number:hs,integer:$(hs),float:$(hs),bool:$(kt),regexp:$(kt),escape:$(kt),color:$(kt),url:$(kt),keyword:Ke,self:$(Ke),null:$(Ke),atom:$(Ke),unit:$(Ke),modifier:$(Ke),operatorKeyword:$(Ke),controlKeyword:$(Ke),definitionKeyword:$(Ke),moduleKeyword:$(Ke),operator:Je,derefOperator:$(Je),arithmeticOperator:$(Je),logicOperator:$(Je),bitwiseOperator:$(Je),compareOperator:$(Je),updateOperator:$(Je),definitionOperator:$(Je),typeOperator:$(Je),controlOperator:$(Je),punctuation:uo,separator:$(uo),bracket:Zi,angleBracket:$(Zi),squareBracket:$(Zi),paren:$(Zi),brace:$(Zi),content:et,heading:Rt,heading1:$(Rt),heading2:$(Rt),heading3:$(Rt),heading4:$(Rt),heading5:$(Rt),heading6:$(Rt),contentSeparator:$(et),list:$(et),quote:$(et),emphasis:$(et),strong:$(et),link:$(et),monospace:$(et),strikethrough:$(et),inserted:$(),deleted:$(),changed:$(),invalid:$(),meta:Wn,documentMeta:$(Wn),annotation:$(Wn),processingInstruction:$(Wn),definition:Xe.defineModifier("definition"),constant:Xe.defineModifier("constant"),function:Xe.defineModifier("function"),standard:Xe.defineModifier("standard"),local:Xe.defineModifier("local"),special:Xe.defineModifier("special")};for(let n in m){let e=m[n];e instanceof Xe&&(e.name=n)}ff([{tag:m.link,class:"tok-link"},{tag:m.heading,class:"tok-heading"},{tag:m.emphasis,class:"tok-emphasis"},{tag:m.strong,class:"tok-strong"},{tag:m.keyword,class:"tok-keyword"},{tag:m.atom,class:"tok-atom"},{tag:m.bool,class:"tok-bool"},{tag:m.url,class:"tok-url"},{tag:m.labelName,class:"tok-labelName"},{tag:m.inserted,class:"tok-inserted"},{tag:m.deleted,class:"tok-deleted"},{tag:m.literal,class:"tok-literal"},{tag:m.string,class:"tok-string"},{tag:m.number,class:"tok-number"},{tag:[m.regexp,m.escape,m.special(m.string)],class:"tok-string2"},{tag:m.variableName,class:"tok-variableName"},{tag:m.local(m.variableName),class:"tok-variableName tok-local"},{tag:m.definition(m.variableName),class:"tok-variableName tok-definition"},{tag:m.special(m.variableName),class:"tok-variableName2"},{tag:m.definition(m.propertyName),class:"tok-propertyName tok-definition"},{tag:m.typeName,class:"tok-typeName"},{tag:m.namespace,class:"tok-namespace"},{tag:m.className,class:"tok-className"},{tag:m.macroName,class:"tok-macroName"},{tag:m.propertyName,class:"tok-propertyName"},{tag:m.operator,class:"tok-operator"},{tag:m.comment,class:"tok-comment"},{tag:m.meta,class:"tok-meta"},{tag:m.invalid,class:"tok-invalid"},{tag:m.punctuation,class:"tok-punctuation"}]);var cs;const _t=new R;function Fo(n){return Z.define({combine:n?e=>e.concat(n):void 0})}const Ho=new R;class Ye{constructor(e,t,i=[],r=""){this.data=e,this.name=r,W.prototype.hasOwnProperty("tree")||Object.defineProperty(W.prototype,"tree",{get(){return J(this)}}),this.parser=t,this.extension=[Si.of(this),W.languageData.of((s,o,l)=>{let a=Za(s,o,l),h=a.type.prop(_t);if(!h)return[];let c=s.facet(h),f=a.type.prop(Ho);if(f){let u=a.resolve(o-a.from,l);for(let O of f)if(O.test(u,s)){let d=s.facet(O.facet);return O.type=="replace"?d:d.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return Za(e,t,i).type.prop(_t)==this.data}findRegions(e){let t=e.facet(Si);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],r=(s,o)=>{if(s.prop(_t)==this.data){i.push({from:o,to:o+s.length});return}let l=s.prop(R.mounted);if(l){if(l.tree.prop(_t)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+s.length});return}else if(l.overlay){let a=i.length;if(r(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new mi(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function J(n){let e=n.field(Ye.state,!1);return e?e.tree:B.empty}class Lm{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let Xi=null;class nn{constructor(e,t,i=[],r,s,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=r,this.treeLen=s,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new nn(e,t,[],B.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Lm(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=B.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let r=Date.now()+e;e=()=>Date.now()>r}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(gt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Xi;Xi=this;try{return e()}finally{Xi=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Xa(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:r,treeLen:s,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=gt.applyChanges(i,a),r=B.empty,s=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=Xa(this.fragments,r,s),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Uo{createParse(t,i,r){let s=r[0].from,o=r[r.length-1].to;return{parsedPos:s,advance(){let a=Xi;if(a){for(let h of r)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new B(se.none,[],[],o-s)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Xi}}function Xa(n,e,t){return gt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class gi{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new gi(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=nn.create(e.facet(Si).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new gi(i)}}Ye.state=_e.define({create:gi.init,update(n,e){for(let t of e.effects)if(t.is(Ye.setState))return t.value;return e.startState.facet(Si)!=e.state.facet(Si)?gi.init(e.state):n.apply(e)}});let uf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(uf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const fs=typeof navigator<"u"&&(!((cs=navigator.scheduling)===null||cs===void 0)&&cs.isInputPending)?()=>navigator.scheduling.isInputPending():null,Ym=Se.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Ye.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Ye.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=uf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndr+1e3,a=s.context.work(()=>fs&&fs()||Date.now()>o,r+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:Ye.setState.of(new gi(s.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>Ae(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),Si=Z.define({combine(n){return n.length?n[0]:null},enables:n=>[Ye.state,Ym,C.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class rn{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}class mr{constructor(e,t,i,r,s,o=void 0){this.name=e,this.alias=t,this.extensions=i,this.filename=r,this.loadFunc=s,this.support=o,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(e=>this.support=e,e=>{throw this.loading=null,e}))}static of(e){let{load:t,support:i}=e;if(!t){if(!i)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");t=()=>Promise.resolve(i)}return new mr(e.name,(e.alias||[]).concat(e.name).map(r=>r.toLowerCase()),e.extensions||[],e.filename,t,i)}static matchFilename(e,t){for(let r of e)if(r.filename&&r.filename.test(t))return r;let i=/\.([^.]+)$/.exec(t);if(i){for(let r of e)if(r.extensions.indexOf(i[1])>-1)return r}return null}static matchLanguageName(e,t,i=!0){t=t.toLowerCase();for(let r of e)if(r.alias.some(s=>s==t))return r;if(i)for(let r of e)for(let s of r.alias){let o=t.indexOf(s);if(o>-1&&(s.length>2||!/\w/.test(t[o-1])&&!/\w/.test(t[o+s.length])))return r}return null}}const Em=Z.define(),gn=Z.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function gr(n){let e=n.facet(gn);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Sr(n,e){let t="",i=n.tabSize,r=n.facet(gn)[0];if(r==" "){for(;e>=i;)t+=" ",e-=i;r=" "}for(let s=0;s=e?zm(n,t,e):null}class Yr{constructor(e,t={}){this.state=e,this.options=t,this.unit=gr(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:r,simulateDoubleBreak:s}=this.options;return r!=null&&r>=i.from&&r<=i.to?s&&r==e?{text:"",from:e}:(t<0?r-1&&(s+=o-this.countColumn(i,i.search(/\S|$/))),s}countColumn(e,t=e.length){return St(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:r}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let o=s(r);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const Sn=new R;function zm(n,e,t){let i=e.resolveStack(t),r=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(r!=i.node){let s=[];for(let o=r;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)s.push(o);for(let o=s.length-1;o>=0;o--)i={node:s[o],next:i}}return df(i,n,t)}function df(n,e,t){for(let i=n;i;i=i.next){let r=Wm(i.node);if(r)return r(Ko.create(e,t,i))}return 0}function _m(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function Wm(n){let e=n.type.prop(Sn);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(R.closedBy))){let r=n.lastChild,s=r&&i.indexOf(r.name)>-1;return o=>pf(o,!0,1,void 0,s&&!_m(o)?r.from:void 0)}return n.parent==null?Vm:null}function Vm(){return 0}class Ko extends Yr{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new Ko(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(Bm(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return df(this.context.next,this.base,this.pos)}}function Bm(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function qm(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let r=n.options.simulateBreak,s=n.state.doc.lineAt(t.from),o=r==null||r<=s.from?s.to:Math.min(s.to,r);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(s.text.slice(t.to-s.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function Dm({closing:n,align:e=!0,units:t=1}){return i=>pf(i,e,t,n)}function pf(n,e,t,i,r){let s=n.textAfter,o=s.match(/^\s*/)[0].length,l=i&&s.slice(o,o+i.length)==i||r==n.pos+o,a=e?qm(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}const Im=n=>n.baseIndent;function Kn({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const mf=Z.define(),ki=new R;function gf(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(s&&l.from=e&&h.to>t&&(s=h)}}return s}function Gm(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Sf(n,e,t){for(let i of n.facet(mf)){let r=i(n,e,t);if(r)return r}return Nm(n,e,t)}function bf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const bn=V.define({map:bf}),Qn=V.define({map:bf});function Qf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const wi=_e.define({create(){return M.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((i,r)=>n=Aa(n,i,r)),n=n.map(e.changes);let t=[];for(let i of e.effects)i.is(bn)&&!Fm(n,i.value.from,i.value.to)?t.push(i.value):i.is(Qn)&&(n=n.update({filter:(r,s)=>i.value.from!=r||i.value.to!=s,filterFrom:i.value.from,filterTo:i.value.to}));if(t.length){let{preparePlaceholder:i}=e.state.facet(Jo),r=t.map(s=>(i?M.replace({widget:new ng(i(e.state,s))}):Ra).range(s.from,s.to));n=n.update({add:r})}return e.selection&&(n=Aa(n,e.selection.main.head)),n},provide:n=>C.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,r)=>{t.push(i,r)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{re&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(r,s)=>r>=t||s<=e}):n}function Um(n){return n.field(wi,!1)||E.empty}function yf(n,e,t){var i;let r=null;return(i=n.field(wi,!1))===null||i===void 0||i.between(e,t,(s,o)=>{(!r||r.from>s)&&(r={from:s,to:o})}),r}function Fm(n,e,t){let i=!1;return n.between(e,e,(r,s)=>{r==e&&s==t&&(i=!0)}),i}function xf(n,e){return n.field(wi,!1)?e:e.concat(V.appendConfig.of(wf()))}const Hm=n=>{for(let e of Qf(n)){let t=Sf(n.state,e.from,e.to);if(t)return n.dispatch({effects:xf(n.state,[bn.of(t),kf(n,t)])}),!0}return!1},Km=n=>{if(!n.state.field(wi,!1))return!1;let e=[];for(let t of Qf(n)){let i=yf(n.state,t.from,t.to);i&&e.push(Qn.of(i),kf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function kf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,r=n.state.doc.lineAt(e.to).number;return C.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${r}.`)}const Jm=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(wi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,r)=>{t.push(Qn.of({from:i,to:r}))}),n.dispatch({effects:t}),!0},tg=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:Hm},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:Km},{key:"Ctrl-Alt-[",run:Jm},{key:"Ctrl-Alt-]",run:eg}],ig={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},Jo=Z.define({combine(n){return Xr(n,ig)}});function wf(n){let e=[wi,rg];return n&&e.push(Jo.of(n)),e}function $f(n,e){let{state:t}=n,i=t.facet(Jo),r=o=>{let l=n.lineBlockAt(n.posAtDOM(o.target)),a=yf(n.state,l.from,l.to);a&&n.dispatch({effects:Qn.of(a)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,r,e);let s=document.createElement("span");return s.textContent=i.placeholderText,s.setAttribute("aria-label",t.phrase("folded code")),s.title=t.phrase("unfold"),s.className="cm-foldPlaceholder",s.onclick=r,s}const Ra=M.replace({widget:new class extends at{toDOM(n){return $f(n,null)}}});class ng extends at{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return $f(e,this.value)}}const rg=C.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Er{constructor(e,t){this.specs=e;let i;function r(l){let a=Tt.newName();return(i||(i=Object.create(null)))["."+a]=l,a}const s=typeof t.all=="string"?t.all:t.all?r(t.all):void 0,o=t.scope;this.scope=o instanceof Ye?l=>l.prop(_t)==o.data:o?l=>l==o:void 0,this.style=ff(e.map(l=>({tag:l.tag,class:l.class||r(Object.assign({},l,{tag:null}))})),{all:s}).style,this.module=i?new Tt(i):null,this.themeType=t.themeType}static define(e,t){return new Er(e,t||{})}}const Oo=Z.define(),Pf=Z.define({combine(n){return n.length?[n[0]]:null}});function us(n){let e=n.facet(Oo);return e.length?e:n.facet(Pf)}function sg(n,e){let t=[lg],i;return n instanceof Er&&(n.module&&t.push(C.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(Pf.of(n)):i?t.push(Oo.computeN([C.darkTheme],r=>r.facet(C.darkTheme)==(i=="dark")?[n]:[])):t.push(Oo.of(n)),t}class og{constructor(e){this.markCache=Object.create(null),this.tree=J(e.state),this.decorations=this.buildDeco(e,us(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=J(e.state),i=us(e.state),r=i!=us(e.startState),{viewport:s}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=s.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||r)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=s.to)}buildDeco(e,t){if(!t||!this.tree.length)return M.none;let i=new si;for(let{from:r,to:s}of e.visibleRanges)Rm(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=M.mark({class:a})))},r,s);return i.finish()}}const lg=Nt.high(Se.fromClass(og,{decorations:n=>n.decorations})),ag=Er.define([{tag:m.meta,color:"#404740"},{tag:m.link,textDecoration:"underline"},{tag:m.heading,textDecoration:"underline",fontWeight:"bold"},{tag:m.emphasis,fontStyle:"italic"},{tag:m.strong,fontWeight:"bold"},{tag:m.strikethrough,textDecoration:"line-through"},{tag:m.keyword,color:"#708"},{tag:[m.atom,m.bool,m.url,m.contentSeparator,m.labelName],color:"#219"},{tag:[m.literal,m.inserted],color:"#164"},{tag:[m.string,m.deleted],color:"#a11"},{tag:[m.regexp,m.escape,m.special(m.string)],color:"#e40"},{tag:m.definition(m.variableName),color:"#00f"},{tag:m.local(m.variableName),color:"#30a"},{tag:[m.typeName,m.namespace],color:"#085"},{tag:m.className,color:"#167"},{tag:[m.special(m.variableName),m.macroName],color:"#256"},{tag:m.definition(m.propertyName),color:"#00c"},{tag:m.comment,color:"#940"},{tag:m.invalid,color:"#f00"}]),hg=1e4,cg="()[]{}",vf=new R;function po(n,e,t){let i=n.prop(e<0?R.openedBy:R.closedBy);if(i)return i;if(n.name.length==1){let r=t.indexOf(n.name);if(r>-1&&r%2==(e<0?1:0))return[t[r+e]]}return null}function mo(n){let e=n.type.prop(vf);return e?e(n.node):n}function ii(n,e,t,i={}){let r=i.maxScanDistance||hg,s=i.brackets||cg,o=J(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=po(a.type,t,s);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return fg(n,e,t,a,c,h,s)}}return ug(n,e,t,o,l.type,r,s)}function fg(n,e,t,i,r,s,o){let l=i.parent,a={from:r.from,to:r.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&s.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=s;){let O=c.value;t<0&&(u+=O.length);let d=e+u*t;for(let p=t>0?0:O.length-1,g=t>0?O.length:-1;p!=g;p+=t){let S=o.indexOf(O[p]);if(!(S<0||i.resolveInner(d+p,1).type!=r))if(S%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:d+p,to:d+p+1},matched:S>>1==a>>1};f--}}t>0&&(u+=O.length)}return c.done?{start:h,matched:!1}:null}const Og=Object.create(null),Ma=[se.none],ja=[],La=Object.create(null),dg=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])dg[n]=pg(Og,e);function Os(n,e){ja.indexOf(n)>-1||(ja.push(n),console.warn(e))}function pg(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let c=n[h]||m[h];c?typeof c=="function"?a.length?a=a.map(c):Os(h,`Modifier ${h} used at start of tag`):a.length?Os(h,`Tag ${h} used as modifier`):a=Array.isArray(c)?c:[c]:Os(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),r=i+" "+t.map(l=>l.id),s=La[r];if(s)return s.id;let o=La[r]=se.define({id:Ma.length,name:i,props:[xi({[i]:t})]});return Ma.push(o),o.id}K.RTL,K.LTR;const mg=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=tl(n.state,t.from);return i.line?gg(n):i.block?bg(n):!1};function el(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let r=n(e,t);return r?(i(t.update(r)),!0):!1}}const gg=el(xg,0),Sg=el(Tf,0),bg=el((n,e)=>Tf(n,e,yg(e)),0);function tl(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const Ai=50;function Qg(n,{open:e,close:t},i,r){let s=n.sliceDoc(i-Ai,i),o=n.sliceDoc(r,r+Ai),l=/\s*$/.exec(s)[0].length,a=/^\s*/.exec(o)[0].length,h=s.length-l;if(s.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:r+a,margin:a&&1}};let c,f;r-i<=2*Ai?c=f=n.sliceDoc(i,r):(c=n.sliceDoc(i,i+Ai),f=n.sliceDoc(r-Ai,r));let u=/^\s*/.exec(c)[0].length,O=/\s*$/.exec(f)[0].length,d=f.length-O-t.length;return c.slice(u,u+e.length)==e&&f.slice(d,d+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:r-O-t.length,margin:/\s/.test(f.charAt(d-1))?1:0}}:null}function yg(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),r=t.to<=i.to?i:n.doc.lineAt(t.to);r.from>i.from&&r.from==t.to&&(r=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let s=e.length-1;s>=0&&e[s].to>i.from?e[s].to=r.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:r.to})}return e}function Tf(n,e,t=e.selection.ranges){let i=t.map(s=>tl(e,s.from).block);if(!i.every(s=>s))return null;let r=t.map((s,o)=>Qg(e,i[o],s.from,s.to));if(n!=2&&!r.every(s=>s))return{changes:e.changes(t.map((s,o)=>r[o]?[]:[{from:s.from,insert:i[o].open+" "},{from:s.to,insert:" "+i[o].close}]))};if(n!=1&&r.some(s=>s)){let s=[];for(let o=0,l;or&&(s==o||o>f.from)){r=f.from;let u=/^\s*/.exec(f.text)[0].length,O=u==f.length,d=f.text.slice(u,u+h.length)==h?u:-1;us.comment<0&&(!s.empty||s.single))){let s=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&s.push({from:l.from+h,insert:a+" "});let o=e.changes(s);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(s=>s.comment>=0)){let s=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,s.push({from:h,to:c})}return{changes:s}}return null}const go=Ie.define(),kg=Ie.define(),wg=Z.define(),Cf=Z.define({combine(n){return Xr(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,r)=>e(i,r)||t(i,r)})}}),Zf=_e.define({create(){return st.empty},update(n,e){let t=e.state.facet(Cf),i=e.annotation(go);if(i){let a=$e.fromTransaction(e,i.selection),h=i.side,c=h==0?n.undone:n.done;return a?c=br(c,c.length,t.minDepth,a):c=Rf(c,e.startState.selection),new st(h==0?i.rest:c,h==0?c:i.rest)}let r=e.annotation(kg);if((r=="full"||r=="before")&&(n=n.isolate()),e.annotation(ne.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let s=$e.fromTransaction(e),o=e.annotation(ne.time),l=e.annotation(ne.userEvent);return s?n=n.addChanges(s,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(r=="full"||r=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new st(n.done.map($e.fromJSON),n.undone.map($e.fromJSON))}});function $g(n={}){return[Zf,Cf.of(n),C.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Xf:e.inputType=="historyRedo"?So:null;return i?(e.preventDefault(),i(t)):!1}})]}function zr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let r=t.field(Zf,!1);if(!r)return!1;let s=r.pop(n,t,e);return s?(i(s),!0):!1}}const Xf=zr(0,!1),So=zr(1,!1),Pg=zr(0,!0),vg=zr(1,!0);class $e{constructor(e,t,i,r,s){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=r,this.selectionsAfter=s}setSelAfter(e){return new $e(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(r=>r.toJSON())}}static fromJSON(e){return new $e(e.changes&&re.fromJSON(e.changes),[],e.mapped&&ot.fromJSON(e.mapped),e.startSelection&&y.fromJSON(e.startSelection),e.selectionsAfter.map(y.fromJSON))}static fromTransaction(e,t){let i=Ee;for(let r of e.startState.facet(wg)){let s=r(e);s.length&&(i=i.concat(s))}return!i.length&&e.changes.empty?null:new $e(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Ee)}static selection(e){return new $e(void 0,Ee,void 0,void 0,e)}}function br(n,e,t,i){let r=e+1>t+20?e-t-1:0,s=n.slice(r,e);return s.push(i),s}function Tg(n,e){let t=[],i=!1;return n.iterChangedRanges((r,s)=>t.push(r,s)),e.iterChangedRanges((r,s,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function Cg(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Af(n,e){return n.length?e.length?n.concat(e):n:e}const Ee=[],Zg=200;function Rf(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-Zg));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),br(n,n.length-1,1e9,t.setSelAfter(i)))}else return[$e.selection([e])]}function Xg(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function ds(n,e){if(!n.length)return n;let t=n.length,i=Ee;for(;t;){let r=Ag(n[t-1],e,i);if(r.changes&&!r.changes.empty||r.effects.length){let s=n.slice(0,t);return s[t-1]=r,s}else e=r.mapped,t--,i=r.selectionsAfter}return i.length?[$e.selection(i)]:Ee}function Ag(n,e,t){let i=Af(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):Ee,t);if(!n.changes)return $e.selection(i);let r=n.changes.map(e),s=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(s):s;return new $e(r,V.mapEffects(n.effects,e),o,n.startSelection.map(s),i)}const Rg=/^(input\.type|delete)($|\.)/;class st{constructor(e,t,i=0,r=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=r}isolate(){return this.prevTime?new st(this.done,this.undone):this}addChanges(e,t,i,r,s){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||Rg.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):_r(t,e))}function Oe(n){return n.textDirectionAt(n.state.selection.main.head)==K.LTR}const jf=n=>Mf(n,!Oe(n)),Lf=n=>Mf(n,Oe(n));function Yf(n,e){return Ge(n,t=>t.empty?n.moveByGroup(t,e):_r(t,e))}const jg=n=>Yf(n,!Oe(n)),Lg=n=>Yf(n,Oe(n));function Yg(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function Wr(n,e,t){let i=J(n).resolveInner(e.head),r=t?R.closedBy:R.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;Yg(n,h,r)?i=h:a=t?h.to:h.from}let s=i.type.prop(r),o,l;return s&&(o=t?ii(n,i.from,1):ii(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,y.cursor(l,t?-1:1)}const Eg=n=>Ge(n,e=>Wr(n.state,e,!Oe(n))),zg=n=>Ge(n,e=>Wr(n.state,e,Oe(n)));function Ef(n,e){return Ge(n,t=>{if(!t.empty)return _r(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const zf=n=>Ef(n,!1),_f=n=>Ef(n,!0);function Wf(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):_r(o,e));if(r.eq(i.selection))return!1;let s;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomVf(n,!1),bo=n=>Vf(n,!0);function At(n,e,t){let i=n.lineBlockAt(e.head),r=n.moveToLineBoundary(e,t);if(r.head==e.head&&r.head!=(t?i.to:i.from)&&(r=n.moveToLineBoundary(e,t,!1)),!t&&r.head==i.from&&i.length){let s=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;s&&e.head!=i.from+s&&(r=y.cursor(i.from+s))}return r}const _g=n=>Ge(n,e=>At(n,e,!0)),Wg=n=>Ge(n,e=>At(n,e,!1)),Vg=n=>Ge(n,e=>At(n,e,!Oe(n))),Bg=n=>Ge(n,e=>At(n,e,Oe(n))),qg=n=>Ge(n,e=>y.cursor(n.lineBlockAt(e.head).from,1)),Dg=n=>Ge(n,e=>y.cursor(n.lineBlockAt(e.head).to,-1));function Ig(n,e,t){let i=!1,r=$i(n.selection,s=>{let o=ii(n,s.head,-1)||ii(n,s.head,1)||s.head>0&&ii(n,s.head-1,1)||s.headIg(n,e);function We(n,e,t){let i=$i(n.state.selection,r=>{r.undirectional&&r.head>=r.anchor!=e&&(r=y.range(r.head,r.anchor));let s=t(r);return y.range(r.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(Ne(n.state,i)),!0)}function Bf(n,e){return We(n,e,t=>n.moveByChar(t,e))}const qf=n=>Bf(n,!Oe(n)),Df=n=>Bf(n,Oe(n));function If(n,e){return We(n,e,t=>n.moveByGroup(t,e))}const Gg=n=>If(n,!Oe(n)),Ug=n=>If(n,Oe(n)),Fg=n=>{let e=!Oe(n);return We(n,e,t=>Wr(n.state,t,e))},Hg=n=>{let e=Oe(n);return We(n,e,t=>Wr(n.state,t,e))};function Nf(n,e){return We(n,e,t=>n.moveVertically(t,e))}const Gf=n=>Nf(n,!1),Uf=n=>Nf(n,!0);function Ff(n,e){return We(n,e,t=>n.moveVertically(t,e,Wf(n).height))}const Ea=n=>Ff(n,!1),za=n=>Ff(n,!0),Kg=n=>We(n,!0,e=>At(n,e,!0)),Jg=n=>We(n,!1,e=>At(n,e,!1)),e0=n=>{let e=!Oe(n);return We(n,e,t=>At(n,t,e))},t0=n=>{let e=Oe(n);return We(n,e,t=>At(n,t,e))},i0=n=>We(n,!1,e=>y.cursor(n.lineBlockAt(e.head).from)),n0=n=>We(n,!0,e=>y.cursor(n.lineBlockAt(e.head).to)),_a=({state:n,dispatch:e})=>(e(Ne(n,{anchor:0})),!0),Wa=({state:n,dispatch:e})=>(e(Ne(n,{anchor:n.doc.length})),!0),Va=({state:n,dispatch:e})=>(e(Ne(n,{anchor:n.selection.main.anchor,head:0})),!0),Ba=({state:n,dispatch:e})=>(e(Ne(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),r0=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),s0=({state:n,dispatch:e})=>{let t=Vr(n).map(({from:i,to:r})=>y.undirectionalRange(i,Math.min(r+1,n.doc.length)));return e(n.update({selection:y.create(t),userEvent:"select"})),!0},o0=({state:n,dispatch:e})=>{let t=$i(n.selection,i=>{let r=J(n),s=r.resolveStack(i.from,1);if(i.empty){let o=r.resolveStack(i.from,-1);o.node.from>=s.node.from&&o.node.to<=s.node.to&&(s=o)}for(let o=s;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return y.undirectionalRange(l.from,l.to)}return i});return t.eq(n.selection)?!1:(e(Ne(n,t)),!0)};function Hf(n,e){let{state:t}=n,i=t.selection,r=t.selection.ranges.slice();for(let s of t.selection.ranges){let o=t.doc.lineAt(s.head);if(e?o.to0)for(let l=s;;){let a=n.moveVertically(l,e);if(a.heado.to){r.some(h=>h.head==a.head)||r.push(a);break}else{if(a.head==l.head)break;l=a}}}return r.length==i.ranges.length?!1:(n.dispatch(Ne(t,y.create(r,r.length-1))),!0)}const l0=n=>Hf(n,!1),a0=n=>Hf(n,!0),h0=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=y.create([t.main]):t.main.empty||(i=y.create([y.cursor(t.main.head)])),i?(e(Ne(n,i)),!0):!1};function yn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,r=i.changeByRange(s=>{let{from:o,to:l}=s;if(o==l){let a=e(s);ao&&(t="delete.forward",a=Vn(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=Vn(n,o,!1),l=Vn(n,l,!0);return o==l?{range:s}:{changes:{from:o,to:l},range:y.cursor(o,or(n)))i.between(e,e,(r,s)=>{re&&(e=t?s:r)});return e}const Kf=(n,e,t)=>yn(n,i=>{let r=i.from,{state:s}=n,o=s.doc.lineAt(r),l,a;if(t&&!e&&r>o.from&&rKf(n,!1,!0),Jf=n=>Kf(n,!0,!1),eu=(n,e)=>yn(n,t=>{let i=t.head,{state:r}=n,s=r.doc.lineAt(i),o=r.charCategorizer(i);for(let l=null;;){if(i==(e?s.to:s.from)){i==t.head&&s.number!=(e?r.doc.lines:1)&&(i+=e?1:-1);break}let a=fe(s.text,i-s.from,e)+s.from,h=s.text.slice(Math.min(i,a)-s.from,Math.max(i,a)-s.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t.head)&&(l=c),i=a}return i}),tu=n=>eu(n,!1),c0=n=>eu(n,!0),f0=n=>yn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headyn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),O0=n=>yn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:_.of(["",""])},range:y.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},p0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let r=i.from,s=n.doc.lineAt(r),o=r==s.from?r-1:fe(s.text,r-s.from,!1)+s.from,l=r==s.to?r+1:fe(s.text,r-s.from,!0)+s.from;return{changes:{from:o,to:l,insert:n.doc.slice(r,l).append(n.doc.slice(o,r))},range:y.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Vr(n){let e=[],t=-1;for(let i of n.selection.ranges){let r=n.doc.lineAt(i.from),s=n.doc.lineAt(i.to);if(!i.empty&&i.to==s.from&&(s=n.doc.lineAt(i.to-1)),t>=r.number){let o=e[e.length-1];o.to=s.to,o.ranges.push(i)}else e.push({from:r.from,to:s.to,ranges:[i]});t=s.number+1}return e}function iu(n,e,t){if(n.readOnly)return!1;let i=[],r=[];for(let s of Vr(n)){if(t?s.to==n.doc.length:s.from==0)continue;let o=n.doc.lineAt(t?s.to+1:s.from-1),l=o.length+1;if(t){i.push({from:s.to,to:o.to},{from:s.from,insert:o.text+n.lineBreak});for(let a of s.ranges)r.push(y.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:s.from},{from:s.to,insert:n.lineBreak+o.text});for(let a of s.ranges)r.push(y.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:y.create(r,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const m0=({state:n,dispatch:e})=>iu(n,e,!1),g0=({state:n,dispatch:e})=>iu(n,e,!0);function nu(n,e,t){if(n.readOnly)return!1;let i=[];for(let s of Vr(n))t?i.push({from:s.from,insert:n.doc.slice(s.from,s.to)+n.lineBreak}):i.push({from:s.to,insert:n.lineBreak+n.doc.slice(s.from,s.to)});let r=n.changes(i);return e(n.update({changes:r,selection:n.selection.map(r,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const S0=({state:n,dispatch:e})=>nu(n,e,!1),b0=({state:n,dispatch:e})=>nu(n,e,!0),Q0=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Vr(e).map(({from:r,to:s})=>(r>0?r--:s{let s;if(n.lineWrapping){let o=n.lineBlockAt(r.head),l=n.coordsAtPos(r.head,r.assoc||1);l&&(s=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(r,!0,s)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function y0(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=J(n).resolveInner(e),i=t.childBefore(e),r=t.childAfter(e),s;return i&&r&&i.to<=e&&r.from>=e&&(s=i.type.prop(R.closedBy))&&s.indexOf(r.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(r.from).from&&!/\S/.test(n.sliceDoc(i.to,r.from))?{from:i.to,to:r.from}:null}const qa=ru(!1),x0=ru(!0);function ru(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(r=>{let{from:s,to:o}=r,l=e.doc.lineAt(s),a=!n&&s==o&&y0(e,s);n&&(s=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Yr(e,{simulateBreak:s,simulateDoubleBreak:!!a}),c=Of(h,s);for(c==null&&(c=St(/^\s*/.exec(e.doc.lineAt(s).text)[0],e.tabSize));ol.from&&s{let r=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,r,i),t=l.number),o=l.to+1}let s=n.changes(r);return{changes:r,range:y.range(s.mapPos(i.anchor,1),s.mapPos(i.head,1))}})}const k0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Yr(n,{overrideIndentation:s=>{let o=t[s];return o??-1}}),r=il(n,(s,o,l)=>{let a=Of(i,s.from);if(a==null)return;/\S/.test(s.text)||(a=0);let h=/^\s*/.exec(s.text)[0],c=Sr(n,a);(h!=c||l.fromn.readOnly?!1:(e(n.update(il(n,(t,i)=>{i.push({from:t.from,insert:n.facet(gn)})}),{userEvent:"input.indent"})),!0),ou=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(il(n,(t,i)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let s=St(r,n.tabSize),o=0,l=Sr(n,Math.max(0,s-gr(n)));for(;o(n.setTabFocusMode(),!0),$0=[{key:"Ctrl-b",run:jf,shift:qf,preventDefault:!0},{key:"Ctrl-f",run:Lf,shift:Df},{key:"Ctrl-p",run:zf,shift:Gf},{key:"Ctrl-n",run:_f,shift:Uf},{key:"Ctrl-a",run:qg,shift:i0},{key:"Ctrl-e",run:Dg,shift:n0},{key:"Ctrl-d",run:Jf},{key:"Ctrl-h",run:Qo},{key:"Ctrl-k",run:f0},{key:"Ctrl-Alt-h",run:tu},{key:"Ctrl-o",run:d0},{key:"Ctrl-t",run:p0},{key:"Ctrl-v",run:bo}],P0=[{key:"ArrowLeft",run:jf,shift:qf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:jg,shift:Gg,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Vg,shift:e0,preventDefault:!0},{key:"ArrowRight",run:Lf,shift:Df,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Lg,shift:Ug,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Bg,shift:t0,preventDefault:!0},{key:"ArrowUp",run:zf,shift:Gf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:_a,shift:Va},{mac:"Ctrl-ArrowUp",run:Ya,shift:Ea},{key:"ArrowDown",run:_f,shift:Uf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Wa,shift:Ba},{mac:"Ctrl-ArrowDown",run:bo,shift:za},{key:"PageUp",run:Ya,shift:Ea},{key:"PageDown",run:bo,shift:za},{key:"Home",run:Wg,shift:Jg,preventDefault:!0},{key:"Mod-Home",run:_a,shift:Va},{key:"End",run:_g,shift:Kg,preventDefault:!0},{key:"Mod-End",run:Wa,shift:Ba},{key:"Enter",run:qa,shift:qa},{key:"Mod-a",run:r0},{key:"Backspace",run:Qo,shift:Qo,preventDefault:!0},{key:"Delete",run:Jf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:tu,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:c0,preventDefault:!0},{mac:"Mod-Backspace",run:u0,preventDefault:!0},{mac:"Mod-Delete",run:O0,preventDefault:!0}].concat($0.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),v0=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Eg,shift:Fg},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:zg,shift:Hg},{key:"Alt-ArrowUp",run:m0},{key:"Shift-Alt-ArrowUp",run:S0},{key:"Alt-ArrowDown",run:g0},{key:"Shift-Alt-ArrowDown",run:b0},{key:"Mod-Alt-ArrowUp",run:l0},{key:"Mod-Alt-ArrowDown",run:a0},{key:"Escape",run:h0},{key:"Mod-Enter",run:x0},{key:"Alt-l",mac:"Ctrl-l",run:s0},{key:"Mod-i",run:o0,preventDefault:!0},{key:"Mod-[",run:ou},{key:"Mod-]",run:su},{key:"Mod-Alt-\\",run:k0},{key:"Shift-Mod-k",run:Q0},{key:"Shift-Mod-\\",run:Ng},{key:"Mod-/",run:mg},{key:"Alt-A",mac:"Ctrl-A",run:Sg},{key:"Ctrl-m",mac:"Shift-Alt-m",run:w0}].concat(P0),T0={key:"Tab",run:su,shift:ou};class nl{constructor(e,t,i,r){this.state=e,this.pos=t,this.explicit=i,this.view=r,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=J(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),r=t.text.slice(i-t.from,this.pos-t.from),s=r.search(au(e,!1));return s<0?null:{from:i+s,to:this.pos,text:r.slice(s)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Da(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function C0(n){let e=Object.create(null),t=Object.create(null);for(let{label:r}of n){e[r[0]]=!0;for(let s=1;stypeof r=="string"?{label:r}:r),[t,i]=e.every(r=>/^\w+$/.test(r.label))?[/\w*$/,/\w+$/]:C0(e);return r=>{let s=r.matchBefore(i);return s||r.explicit?{from:s?s.from:r.pos,options:e,validFor:t}:null}}function Z0(n,e){return t=>{for(let i=J(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}class Ia{constructor(e,t,i,r){this.completion=e,this.source=t,this.match=i,this.score=r}}function Wt(n){return n.selection.main.from}function au(n,e){var t;let{source:i}=n,r=e&&i[0]!="^",s=i[i.length-1]!="$";return!r&&!s?n:new RegExp(`${r?"^":""}(?:${i})${s?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const rl=Ie.define();function X0(n,e,t,i){let{main:r}=n.selection,s=t-r.from,o=i-r.from;return{...n.changeByRange(l=>{if(l!=r&&t!=i&&n.sliceDoc(l.from+s,l.from+o)!=n.sliceDoc(t,i))return{range:l};let a=n.toText(e);return{changes:{from:l.from+s,to:i==r.from?l.to:l.from+o,insert:a},range:y.cursor(l.from+s+a.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Na=new WeakMap;function A0(n){if(!Array.isArray(n))return n;let e=Na.get(n);return e||Na.set(n,e=lu(n)),e}const Qr=V.define(),sn=V.define();class R0{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&k<=57||k>=97&&k<=122?2:k>=65&&k<=90?1:0:(v=IO(k))!=v.toLowerCase()?1:v!=v.toUpperCase()?2:0;(!b||T==1&&g||w==0&&T!=0)&&(t[f]==k||i[f]==k&&(u=!0)?o[f++]=b:o.length&&(S=!1)),w=T,b+=Ft(k)}return f==a&&o[0]==0&&S?this.result(-100+(u?-200:0),o,e):O==a&&d==0?this.ret(-200-e.length+(p==e.length?0:-100),[0,p]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):O==a?this.ret(-900-e.length,[d,p]):f==a?this.result(-100+(u?-200:0)+-700+(S?0:-1100),o,e):t.length==2?null:this.result((r[0]?-700:0)+-200+-1100,r,e)}result(e,t,i){let r=[],s=0;for(let o of t){let l=o+(this.astral?Ft(jt(i,o)):1);s&&r[s-1]==o?r[s-1]=l:(r[s++]=o,r[s++]=l)}return this.ret(e-i.length,r)}}class M0{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:j0,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Ga(e(i),t(i)),optionClass:(e,t)=>i=>Ga(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Ga(n,e){return n?e?n+" "+e:n:e}function j0(n,e,t,i,r,s){let o=n.textDirection==K.RTL,l=o,a=!1,h="top",c,f,u=e.left-r.left,O=r.right-e.right,d=i.right-i.left,p=i.bottom-i.top;if(l&&u=p||b>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/s.offsetHeight,S=(e.right-e.left)/s.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/S}px`,class:"cm-completionInfo-"+(a?o?"left-narrow":"right-narrow":l?"left":"right")}}const sl=V.define();function L0(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(r=>"cm-completionIcon-"+r)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,r,s){let o=document.createElement("span");o.className="cm-completionLabel";let l=t.displayLabel||t.label,a=0;for(let h=0;ha&&o.appendChild(document.createTextNode(l.slice(a,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(l.slice(c,f))),u.className="cm-completionMatchedText",a=f}return at.position-i.position).map(t=>t.render)}function ps(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let r=Math.floor(e/t);return{from:r*t,to:(r+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}class Y0{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:a=>this.placeInfo(a),key:this},this.space=null,this.currentClass="";let r=e.state.field(t),{options:s,selected:o}=r.open,l=e.state.facet(le);this.optionContent=L0(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=ps(s.length,o,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",a=>{let{options:h}=e.state.field(t).open;for(let c=a.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;c!=null&&(e.dispatch({effects:sl.of(c)}),a.preventDefault())}}),this.dom.addEventListener("focusout",a=>{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(le).closeOnBlur&&a.relatedTarget!=e.contentDOM&&e.dispatch({effects:sn.of(null)})}),this.showOptions(s,r.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),r=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=r){let{options:s,selected:o,disabled:l}=i.open;(!r.open||r.open.options!=s)&&(this.range=ps(s.length,o,e.state.facet(le).maxRenderedOptions),this.showOptions(s,i.id)),this.updateSel(),l!=((t=r.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected=this.range.to)&&(this.range=ps(t.options.length,t.selected,this.view.state.facet(le).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:r}=t.options[t.selected],{info:s}=r;if(!s)return;let o=typeof s=="string"?document.createTextNode(s):s(r);if(!o)return;"then"in o?o.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,r)}).catch(l=>Ae(this.view.state,l,"completion info")):(this.addInfoPane(o,r),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:r,destroy:s}=e;i.appendChild(r),this.infoDestroy=s||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,r=this.range.from;i;i=i.nextSibling,r++)i.nodeName!="LI"||!i.id?r--:r==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&z0(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),r=e.getBoundingClientRect(),s=this.space;if(!s){let o=this.dom.ownerDocument.documentElement;s={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return r.top>Math.min(s.bottom,t.bottom)-10||r.bottom{o.target==r&&o.preventDefault()});let s=null;for(let o=i.from;oi.from||i.from==0))if(s=u,typeof h!="string"&&h.header)r.appendChild(h.header(h));else{let O=r.appendChild(document.createElement("completion-section"));O.textContent=u}}const c=r.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(l);f&&(c.className=f);for(let u of this.optionContent){let O=u(l,this.view.state,this.view,a);O&&c.appendChild(O)}}return i.from&&r.classList.add("cm-completionListIncompleteTop"),i.tonew Y0(t,n,e)}function z0(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),r=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/r)}function Ua(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function _0(n,e){let t=[],i=null,r=null,s=c=>{t.push(c);let{section:f}=c.completion;if(f){i||(i=[]);let u=typeof f=="string"?f:f.name;i.some(O=>O.name==u)||i.push(typeof f=="string"?{name:u}:f)}},o=e.facet(le);for(let c of n)if(c.hasResult()){let f=c.result.getMatch;if(c.result.filter===!1)for(let u of c.result.options)s(new Ia(u,c.source,f?f(u):[],1e9-t.length));else{let u=e.sliceDoc(c.from,c.to),O,d=o.filterStrict?new M0(u):new R0(u);for(let p of c.result.options)if(O=d.match(p.label)){let g=p.displayLabel?f?f(p,O.matched):[]:O.matched,S=O.score+(p.boost||0);if(s(new Ia(p,c.source,g,S)),typeof p.section=="object"&&p.section.rank==="dynamic"){let{name:b}=p.section;r||(r=Object.create(null)),r[b]=Math.max(S,r[b]||-1e9)}}}}if(i){let c=Object.create(null),f=0,u=(O,d)=>(O.rank==="dynamic"&&d.rank==="dynamic"?r[d.name]-r[O.name]:0)||(typeof O.rank=="number"?O.rank:1e9)-(typeof d.rank=="number"?d.rank:1e9)||(O.nameu.score-f.score||h(f.completion,u.completion))){let f=c.completion;!a||a.label!=f.label||a.detail!=f.detail||a.type!=null&&f.type!=null&&a.type!=f.type||a.apply!=f.apply||a.boost!=f.boost?l.push(c):Ua(c.completion)>Ua(a)&&(l[l.length-1]=c),a=c.completion}return l}class ni{constructor(e,t,i,r,s,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=r,this.selected=s,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new ni(this.options,Fa(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,r,s,o){if(r&&!o&&e.some(h=>h.isPending))return r.setDisabled();let l=_0(e,t);if(!l.length)return r&&e.some(h=>h.isPending)?r.setDisabled():null;let a=t.facet(le).selectOnOpen?0:-1;if(r&&r.selected!=a&&r.selected!=-1){let h=r.options[r.selected].completion;for(let c=0;cc.hasResult()?Math.min(h,c.from):h,1e8),create:I0,above:s.aboveCursor},r?r.timestamp:Date.now(),a,!1)}map(e){return new ni(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new ni(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class yr{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new yr(q0,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(le),s=(i.override||t.languageDataAt("autocomplete",Wt(t)).map(A0)).map(a=>(this.active.find(c=>c.source==a)||new ze(a,this.active.some(c=>c.state!=0)?1:0)).update(e,i));s.length==this.active.length&&s.every((a,h)=>a==this.active[h])&&(s=this.active);let o=this.open,l=e.effects.some(a=>a.is(ol));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||s.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!W0(s,this.active)||l?o=ni.build(s,t,this.id,o,i,l):o&&o.disabled&&!s.some(a=>a.isPending)&&(o=null),!o&&s.every(a=>!a.isPending)&&s.some(a=>a.hasResult())&&(s=s.map(a=>a.hasResult()?new ze(a.source,0):a));for(let a of e.effects)a.is(sl)&&(o=o&&o.setSelected(a.value,this.id));return s==this.active&&o==this.open?this:new yr(s,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?V0:B0}}function W0(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}const q0=[];function hu(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(rl);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}class ze{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=hu(e,t),r=this;(i&8||i&16&&this.touches(e))&&(r=new ze(r.source,0)),i&4&&r.state==0&&(r=new ze(this.source,1)),r=r.updateFor(e,i);for(let s of e.effects)if(s.is(Qr))r=new ze(r.source,1,s.value);else if(s.is(sn))r=new ze(r.source,0);else if(s.is(ol))for(let o of s.value)o.source==r.source&&(r=o);return r}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(Wt(e.state))}}class ci extends ze{constructor(e,t,i,r,s,o){super(e,3,t),this.limit=i,this.result=r,this.from=s,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let r=this.result;r.map&&!e.changes.empty&&(r=r.map(r,e.changes));let s=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),l=Wt(e.state);if(l>o||!r||t&2&&(Wt(e.startState)==this.from||lt.map(e))}}),ke=_e.define({create(){return yr.start()},update(n,e){return n.update(e)},provide:n=>[ef.from(n,e=>e.tooltip),C.contentAttributes.from(n,e=>e.attrs)]});function ll(n,e){const t=e.completion.apply||e.completion.label;let i=n.state.field(ke).active.find(r=>r.source==e.source);return i instanceof ci?(typeof t=="string"?n.dispatch({...X0(n.state,t,i.from,i.to),annotations:rl.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}const I0=E0(ke,ll);function Bn(n,e="option"){return t=>{let i=t.state.field(ke,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+r*(n?1:-1):n?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:sl.of(l)}),!0}}const N0=n=>{let e=n.state.field(ke,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(ke,!1)?(n.dispatch({effects:Qr.of(!0)}),!0):!1,G0=n=>{let e=n.state.field(ke,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:sn.of(null)}),!0)};class U0{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const F0=50,H0=1e3,K0=Se.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(ke).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(ke),t=n.state.facet(le);if(!n.selectionSet&&!n.docChanged&&n.startState.field(ke)==e)return;let i=n.transactions.some(s=>{let o=hu(s,t);return o&8||(s.selection||s.docChanged)&&!(o&3)});for(let s=0;sF0&&Date.now()-o.time>H0){for(let l of o.context.abortListeners)try{l()}catch(a){Ae(this.view.state,a)}o.context.abortListeners=null,this.running.splice(s--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(s=>s.effects.some(o=>o.is(Qr)))&&(this.pendingStart=!0);let r=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(s=>s.isPending&&!this.running.some(o=>o.active.source==s.source))?setTimeout(()=>this.startUpdate(),r):-1,this.composing!=0)for(let s of n.transactions)s.isUserEvent("input.type")?this.composing=2:this.composing==2&&s.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(ke);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(le).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=Wt(e),i=new nl(e,t,n.explicit,this.view),r=new U0(n,i);this.running.push(r),Promise.resolve(n.source(i)).then(s=>{r.context.aborted||(r.done=s||null,this.scheduleAccept())},s=>{this.view.dispatch({effects:sn.of(null)}),Ae(this.view.state,s)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(le).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(le),i=this.view.state.field(ke);for(let r=0;rl.source==s.active.source);if(o&&o.isPending)if(s.done==null){let l=new ze(s.active.source,0);for(let a of s.updates)l=l.update(a,t);l.isPending||e.push(l)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:ol.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(ke,!1);if(e&&e.tooltip&&this.view.state.facet(le).closeOnBlur){let t=e.open&&tf(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:sn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Qr.of(!1)}),20),this.composing=0}}}),J0=typeof navigator=="object"&&/Win/.test(navigator.platform),eS=Nt.highest(C.domEventHandlers({keydown(n,e){let t=e.state.field(ke,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(J0&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],r=t.active.find(o=>o.source==i.source),s=i.completion.commitCharacters||r.result.commitCharacters;return s&&s.indexOf(n.key)>-1&&ll(e,i),!1}})),cu=C.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class tS{constructor(e,t,i,r){this.field=e,this.line=t,this.from=i,this.to=r}}class al{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,me.TrackDel),i=e.mapPos(this.to,1,me.TrackDel);return t==null||i==null?null:new al(this.field,t,i)}}class hl{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],r=[t],s=e.doc.lineAt(t),o=/^\s*/.exec(s.text)[0];for(let a of this.lines){if(i.length){let h=o,c=/^\t*/.exec(a)[0].length;for(let f=0;fnew al(a.field,r[a.line]+a.from,r[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],r=[],s;for(let o of e.split(/\r\n?|\n/)){for(;s=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let l=s[1]?+s[1]:null,a=s[2]||s[3]||"",h=-1;l===0&&(l=1e9);let c=a.replace(/\\[{}]/g,f=>f[1]);for(let f=0;f=h&&u.field++}for(let f of r)if(f.line==i.length&&f.from>s.index){let u=s[2]?3+(s[1]||"").length:2;f.from-=u,f.to-=u}r.push(new tS(h,i.length,s.index,s.index+c.length)),o=o.slice(0,s.index)+a+o.slice(s.index+s[0].length)}o=o.replace(/\\([{}])/g,(l,a,h)=>{for(let c of r)c.line==i.length&&c.from>h&&(c.from--,c.to--);return a}),i.push(o)}return new hl(i,r)}}let iS=M.widget({widget:new class extends at{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),nS=M.mark({class:"cm-snippetField"});class Pi{constructor(e,t){this.ranges=e,this.active=t,this.deco=M.set(e.map(i=>(i.from==i.to?iS:nS).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let r=i.map(e);if(!r)return null;t.push(r)}return new Pi(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const xn=V.define({map(n,e){return n&&n.map(e)}}),rS=V.define(),on=_e.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(xn))return t.value;if(t.is(rS)&&n)return new Pi(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>C.decorations.from(n,e=>e?e.deco:M.none)});function cl(n,e){return y.create(n.filter(t=>t.field==e).map(t=>y.range(t.from,t.to)))}function sS(n){let e=hl.parse(n);return(t,i,r,s)=>{let{text:o,ranges:l}=e.instantiate(t.state,r),{main:a}=t.state.selection,h={changes:{from:r,to:s==a.from?a.to:s,insert:_.of(o)},scrollIntoView:!0,annotations:i?[rl.of(i),ne.userEvent.of("input.complete")]:void 0};if(l.length&&(h.selection=cl(l,0)),l.some(c=>c.field>0)){let c=new Pi(l,0),f=h.effects=[xn.of(c)];t.state.field(on,!1)===void 0&&f.push(V.appendConfig.of([on,cS,fS,cu]))}t.dispatch(t.state.update(h))}}function fu(n){return({state:e,dispatch:t})=>{let i=e.field(on,!1);if(!i||n<0&&i.active==0)return!1;let r=i.active+n,s=n>0&&!i.ranges.some(o=>o.field==r+n);return t(e.update({selection:cl(i.ranges,r),effects:xn.of(s?null:new Pi(i.ranges,r)),scrollIntoView:!0})),!0}}const oS=({state:n,dispatch:e})=>n.field(on,!1)?(e(n.update({effects:xn.of(null)})),!0):!1,lS=fu(1),aS=fu(-1),hS=[{key:"Tab",run:lS,shift:aS},{key:"Escape",run:oS}],Ha=Z.define({combine(n){return n.length?n[0]:hS}}),cS=Nt.highest(pn.compute([Ha],n=>n.facet(Ha)));function xe(n,e){return{...e,apply:sS(n)}}const fS=C.domEventHandlers({mousedown(n,e){let t=e.state.field(on,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let r=t.ranges.find(s=>s.from<=i&&s.to>=i);return!r||r.field==t.active?!1:(e.dispatch({selection:cl(t.ranges,r.field),effects:xn.of(t.ranges.some(s=>s.field>r.field)?new Pi(t.ranges,r.field):null),scrollIntoView:!0}),!0)}}),uu=new class extends vt{};uu.startSide=1;uu.endSide=-1;function uS(n={}){return[eS,ke,le.of(n),K0,OS,cu]}const Ou=[{key:"Ctrl-Space",run:qi},{mac:"Alt-`",run:qi},{mac:"Alt-i",run:qi},{key:"Escape",run:G0},{key:"ArrowDown",run:Bn(!0)},{key:"ArrowUp",run:Bn(!1)},{key:"PageDown",run:Bn(!0,"page")},{key:"PageUp",run:Bn(!1,"page")},{key:"Enter",run:N0}],OS=Nt.highest(pn.computeN([le],n=>n.facet(le).defaultKeymap?[Ou]:[]));class xr{static create(e,t,i,r,s){let o=r+(r<<8)+e+(t<<4)|0;return new xr(e,t,i,o,s,[],[])}constructor(e,t,i,r,s,o,l){this.type=e,this.value=t,this.from=i,this.hash=r,this.end=s,this.children=o,this.positions=l,this.hashProp=[[R.contextHash,r]]}addChild(e,t){e.prop(R.contextHash)!=this.hash&&(e=new B(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let i=this.children.length-1;return i>=0&&(t=Math.max(t,this.positions[i]+this.children[i].length+this.from)),new B(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(r,s,o)=>new B(se.none,r,s,o,this.hashProp)})}}var x;(function(n){n[n.Document=1]="Document",n[n.CodeBlock=2]="CodeBlock",n[n.FencedCode=3]="FencedCode",n[n.Blockquote=4]="Blockquote",n[n.HorizontalRule=5]="HorizontalRule",n[n.BulletList=6]="BulletList",n[n.OrderedList=7]="OrderedList",n[n.ListItem=8]="ListItem",n[n.ATXHeading1=9]="ATXHeading1",n[n.ATXHeading2=10]="ATXHeading2",n[n.ATXHeading3=11]="ATXHeading3",n[n.ATXHeading4=12]="ATXHeading4",n[n.ATXHeading5=13]="ATXHeading5",n[n.ATXHeading6=14]="ATXHeading6",n[n.SetextHeading1=15]="SetextHeading1",n[n.SetextHeading2=16]="SetextHeading2",n[n.HTMLBlock=17]="HTMLBlock",n[n.LinkReference=18]="LinkReference",n[n.Paragraph=19]="Paragraph",n[n.CommentBlock=20]="CommentBlock",n[n.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",n[n.Escape=22]="Escape",n[n.Entity=23]="Entity",n[n.HardBreak=24]="HardBreak",n[n.Emphasis=25]="Emphasis",n[n.StrongEmphasis=26]="StrongEmphasis",n[n.Link=27]="Link",n[n.Image=28]="Image",n[n.InlineCode=29]="InlineCode",n[n.HTMLTag=30]="HTMLTag",n[n.Comment=31]="Comment",n[n.ProcessingInstruction=32]="ProcessingInstruction",n[n.Autolink=33]="Autolink",n[n.HeaderMark=34]="HeaderMark",n[n.QuoteMark=35]="QuoteMark",n[n.ListMark=36]="ListMark",n[n.LinkMark=37]="LinkMark",n[n.EmphasisMark=38]="EmphasisMark",n[n.CodeMark=39]="CodeMark",n[n.CodeText=40]="CodeText",n[n.CodeInfo=41]="CodeInfo",n[n.LinkTitle=42]="LinkTitle",n[n.LinkLabel=43]="LinkLabel",n[n.URL=44]="URL"})(x||(x={}));class dS{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}}class pS{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return Di(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,i=0){for(let r=t;r=e.stack[t.depth+1].value+t.baseIndent)return!0;if(t.indent>=t.baseIndent+4)return!1;let i=(n.type==x.OrderedList?Ol:ul)(t,e,!1);return i>0&&(n.type!=x.BulletList||fl(t,e,!1)<0)&&t.text.charCodeAt(t.pos+i-1)==n.value}const du={[x.Blockquote](n,e,t){return t.next!=62?!1:(t.markers.push(z(x.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1)),t.moveBase(t.pos+(Ve(t.text.charCodeAt(t.pos+1))?2:1)),n.end=e.lineStart+t.text.length,!0)},[x.ListItem](n,e,t){return t.indent-1?!1:(t.moveBaseColumn(t.baseIndent+n.value),!0)},[x.OrderedList]:Ka,[x.BulletList]:Ka,[x.Document](){return!0}};function Ve(n){return n==32||n==9||n==10||n==13}function Di(n,e=0){for(;et&&Ve(n.charCodeAt(e-1));)e--;return e}function pu(n){if(n.next!=96&&n.next!=126)return-1;let e=n.pos+1;for(;e-1&&n.depth==e.stack.length&&e.parser.leafBlockParsers.indexOf(ku.SetextHeading)>-1||i<3?-1:1}function gu(n,e){for(let t=n.stack.length-1;t>=0;t--)if(n.stack[t].type==e)return!0;return!1}function ul(n,e,t){return(n.next==45||n.next==43||n.next==42)&&(n.pos==n.text.length-1||Ve(n.text.charCodeAt(n.pos+1)))&&(!t||gu(e,x.BulletList)||n.skipSpace(n.pos+2)=48&&r<=57;){i++;if(i==n.text.length)return-1;r=n.text.charCodeAt(i)}return i==n.pos||i>n.pos+9||r!=46&&r!=41||in.pos+1||n.next!=49)?-1:i+1-n.pos}function Su(n){if(n.next!=35)return-1;let e=n.pos+1;for(;e6?-1:t}function bu(n){if(n.next!=45&&n.next!=61||n.indent>=n.baseIndent+4)return-1;let e=n.pos+1;for(;e/,yu=/\?>/,xo=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*/,xu=/\?>/,ko=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*/i.exec(i);if(s)return n.append(z(x.Comment,t,t+1+s[0].length));let o=/^\?[^]*?\?>/.exec(i);if(o)return n.append(z(x.ProcessingInstruction,t,t+1+o[0].length));let l=/^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(i);return l?n.append(z(x.HTMLTag,t,t+1+l[0].length)):-1},Emphasis(n,e,t){if(e!=95&&e!=42)return-1;let i=t+1;for(;n.char(i)==e;)i++;let r=n.slice(t-1,t),s=n.slice(i,i+1),o=an.test(r),l=an.test(s),a=/\s|^$/.test(r),h=/\s|^$/.test(s),c=!h&&(!l||a||o),f=!a&&(!o||h||l),u=c&&(e==42||!f||o),O=f&&(e==42||!c||l);return n.append(new Ze(e==95?Tu:Cu,t,i,(u?1:0)|(O?2:0)))},HardBreak(n,e,t){if(e==92&&n.char(t+1)==10)return n.append(z(x.HardBreak,t,t+2));if(e==32){let i=t+1;for(;n.char(i)==32;)i++;if(n.char(i)==10&&i>=t+2)return n.append(z(x.HardBreak,t,i+1))}return-1},Link(n,e,t){return e==91?n.append(new Ze(Et,t,t+1,1)):-1},Image(n,e,t){return e==33&&n.char(t+1)==91?n.append(new Ze(kr,t,t+2,1)):-1},LinkEnd(n,e,t){if(e!=93)return-1;for(let i=n.parts.length-1;i>=0;i--){let r=n.parts[i];if(r instanceof Ze&&(r.type==Et||r.type==kr)){if(!r.side||n.skipSpace(r.to)==t&&!/[(\[]/.test(n.slice(t+1,t+2)))return n.parts[i]=null,-1;let s=n.takeContent(i),o=n.parts[i]=yS(n,s,r.type==Et?x.Link:x.Image,r.from,t+1);if(r.type==Et)for(let l=0;le?z(x.URL,e+t,s+t):s==n.length?null:!1}}function Xu(n,e,t){let i=n.charCodeAt(e);if(i!=39&&i!=34&&i!=40)return!1;let r=i==40?41:i;for(let s=e+1,o=!1;s=this.end?-1:this.text.charCodeAt(e-this.offset)}get end(){return this.offset+this.text.length}slice(e,t){return this.text.slice(e-this.offset,t-this.offset)}append(e){return this.parts.push(e),e.to}addDelimiter(e,t,i,r,s){return this.append(new Ze(e,t,i,(r?1:0)|(s?2:0)))}get hasOpenLink(){for(let e=this.parts.length-1;e>=0;e--){let t=this.parts[e];if(t instanceof Ze&&(t.type==Et||t.type==kr))return!0}return!1}addElement(e){return this.append(e)}resolveMarkers(e){for(let i=e;i=e;a--){let p=this.parts[a];if(p instanceof Ze&&p.side&1&&p.type==r.type&&!(s&&(r.side&1||p.side&2)&&(p.to-p.from+o)%3==0&&((p.to-p.from)%3||o%3))){l=p;break}}if(!l)continue;let h=r.type.resolve,c=[],f=l.from,u=r.to;if(s){let p=Math.min(2,l.to-l.from,o);f=l.to-p,u=r.from+p,h=p==1?"Emphasis":"StrongEmphasis"}l.type.mark&&c.push(this.elt(l.type.mark,f,l.to));for(let p=a+1;p=0;t--){let i=this.parts[t];if(i instanceof Ze&&i.type==e&&i.side&1)return t}return null}takeContent(e){let t=this.resolveMarkers(e);return this.parts.length=e,t}getDelimiterAt(e){let t=this.parts[e];return t instanceof Ze?t:null}skipSpace(e){return Di(this.text,e-this.offset)+this.offset}elt(e,t,i,r){return typeof e=="string"?z(this.parser.getNodeType(e),t,i,r):new vu(e,t)}}dl.linkStart=Et;dl.imageStart=kr;function wo(n,e){if(!e.length)return n;if(!n.length)return e;let t=n.slice(),i=0;for(let r of e){for(;i(e?e-1:0))return!1;if(this.fragmentEnd<0){let s=this.fragment.to;for(;s>0&&this.input.read(s-1,s)!=` -`;)s--;this.fragmentEnd=s?s-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(R.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),s=e.absoluteLineStart,o=s,l=e.block.children.length,a=o,h=l;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=Ru(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let f=new B(e.parser.nodeSet.types[x.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(f,t.tree),e.addNode(f,c)}if(t.type.is("Block")&&(xS.indexOf(t.type.id)<0?(o=t.to-i,l=e.block.children.length):(o=a,l=h),a=t.to-i,h=e.block.children.length),!t.nextSibling())break}for(;e.block.children.length>l;)e.block.children.pop(),e.block.positions.pop();return o-s}};function Ru(n,e){let t=n;for(let i=1;iqn[n]),Object.keys(qn).map(n=>ku[n]),Object.keys(qn),SS,du,Object.keys(gs).map(n=>gs[n]),Object.keys(gs),[]);function PS(n,e,t){let i=[];for(let r=n.firstChild,s=e;;r=r.nextSibling){let o=r?r.from:t;if(o>s&&i.push({from:s,to:o}),!r)break;s=r.to}return i}function vS(n){let{codeParser:e,htmlParser:t}=n;return{wrap:hf((r,s)=>{let o=r.type.id;if(e&&(o==x.CodeBlock||o==x.FencedCode)){let l="";if(o==x.FencedCode){let h=r.node.getChild(x.CodeInfo);h&&(l=s.read(h.from,h.to))}let a=e(l);if(a)return{parser:a,overlay:h=>h.type.id==x.CodeText,bracketed:o==x.FencedCode}}else if(t&&(o==x.HTMLBlock||o==x.HTMLTag||o==x.CommentBlock))return{parser:t,overlay:PS(r.node,r.from,r.to)};return null})}}const TS={resolve:"Strikethrough",mark:"StrikethroughMark"},CS={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":m.strikethrough}},{name:"StrikethroughMark",style:m.processingInstruction}],parseInline:[{name:"Strikethrough",parse(n,e,t){if(e!=126||n.char(t+1)!=126||n.char(t+2)==126)return-1;let i=n.slice(t-1,t),r=n.slice(t+2,t+3),s=/\s|^$/.test(i),o=/\s|^$/.test(r),l=an.test(i),a=an.test(r);return n.addDelimiter(TS,t,t+2,!o&&(!a||s||l),!s&&(!l||o||a))},after:"Emphasis"}]};function Ii(n,e,t=0,i,r=0){let s=0,o=!0,l=-1,a=-1,h=!1,c=()=>{i.push(n.elt("TableCell",r+l,r+a,n.parser.parseInline(e.slice(l,a),r+l)))};for(let f=t;f-1)&&s++,o=!1,i&&(l>-1&&c(),i.push(n.elt("TableDelimiter",f+r,f+r+1))),l=a=-1):(h||u!=32&&u!=9)&&(l<0&&(l=f),a=f+1),h=!h&&u==92}return l>-1&&(s++,i&&c()),s}function ih(n,e){for(let t=e;t\s]*\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/;class nh{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&Mu.test(r=t.text.slice(t.pos))){let s=[];Ii(e,i.content,0,s,i.start)==Ii(e,r,0)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,s),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];Ii(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}}const ZS={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":m.heading}},"TableRow",{name:"TableCell",style:m.content},{name:"TableDelimiter",style:m.processingInstruction}],parseBlock:[{name:"Table",leaf(n,e){return ih(e.content,0)?new nh:null},endLeaf(n,e,t){if(t.parsers.some(r=>r instanceof nh)||!ih(e.text,e.basePos))return!1;let i=n.peekLine();return Mu.test(i)&&Ii(n,e.text,e.basePos)==Ii(n,i,e.basePos)},before:"SetextHeading"}]};class XS{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}}const AS={defineNodes:[{name:"Task",block:!0,style:m.list},{name:"TaskMarker",style:m.atom}],parseBlock:[{name:"TaskList",leaf(n,e){return/^\[[ xX]\][ \t]/.test(e.content)&&n.parentType().name=="ListItem"?new XS:null},after:"SetextHeading"}]},rh=/(www\.)|(https?:\/\/)|([\w.+-]{1,100}@)|(mailto:|xmpp:)/gy,sh=/[\w-]+(\.[\w-]+)+(:\d+)?(\/[^\s<]*)?/gy,RS=/[\w-]+\.[\w-]+($|[/:])/,oh=/[\w.+-]+@[\w-]+(\.[\w.-]+)+/gy,lh=/\/[a-zA-Z\d@.]+/gy;function ah(n,e,t,i){let r=0;for(let s=e;s-1)return-1;let i=e+t[0].length;for(;;){let r=n[i-1],s;if(/[?!.,:*_~]/.test(r)||r==")"&&ah(n,e,i,")")>ah(n,e,i,"("))i--;else if(r==";"&&(s=/&(?:#\d+|#x[a-f\d]+|\w+);$/.exec(n.slice(e,i))))i=e+s.index;else break}return i}function hh(n,e){oh.lastIndex=e;let t=oh.exec(n);if(!t)return-1;let i=t[0][t[0].length-1];return i=="_"||i=="-"?-1:e+t[0].length-(i=="."?1:0)}const jS={parseInline:[{name:"Autolink",parse(n,e,t){let i=t-n.offset;if(i&&/\w/.test(n.text[i-1]))return-1;rh.lastIndex=i;let r=rh.exec(n.text),s=-1;if(!r)return-1;if(r[1]||r[2]){if(s=MS(n.text,i+r[0].length),s>-1&&n.hasOpenLink){let o=/([^\[\]]|\[[^\]]*\])*/.exec(n.text.slice(i,s));s=i+o[0].length}}else r[3]?s=hh(n.text,i):(s=hh(n.text,i+r[0].length),s>-1&&r[0]=="xmpp:"&&(lh.lastIndex=s,r=lh.exec(n.text),r&&(s=r.index+r[0].length)));return s<0?-1:(n.addElement(n.elt("URL",t,s+n.offset)),s+n.offset)}}]},LS=[ZS,AS,CS,jS];function ju(n,e,t){return(i,r,s)=>{if(r!=n||i.char(s+1)==n)return-1;let o=[i.elt(t,s,s+1)];for(let l=s+1;lt%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let r=e.parser.context;return new wr(e,[],t,i,i,0,[],0,r?new fh(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,r=e&65535,{parser:s}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[r])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(r,h)}storeNode(e,t,i,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!s||this.pos==i)this.buffer.push(e,t,i,r);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=r}}shift(e,t,i,r){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let s=e,{parser:o}=this.p;this.pos=r;let l=o.stateFlag(s,1);!l&&(r>i||t<=o.maxNode)&&(this.reducePos=r),this.pushState(s,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,r,4)}else this.pos=r,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,r,4)}apply(e,t,i,r){e&65536?this.reduce(e):this.shift(e,t,i,r)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(i,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new wr(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new _S(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let r=[];for(let s=0,o;sa&1&&l==o)||r.push(t[s],o)}t=r}let i=[];for(let r=0;r>19,r=t&65535,s=this.stack.length-i*3;if(s<0||e.getGoto(this.stack[s],r,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(r,s)=>{if(!t.includes(r))return t.push(r),e.allActions(r,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-s;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,s+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}}class fh{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class _S{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class $r{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new $r(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new $r(this.stack,this.pos,this.index)}}function Ei(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,r=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),s+=a,l)break;s*=46}t?t[r++]=s:t=new e(s)}return t}class Jn{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const uh=new Jn;class WS{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=uh,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,r=this.rangeIndex,s=this.pos+e;for(;si.to:s>=i.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-i.to,i=o}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,r;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),r=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),r}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=uh,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(i+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return i}}class fi{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;Lu(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}fi.prototype.contextual=fi.prototype.fallback=fi.prototype.extend=!1;class Pr{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?Ei(e):e}token(e,t){let i=e.pos,r=0;for(;;){let s=e.next<0,o=e.resolveOffset(1,1);if(Lu(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(s||r++,o==null)break;e.reset(o,e.token)}r&&(e.reset(i,e.token),e.acceptToken(this.elseToken,r))}}Pr.prototype.contextual=fi.prototype.fallback=fi.prototype.extend=!1;class Re{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function Lu(n,e,t,i,r,s){let o=0,l=1<0){let d=n[O];if(a.allows(d)&&(e.token.value==-1||e.token.value==d||VS(d,e.token.value,r,s))){e.acceptToken(d);break}}let c=e.next,f=0,u=n[o+2];if(e.next<0&&u>f&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;f>1,d=h+O+(O<<1),p=n[d],g=n[d+1]||65536;if(c=g)f=O+1;else{o=n[d+2],e.advance();continue e}}break}}function Oh(n,e,t){for(let i=e,r;(r=n[i])!=65535;i++)if(r==t)return i-e;return-1}function VS(n,e,t,i){let r=Oh(t,i,e);return r<0||Oh(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class BS{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?dh(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?dh(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(s instanceof B){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}}class qS{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Jn)}getActions(e){let t=0,i=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),f.value!=0)){let u=t;if(f.extended>-1&&(t=this.addActions(e,f.extended,f.end,t)),t=this.addActions(e,f.value,f.end,t),!c.extend&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new Jn,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Jn,{pos:i,p:r}=e;return t.start=i,t.end=Math.min(i+1,r.stream.end),t.value=i==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,i){let r=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(r,e),i),e.value>-1){let{parser:s}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,i,r){for(let s=0;se.bufferLength*4?new BS(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],r,s;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{r||(r=[],s=[]),r.push(l);let a=this.tokens.getMainToken(l);s.push(a.value,a.end)}}break}}if(!i.length){let o=r&&NS(r);if(o)return ve&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw ve&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,i);if(o)return ve&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let f=this.fragments.nodeAt(r);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?s.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(R.contextHash)||0)==c))return e.useNode(f,u),ve&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(f.type.id)})`),!0;if(!(f instanceof B)||f.children.length==0||f.positions[0]>0)break;let O=f.children[0];if(O instanceof B&&f.positions[0]==0)f=O;else break}}let l=s.stateSlot(e.state,4);if(l>0)return e.reduce(l),ve&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hr?t.push(d):i.push(d)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return ph(e,t),!0}}runRecovery(e,t,i){let r=null,s=!1;for(let o=0;o ":"";if(l.deadEnd&&(s||(s=!0,l.restart(),ve&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let O=0;O<10&&f.forceReduce()&&(ve&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));O++)ve&&(u=this.stackID(f)+" -> ");for(let O of l.recoverByInsert(a))ve&&console.log(c+this.stackID(O)+" (via recover-insert)"),this.advanceFully(O,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),ve&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),ph(l,i)):(!r||r.scoren;class Yu{constructor(e){this.start=e.start,this.shift=e.shift||bs,this.reduce=e.reduce||bs,this.reuse=e.reuse||bs,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Qi extends Uo{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;le.topRules[l][1]),r=[];for(let l=0;l=0)s(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)s(l[h++],a,f);h++}}}this.nodeSet=new mn(t.map((l,a)=>se.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:r[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=rf;let o=Ei(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new fi(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let r=new DS(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}getGoto(e,t,i=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],l=o&1,a=r[s++];if(l&&i)return a;for(let h=s+(o>>1);s0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),r=i?t(i):void 0;for(let s=this.stateSlot(e,1);r==null;s+=3){if(this.data[s]==65535)if(this.data[s+1]==1)s=Ot(this.data,s+2);else break;r=t(Ot(this.data,s+1))}return r}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ot(this.data,i+2);else break;if((this.data[i+2]&1)==0){let r=this.data[i+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[i],r)}}return t}configure(e){let t=Object.assign(Object.create(Qi.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let r=e.tokenizers.find(s=>s.from==i);return r?r.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,r)=>{let s=e.specializers.find(l=>l.from==i.external);if(!s)return i;let o=Object.assign(Object.assign({},i),{external:s.to});return t.specializers[r]=mh(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(i[o]=!0)}let r=null;for(let s=0;si)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const GS=55,US=1,FS=56,HS=2,KS=57,JS=3,gh=4,e1=5,pl=6,Eu=7,zu=8,_u=9,Wu=10,t1=11,i1=12,n1=13,Qs=58,r1=14,s1=15,Sh=59,Vu=21,o1=23,Bu=24,l1=25,$o=27,qu=28,a1=29,h1=32,c1=35,f1=37,u1=38,O1=0,d1=1,p1={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},m1={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},bh={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function g1(n){return n==45||n==46||n==58||n>=65&&n<=90||n==95||n>=97&&n<=122||n>=161}let Qh=null,yh=null,xh=0;function Po(n,e){let t=n.pos+e;if(xh==t&&yh==n)return Qh;let i=n.peek(e),r="";for(;g1(i);)r+=String.fromCharCode(i),i=n.peek(++e);return yh=n,xh=t,Qh=r?r.toLowerCase():i==S1||i==b1?void 0:null}const Du=60,vr=62,ml=47,S1=63,b1=33,Q1=45;function kh(n,e){this.name=n,this.parent=e}const y1=[pl,Wu,Eu,zu,_u],x1=new Yu({start:null,shift(n,e,t,i){return y1.indexOf(e)>-1?new kh(Po(i,1)||"",n):n},reduce(n,e){return e==Vu&&n?n.parent:n},reuse(n,e,t,i){let r=e.type.id;return r==pl||r==f1?new kh(Po(i,1)||"",n):n},strict:!1}),k1=new Re((n,e)=>{if(n.next!=Du){n.next<0&&e.context&&n.acceptToken(Qs);return}n.advance();let t=n.next==ml;t&&n.advance();let i=Po(n,0);if(i===void 0)return;if(!i)return n.acceptToken(t?s1:r1);let r=e.context?e.context.name:null;if(t){if(i==r)return n.acceptToken(t1);if(r&&m1[r])return n.acceptToken(Qs,-2);if(e.dialectEnabled(O1))return n.acceptToken(i1);for(let s=e.context;s;s=s.parent)if(s.name==i)return;n.acceptToken(n1)}else{if(i=="script")return n.acceptToken(Eu);if(i=="style")return n.acceptToken(zu);if(i=="textarea")return n.acceptToken(_u);if(p1.hasOwnProperty(i))return n.acceptToken(Wu);r&&bh[r]&&bh[r][i]?n.acceptToken(Qs,-1):n.acceptToken(pl)}},{contextual:!0}),w1=new Re(n=>{for(let e=0,t=0;;t++){if(n.next<0){t&&n.acceptToken(Sh);break}if(n.next==Q1)e++;else if(n.next==vr&&e>=2){t>=3&&n.acceptToken(Sh,-2);break}else e=0;n.advance()}});function $1(n){for(;n;n=n.parent)if(n.name=="svg"||n.name=="math")return!0;return!1}const P1=new Re((n,e)=>{if(n.next==ml&&n.peek(1)==vr){let t=e.dialectEnabled(d1)||$1(e.context);n.acceptToken(t?e1:gh,2)}else n.next==vr&&n.acceptToken(gh,1)});function gl(n,e,t){let i=2+n.length;return new Re(r=>{for(let s=0,o=0,l=0;;l++){if(r.next<0){l&&r.acceptToken(e);break}if(s==0&&r.next==Du||s==1&&r.next==ml||s>=2&&so?r.acceptToken(e,-o):r.acceptToken(t,-(o-2));break}else if((r.next==10||r.next==13)&&l){r.acceptToken(e,1);break}else s=o=0;r.advance()}})}const v1=gl("script",GS,US),T1=gl("style",FS,HS),C1=gl("textarea",KS,JS),Z1=xi({"Text RawText IncompleteTag IncompleteCloseTag":m.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":m.angleBracket,TagName:m.tagName,"MismatchedCloseTag/TagName":[m.tagName,m.invalid],AttributeName:m.attributeName,"AttributeValue UnquotedAttributeValue":m.attributeValue,Is:m.definitionOperator,"EntityReference CharacterReference":m.character,Comment:m.blockComment,ProcessingInst:m.processingInstruction,DoctypeDecl:m.documentMeta}),X1=Qi.deserialize({version:14,states:",xOVO!rOOO!ZQ#tO'#CrO!`Q#tO'#C{O!eQ#tO'#DOO!jQ#tO'#DRO!oQ#tO'#DTO!tOaO'#CqO#PObO'#CqO#[OdO'#CqO$kO!rO'#CqOOO`'#Cq'#CqO$rO$fO'#DUO$zQ#tO'#DWO%PQ#tO'#DXOOO`'#Dl'#DlOOO`'#DZ'#DZQVO!rOOO%UQ&rO,59^O%aQ&rO,59gO%lQ&rO,59jO%wQ&rO,59mO&SQ&rO,59oOOOa'#D_'#D_O&_OaO'#CyO&jOaO,59]OOOb'#D`'#D`O&rObO'#C|O&}ObO,59]OOOd'#Da'#DaO'VOdO'#DPO'bOdO,59]OOO`'#Db'#DbO'jO!rO,59]O'qQ#tO'#DSOOO`,59],59]OOOp'#Dc'#DcO'vO$fO,59pOOO`,59p,59pO(OQ#|O,59rO(TQ#|O,59sOOO`-E7X-E7XO(YQ&rO'#CtOOQW'#D['#D[O(hQ&rO1G.xOOOa1G.x1G.xOOO`1G/Z1G/ZO(sQ&rO1G/ROOOb1G/R1G/RO)OQ&rO1G/UOOOd1G/U1G/UO)ZQ&rO1G/XOOO`1G/X1G/XO)fQ&rO1G/ZOOOa-E7]-E7]O)qQ#tO'#CzOOO`1G.w1G.wOOOb-E7^-E7^O)vQ#tO'#C}OOOd-E7_-E7_O){Q#tO'#DQOOO`-E7`-E7`O*QQ#|O,59nOOOp-E7a-E7aOOO`1G/[1G/[OOO`1G/^1G/^OOO`1G/_1G/_O*VQ,UO,59`OOQW-E7Y-E7YOOOa7+$d7+$dOOO`7+$u7+$uOOOb7+$m7+$mOOOd7+$p7+$pOOO`7+$s7+$sO*bQ#|O,59fO*gQ#|O,59iO*lQ#|O,59lOOO`1G/Y1G/YO*qO7[O'#CwO+SOMhO'#CwOOQW1G.z1G.zOOO`1G/Q1G/QOOO`1G/T1G/TOOO`1G/W1G/WOOOO'#D]'#D]O+eO7[O,59cOOQW,59c,59cOOOO'#D^'#D^O+vOMhO,59cOOOO-E7Z-E7ZOOQW1G.}1G.}OOOO-E7[-E7[",stateData:",c~O!_OS~OUSOVPOWQOXROYTO[]O][O^^O_^Oa^Ob^Oc^Od^Oy^O|_O!eZO~OgaO~OgbO~OgcO~OgdO~OgeO~O!XfOPmP![mP~O!YiOQpP![pP~O!ZlORsP![sP~OUSOVPOWQOXROYTOZqO[]O][O^^O_^Oa^Ob^Oc^Od^Oy^O!eZO~O![rO~P#gO!]sO!fuO~OgvO~OgwO~OS|OT}OiyO~OS!POT}OiyO~OS!ROT}OiyO~OS!TOT}OiyO~OS}OT}OiyO~O!XfOPmX![mX~OP!WO![!XO~O!YiOQpX![pX~OQ!ZO![!XO~O!ZlORsX![sX~OR!]O![!XO~O![!XO~P#gOg!_O~O!]sO!f!aO~OS!bO~OS!cO~Oj!dOShXThXihX~OS!fOT!gOiyO~OS!hOT!gOiyO~OS!iOT!gOiyO~OS!jOT!gOiyO~OS!gOT!gOiyO~Og!kO~Og!lO~Og!mO~OS!nO~Ol!qO!a!oO!c!pO~OS!rO~OS!sO~OS!tO~Ob!uOc!uOd!uO!a!wO!b!uO~Ob!xOc!xOd!xO!c!wO!d!xO~Ob!uOc!uOd!uO!a!{O!b!uO~Ob!xOc!xOd!xO!c!{O!d!xO~OT~cbd!ey|!e~",goto:"%q!aPPPPPPPPPPPPPPPPPPPPP!b!hP!nPP!zP!}#Q#T#Z#^#a#g#j#m#s#y!bP!b!bP$P$V$m$s$y%P%V%]%cPPPPPPPP%iX^OX`pXUOX`pezabcde{!O!Q!S!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ!ObQ!QcQ!SdQ!UeZ!e{!O!Q!S!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag EndTag SelfClosingEndTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:68,context:x1,nodeProps:[["closedBy",-10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,22,31,34,37,"CloseTag"],["openedBy",4,"StartTag StartCloseTag",5,"StartTag",-4,30,33,36,38,"OpenTag"],["group",-10,14,15,18,19,20,21,40,41,42,43,"Entity",17,"Entity TextContent",-3,29,32,35,"TextContent Entity"],["isolate",-11,22,30,31,33,34,36,37,38,39,42,43,"ltr",-3,27,28,40,""]],propSources:[Z1],skippedNodes:[0],repeatNodeCount:9,tokenData:"!]tw8twx7Sx!P8t!P!Q5u!Q!]8t!]!^/^!^!a7S!a#S8t#S#T;{#T#s8t#s$f5u$f;'S8t;'S;=`>V<%l?Ah8t?Ah?BY5u?BY?Mn8t?MnO5u!Z5zblWOX5uXZ7SZ[5u[^7S^p5uqr5urs7Sst+Ptw5uwx7Sx!]5u!]!^7w!^!a7S!a#S5u#S#T7S#T;'S5u;'S;=`8n<%lO5u!R7VVOp7Sqs7St!]7S!]!^7l!^;'S7S;'S;=`7q<%lO7S!R7qOb!R!R7tP;=`<%l7S!Z8OYlWb!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!Z8qP;=`<%l5u!_8{iiSlWOX5uXZ7SZ[5u[^7S^p5uqr8trs7Sst/^tw8twx7Sx!P8t!P!Q5u!Q!]8t!]!^:j!^!a7S!a#S8t#S#T;{#T#s8t#s$f5u$f;'S8t;'S;=`>V<%l?Ah8t?Ah?BY5u?BY?Mn8t?MnO5u!_:sbiSlWb!ROX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!a#S/^#S#T0m#T#s/^#s$f+P$f;'S/^;'S;=`1e<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+P!VP<%l?Ah;{?Ah?BY7S?BY?Mn;{?MnO7S!V=dXiSb!Rqr0msw0mx!P0m!Q!^0m!a#s0m$f;'S0m;'S;=`1_<%l?Ah0m?BY?Mn0m!V>SP;=`<%l;{!_>YP;=`<%l8t!_>dhiSlWOX@OXZAYZ[@O[^AY^p@OqrBwrsAYswBwwxAYx!PBw!P!Q@O!Q!]Bw!]!^/^!^!aAY!a#SBw#S#TE{#T#sBw#s$f@O$f;'SBw;'S;=`HS<%l?AhBw?Ah?BY@O?BY?MnBw?MnO@O!Z@TalWOX@OXZAYZ[@O[^AY^p@Oqr@OrsAYsw@OwxAYx!]@O!]!^Az!^!aAY!a#S@O#S#TAY#T;'S@O;'S;=`Bq<%lO@O!RA]UOpAYq!]AY!]!^Ao!^;'SAY;'S;=`At<%lOAY!RAtOc!R!RAwP;=`<%lAY!ZBRYlWc!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!ZBtP;=`<%l@O!_COhiSlWOX@OXZAYZ[@O[^AY^p@OqrBwrsAYswBwwxAYx!PBw!P!Q@O!Q!]Bw!]!^Dj!^!aAY!a#SBw#S#TE{#T#sBw#s$f@O$f;'SBw;'S;=`HS<%l?AhBw?Ah?BY@O?BY?MnBw?MnO@O!_DsbiSlWc!ROX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!a#S/^#S#T0m#T#s/^#s$f+P$f;'S/^;'S;=`1e<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+P!VFQbiSOpAYqrE{rsAYswE{wxAYx!PE{!P!QAY!Q!]E{!]!^GY!^!aAY!a#sE{#s$fAY$f;'SE{;'S;=`G|<%l?AhE{?Ah?BYAY?BY?MnE{?MnOAY!VGaXiSc!Rqr0msw0mx!P0m!Q!^0m!a#s0m$f;'S0m;'S;=`1_<%l?Ah0m?BY?Mn0m!VHPP;=`<%lE{!_HVP;=`<%lBw!ZHcW!cxaP!b`Or(trs'ksv(tw!^(t!^!_)e!_;'S(t;'S;=`*P<%lO(t!aIYliSaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx}-_}!OKQ!O!P-_!P!Q$q!Q!^-_!^!_*V!_!a&X!a#S-_#S#T1k#T#s-_#s$f$q$f;'S-_;'S;=`3X<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q!aK_kiSaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx!P-_!P!Q$q!Q!^-_!^!_*V!_!`&X!`!aMS!a#S-_#S#T1k#T#s-_#s$f$q$f;'S-_;'S;=`3X<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q!TM_XaP!b`!dp!fQOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X!aNZ!ZiSgQaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx}-_}!OMz!O!PMz!P!Q$q!Q![Mz![!]Mz!]!^-_!^!_*V!_!a&X!a!c-_!c!}Mz!}#R-_#R#SMz#S#T1k#T#oMz#o#s-_#s$f$q$f$}-_$}%OMz%O%W-_%W%oMz%o%p-_%p&aMz&a&b-_&b1pMz1p4UMz4U4dMz4d4e-_4e$ISMz$IS$I`-_$I`$IbMz$Ib$Je-_$Je$JgMz$Jg$Kh-_$Kh%#tMz%#t&/x-_&/x&EtMz&Et&FV-_&FV;'SMz;'S;:j!#|;:j;=`3X<%l?&r-_?&r?AhMz?Ah?BY$q?BY?MnMz?MnO$q!a!$PP;=`<%lMz!R!$ZY!b`!dpOq*Vqr!$yrs(Vsv*Vwx)ex!a*V!a!b!4t!b;'S*V;'S;=`*s<%lO*V!R!%Q]!b`!dpOr*Vrs(Vsv*Vwx)ex}*V}!O!%y!O!f*V!f!g!']!g#W*V#W#X!0`#X;'S*V;'S;=`*s<%lO*V!R!&QX!b`!dpOr*Vrs(Vsv*Vwx)ex}*V}!O!&m!O;'S*V;'S;=`*s<%lO*V!R!&vV!b`!dp!ePOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!'dX!b`!dpOr*Vrs(Vsv*Vwx)ex!q*V!q!r!(P!r;'S*V;'S;=`*s<%lO*V!R!(WX!b`!dpOr*Vrs(Vsv*Vwx)ex!e*V!e!f!(s!f;'S*V;'S;=`*s<%lO*V!R!(zX!b`!dpOr*Vrs(Vsv*Vwx)ex!v*V!v!w!)g!w;'S*V;'S;=`*s<%lO*V!R!)nX!b`!dpOr*Vrs(Vsv*Vwx)ex!{*V!{!|!*Z!|;'S*V;'S;=`*s<%lO*V!R!*bX!b`!dpOr*Vrs(Vsv*Vwx)ex!r*V!r!s!*}!s;'S*V;'S;=`*s<%lO*V!R!+UX!b`!dpOr*Vrs(Vsv*Vwx)ex!g*V!g!h!+q!h;'S*V;'S;=`*s<%lO*V!R!+xY!b`!dpOr!+qrs!,hsv!+qvw!-Swx!.[x!`!+q!`!a!/j!a;'S!+q;'S;=`!0Y<%lO!+qq!,mV!dpOv!,hvx!-Sx!`!,h!`!a!-q!a;'S!,h;'S;=`!.U<%lO!,hP!-VTO!`!-S!`!a!-f!a;'S!-S;'S;=`!-k<%lO!-SP!-kO|PP!-nP;=`<%l!-Sq!-xS!dp|POv(Vx;'S(V;'S;=`(h<%lO(Vq!.XP;=`<%l!,ha!.aX!b`Or!.[rs!-Ssv!.[vw!-Sw!`!.[!`!a!.|!a;'S!.[;'S;=`!/d<%lO!.[a!/TT!b`|POr)esv)ew;'S)e;'S;=`)y<%lO)ea!/gP;=`<%l!.[!R!/sV!b`!dp|POr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!0]P;=`<%l!+q!R!0gX!b`!dpOr*Vrs(Vsv*Vwx)ex#c*V#c#d!1S#d;'S*V;'S;=`*s<%lO*V!R!1ZX!b`!dpOr*Vrs(Vsv*Vwx)ex#V*V#V#W!1v#W;'S*V;'S;=`*s<%lO*V!R!1}X!b`!dpOr*Vrs(Vsv*Vwx)ex#h*V#h#i!2j#i;'S*V;'S;=`*s<%lO*V!R!2qX!b`!dpOr*Vrs(Vsv*Vwx)ex#m*V#m#n!3^#n;'S*V;'S;=`*s<%lO*V!R!3eX!b`!dpOr*Vrs(Vsv*Vwx)ex#d*V#d#e!4Q#e;'S*V;'S;=`*s<%lO*V!R!4XX!b`!dpOr*Vrs(Vsv*Vwx)ex#X*V#X#Y!+q#Y;'S*V;'S;=`*s<%lO*V!R!4{Y!b`!dpOr!4trs!5ksv!4tvw!6Vwx!8]x!a!4t!a!b!:]!b;'S!4t;'S;=`!;r<%lO!4tq!5pV!dpOv!5kvx!6Vx!a!5k!a!b!7W!b;'S!5k;'S;=`!8V<%lO!5kP!6YTO!a!6V!a!b!6i!b;'S!6V;'S;=`!7Q<%lO!6VP!6lTO!`!6V!`!a!6{!a;'S!6V;'S;=`!7Q<%lO!6VP!7QOyPP!7TP;=`<%l!6Vq!7]V!dpOv!5kvx!6Vx!`!5k!`!a!7r!a;'S!5k;'S;=`!8V<%lO!5kq!7yS!dpyPOv(Vx;'S(V;'S;=`(h<%lO(Vq!8YP;=`<%l!5ka!8bX!b`Or!8]rs!6Vsv!8]vw!6Vw!a!8]!a!b!8}!b;'S!8];'S;=`!:V<%lO!8]a!9SX!b`Or!8]rs!6Vsv!8]vw!6Vw!`!8]!`!a!9o!a;'S!8];'S;=`!:V<%lO!8]a!9vT!b`yPOr)esv)ew;'S)e;'S;=`)y<%lO)ea!:YP;=`<%l!8]!R!:dY!b`!dpOr!4trs!5ksv!4tvw!6Vwx!8]x!`!4t!`!a!;S!a;'S!4t;'S;=`!;r<%lO!4t!R!;]V!b`!dpyPOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!;uP;=`<%l!4t!V!{let h=l.type.id;if(h==a1)return ys(l,a,t);if(h==h1)return ys(l,a,i);if(h==c1)return ys(l,a,r);if(h==Vu&&s.length){let c=l.node,f=c.firstChild,u=f&&wh(f,a),O;if(u){for(let d of s)if(d.tag==u&&(!d.attrs||d.attrs(O||(O=Iu(f,a))))){let p=c.lastChild,g=p.type.id==u1?p.from:c.to;if(g>f.to)return{parser:d.parser,overlay:[{from:f.to,to:g}]}}}}if(o&&h==Bu){let c=l.node,f;if(f=c.firstChild){let u=o[a.read(f.from,f.to)];if(u)for(let O of u){if(O.tagName&&O.tagName!=wh(c.parent,a))continue;let d=c.lastChild;if(d.type.id==$o){let p=d.from+1,g=d.lastChild,S=d.to-(g&&g.isError?0:1);if(S>p)return{parser:O.parser,overlay:[{from:p,to:S}],bracketed:!0}}else if(d.type.id==qu)return{parser:O.parser,overlay:[{from:d.from,to:d.to}]}}}}return null})}const A1=148,$h=1,R1=149,M1=150,Gu=2,j1=151,L1=3,Y1=4,Uu=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],E1=58,z1=40,Fu=95,_1=91,er=45,W1=46,V1=35,B1=37,q1=38,D1=92,I1=10,N1=42;function hn(n){return n>=65&&n<=90||n>=97&&n<=122||n>=161}function Sl(n){return n>=48&&n<=57}function Ph(n){return Sl(n)||n>=97&&n<=102||n>=65&&n<=70}const Hu=(n,e,t)=>(i,r)=>{for(let s=!1,o=0,l=0;;l++){let{next:a}=i;if(hn(a)||a==er||a==Fu||s&&Sl(a))!s&&(a!=er||l>0)&&(s=!0),o===l&&a==er&&o++,i.advance();else if(a==D1&&i.peek(1)!=I1){if(i.advance(),Ph(i.next)){do i.advance();while(Ph(i.next));i.next==32&&i.advance()}else i.next>-1&&i.advance();s=!0}else{s&&i.acceptToken(o==2&&r.canShift(Gu)?e:a==z1?t:n);break}}},G1=new Re(Hu(R1,Gu,M1),{contextual:!0}),U1=new Re(Hu(j1,L1,Y1),{contextual:!0}),F1=new Re(n=>{if(Uu.includes(n.peek(-1))){let{next:e}=n;(hn(e)||e==Fu||e==V1||e==W1||e==N1||e==_1||e==E1&&hn(n.peek(1))||e==er||e==q1)&&n.acceptToken(A1)}}),H1=new Re(n=>{if(!Uu.includes(n.peek(-1))){let{next:e}=n;if(e==B1&&(n.advance(),n.acceptToken($h)),hn(e)){do n.advance();while(hn(n.next)||Sl(n.next));n.acceptToken($h)}}}),K1=xi({"AtKeyword import charset namespace keyframes media supports font-feature-values":m.definitionKeyword,"from to selector scope MatchFlag":m.keyword,NamespaceName:m.namespace,KeyframeName:m.labelName,KeyframeRangeName:m.operatorKeyword,TagName:m.tagName,ClassName:m.className,PseudoClassName:m.constant(m.className),IdName:m.labelName,"FeatureName PropertyName":m.propertyName,AttributeName:m.attributeName,NumberLiteral:m.number,KeywordQuery:m.keyword,UnaryQueryOp:m.operatorKeyword,"CallTag ValueName FontName":m.atom,VariableName:m.variableName,Callee:m.operatorKeyword,Unit:m.unit,"UniversalSelector NestingSelector":m.definitionOperator,"MatchOp CompareOp":m.compareOperator,"ChildOp SiblingOp, LogicOp":m.logicOperator,BinOp:m.arithmeticOperator,Important:m.modifier,Comment:m.blockComment,ColorLiteral:m.color,"ParenthesizedContent StringLiteral":m.string,":":m.punctuation,"PseudoOp #":m.derefOperator,"; , |":m.separator,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace}),J1={__proto__:null,lang:44,"nth-child":44,"nth-last-child":44,"nth-of-type":44,"nth-last-of-type":44,dir:44,"host-context":44,if:90,url:158,"url-prefix":158,domain:158,regexp:158},eb={__proto__:null,or:104,and:104,not:112,only:112,layer:212},tb={__proto__:null,selector:118,style:124,layer:208},ib={__proto__:null,"@import":204,"@media":216,"@charset":220,"@namespace":224,"@keyframes":230,"@supports":242,"@scope":246,"@font-feature-values":252},nb={__proto__:null,to:249},rb=Qi.deserialize({version:14,states:"MrQYQdOOO#}QdOOP$UO`OOO%OQaO'#CfOOQP'#Ce'#CeO%VQdO'#CgO%[Q`O'#CgO%aQaO'#FqO&XQdO'#CkO&xQaO'#CcO'SQdO'#CnO'_QdO'#ERO'dQdO'#ETO'oQdO'#E[O'oQdO'#E_OOQP'#Fq'#FqO)RQhO'#FQOOQS'#Fp'#FpOOQS'#FT'#FTQYQdOOO)YQdO'#EeO*iQhO'#EkO)YQdO'#EmO*pQdO'#EoO*{QdO'#ErO)}QhO'#ExO+TQdO'#EzO+`QdO'#E}O+eQaO'#CfO+lQ`O'#EbO+qQ`O'#F}O+|QdO'#F}QOQ`OOP,WO&jO'#CaPOOO)CA`)CA`OOQP'#Ci'#CiOOQP,59R,59RO%VQdO,59ROOQP'#Cm'#CmOOQP,59V,59VO&XQdO,59VO,cQdO,59YO'_QdO,5:mO'dQdO,5:oO'oQdO,5:vO'oQdO,5:xO'oQdO,5:yO'oQdO'#F[O,nQ`O,58}O,vQdO'#EaOOQS,58},58}OOQP'#Cq'#CqOOQO'#EP'#EPOOQP,59Y,59YO,}Q`O,59YO-SQ`O,59YOOQP'#ES'#ESOOQP,5:m,5:mO-XQpO'#EUO-dQdO'#EVO-iQ`O'#EVO-nQpO,5:oO.XQaO,5:vO.oQaO,5:yOOQW'#D^'#D^O/nQhO'#DgO0RQhO,5;lO)}QhO'#DeO0`Q`O'#DnO0eQhO'#D{OOQW'#Fw'#FwOOQS,5;l,5;lO0jQ`O'#DhO0oQ`O'#DkOOQS-E9R-E9ROOQ['#Cv'#CvO0tQdO'#CwO1[QdO'#C}O1rQdO'#DQO2YQ!pO'#DSO4fQ!jO,5;POOQO'#DX'#DXO-SQ`O'#DWO4vQ!nO'#FtO6|Q`O'#DYO7RQ`O'#D|OOQ['#Ft'#FtO7WQhO'#GQO7fQ`O,5;VO7kQ!bO,5;XOOQS'#Eq'#EqO7sQ`O,5;ZO7xQdO,5;ZOOQO'#Et'#EtO8QQ`O,5;^O8VQhO,5;dO'oQdO'#DjOOQS,5;f,5;fO0jQ`O,5;fO8_QdO,5;fOOQS'#Fc'#FcO8gQdO'#FPO7fQ`O,5;iO8oQdO,5:|O9PQdO'#F^O9^Q`O,5lQhO'#DoOOQW,5:Y,5:YOOQW,5:g,5:gOOQW,5:S,5:SO>vQhO,5:VO?bQ!fO'#FuOOQS'#Fu'#FuOOQS'#FV'#FVO@rQdO,59cOOQ[,59c,59cOAYQdO,59iOOQ[,59i,59iOApQdO,59lOOQ[,59l,59lOOQ[,59n,59nO)YQdO,59pOBWQhO'#EgOOQW'#Eg'#EgOBuQ`O1G0kO4oQhO1G0kOOQ[,59r,59rO)}QhO'#D[OOQ[,59t,59tOBzQ#tO,5:hOCVQhO'#F`OCdQ`O,5vQhO'#DmOI_QhO'#DsOIgQhO'#DuOIlQ!jO'#FzOOQO'#Fz'#FzOIwQ`O'#DxOJPQ!bO'#DzOOQO'#Fy'#FyOJUQ`O1G/qOOQS-E9T-E9TOOQ[1G.}1G.}OOQ[1G/T1G/TOOQ[1G/W1G/WOOQ[1G/[1G/[OJZQdO,5;ROOQS7+&V7+&VOJ`Q`O7+&VOJeQhO'#D]OJmQ`O,59vO)}QhO,59vOOQ[1G0S1G0SOJuQ`O1G0SOJzQhO,5;zOOQO-E9^-E9^OOQS7+&a7+&aOKYQbO'#DSOOQO'#Ew'#EwOKhQ`O'#EvOOQO'#Ev'#EvOKsQ`O'#FaOK{QdO,5;aOOQS,5;a,5;aOOQ[1G/p1G/pOOQS7+&l7+&lO7fQ`O7+&lOLWQ!fO'#F]O)YQdO'#F]OM_QdO7+&SOOQO7+&S7+&SOOQO,5;O,5;OOOQO1G1d1G1dOMrQ!bO<vQhO'#DtOOQO,5:_,5:_O! sQhO,5:aO! {QhO,5:fO)YQdO,5:dOOQW7+%]7+%]OOQO'#Ei'#EiO!!SQ`O1G0mOOQS<{AN>{O!$^Q`OAN>{O!$cQaO,5;uOOQO-E9X-E9XO!$mQdO,5;tOOQO-E9W-E9WOOQW<vQhO'#DwOOQO1G/{1G/{O!&aQ!bO1G0QO!&iQdO1G0OOJZQdO'#F_O!&pQ`O7+&XOOQW7+&X7+&XO!&xQ!bO1G/cOOQ[7+$|7+$|O!'TQhO7+$|P!'[Q`O'#FWOOQO,5;|,5;|OOQO-E9`-E9`OOQS1G1g1G1gOOQPG24gG24gO!'aQ`OAN>ZO)YQdO1G1_O!'fQ`O7+'mOOQO1G/z1G/zO!'nQ`O,5:cO!'sQhO7+%lOOQO,5;y,5;yOOQO-E9]-E9]OOQW<Q!]!^>|!^!_?_!_!`@Z!`!a@n!a!b%Z!b!cAo!c!k%Z!k!lC|!l!u%Z!u!vC|!v!}%Z!}#OD_#O#P%Z#P#QDp#Q#R2X#R#]%Z#]#^ER#^#g%Z#g#hC|#h#o%Z#o#pIf#p#qIw#q#rJ`#r#sJq#s#y%Z#y#z&R#z$f%Z$f$g&R$g#BY%Z#BY#BZ&R#BZ$IS%Z$IS$I_&R$I_$I|%Z$I|$JO&R$JO$JT%Z$JT$JU&R$JU$KV%Z$KV$KW&R$KW&FU%Z&FU&FV&R&FV;'S%Z;'S;=`KY<%lO%Z`%^SOy%jz;'S%j;'S;=`%{<%lO%j`%oS!r`Oy%jz;'S%j;'S;=`%{<%lO%j`&OP;=`<%l%j~&Wh$_~OX%jX^'r^p%jpq'rqy%jz#y%j#y#z'r#z$f%j$f$g'r$g#BY%j#BY#BZ'r#BZ$IS%j$IS$I_'r$I_$I|%j$I|$JO'r$JO$JT%j$JT$JU'r$JU$KV%j$KV$KW'r$KW&FU%j&FU&FV'r&FV;'S%j;'S;=`%{<%lO%j~'yh$_~!r`OX%jX^'r^p%jpq'rqy%jz#y%j#y#z'r#z$f%j$f$g'r$g#BY%j#BY#BZ'r#BZ$IS%j$IS$I_'r$I_$I|%j$I|$JO'r$JO$JT%j$JT$JU'r$JU$KV%j$KV$KW'r$KW&FU%j&FU&FV'r&FV;'S%j;'S;=`%{<%lO%jj)jS$sYOy%jz;'S%j;'S;=`%{<%lO%j~)yWOY)vZr)vrs*cs#O)v#O#P*h#P;'S)v;'S;=`+d<%lO)v~*hOw~~*kRO;'S)v;'S;=`*t;=`O)v~*wXOY)vZr)vrs*cs#O)v#O#P*h#P;'S)v;'S;=`+d;=`<%l)v<%lO)v~+gP;=`<%l)vj+oYmYOy%jz!Q%j!Q![,_![!c%j!c!i,_!i#T%j#T#Z,_#Z;'S%j;'S;=`%{<%lO%jj,dY!r`Oy%jz!Q%j!Q![-S![!c%j!c!i-S!i#T%j#T#Z-S#Z;'S%j;'S;=`%{<%lO%jj-XY!r`Oy%jz!Q%j!Q![-w![!c%j!c!i-w!i#T%j#T#Z-w#Z;'S%j;'S;=`%{<%lO%jj.OYuY!r`Oy%jz!Q%j!Q![.n![!c%j!c!i.n!i#T%j#T#Z.n#Z;'S%j;'S;=`%{<%lO%jj.uYuY!r`Oy%jz!Q%j!Q![/e![!c%j!c!i/e!i#T%j#T#Z/e#Z;'S%j;'S;=`%{<%lO%jj/jY!r`Oy%jz!Q%j!Q![0Y![!c%j!c!i0Y!i#T%j#T#Z0Y#Z;'S%j;'S;=`%{<%lO%jj0aYuY!r`Oy%jz!Q%j!Q![1P![!c%j!c!i1P!i#T%j#T#Z1P#Z;'S%j;'S;=`%{<%lO%jj1UY!r`Oy%jz!Q%j!Q![1t![!c%j!c!i1t!i#T%j#T#Z1t#Z;'S%j;'S;=`%{<%lO%jj1{SuY!r`Oy%jz;'S%j;'S;=`%{<%lO%jd2[UOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jd2uS!|S!r`Oy%jz;'S%j;'S;=`%{<%lO%jb3WS^QOy%jz;'S%j;'S;=`%{<%lO%j~3gWOY3dZw3dwx*cx#O3d#O#P4P#P;'S3d;'S;=`4{<%lO3d~4SRO;'S3d;'S;=`4];=`O3d~4`XOY3dZw3dwx*cx#O3d#O#P4P#P;'S3d;'S;=`4{;=`<%l3d<%lO3d~5OP;=`<%l3dj5WShYOy%jz;'S%j;'S;=`%{<%lO%j~5iOg~n5pUWQyWOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jj6ZWyW#SQOy%jz!O%j!O!P6s!P!Q%j!Q![9x![;'S%j;'S;=`%{<%lO%jj6xU!r`Oy%jz!Q%j!Q![7[![;'S%j;'S;=`%{<%lO%jj7cY!r`$jYOy%jz!Q%j!Q![7[![!g%j!g!h8R!h#X%j#X#Y8R#Y;'S%j;'S;=`%{<%lO%jj8WY!r`Oy%jz{%j{|8v|}%j}!O8v!O!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj8{U!r`Oy%jz!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj9fU!r`$jYOy%jz!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj:P[!r`$jYOy%jz!O%j!O!P7[!P!Q%j!Q![9x![!g%j!g!h8R!h#X%j#X#Y8R#Y;'S%j;'S;=`%{<%lO%jj:zS!eYOy%jz;'S%j;'S;=`%{<%lO%jj;]WyWOy%jz!O%j!O!P6s!P!Q%j!Q![9x![;'S%j;'S;=`%{<%lO%jj;zU`YOy%jz!Q%j!Q![7[![;'S%j;'S;=`%{<%lO%j~VUcYOy%jz![%j![!]>i!];'S%j;'S;=`%{<%lO%jj>pSdY!r`Oy%jz;'S%j;'S;=`%{<%lO%jj?RSnYOy%jz;'S%j;'S;=`%{<%lO%jh?dU!WWOy%jz!_%j!_!`?v!`;'S%j;'S;=`%{<%lO%jh?}S!WW!r`Oy%jz;'S%j;'S;=`%{<%lO%jl@bS!WW!|SOy%jz;'S%j;'S;=`%{<%lO%jj@uV#PQ!WWOy%jz!_%j!_!`?v!`!aA[!a;'S%j;'S;=`%{<%lO%jbAcS#PQ!r`Oy%jz;'S%j;'S;=`%{<%lO%jjArYOy%jz}%j}!OBb!O!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jjBgW!r`Oy%jz!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jjCW[lY!r`Oy%jz}%j}!OCP!O!Q%j!Q![CP![!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jhDRS!}WOy%jz;'S%j;'S;=`%{<%lO%jjDdSpYOy%jz;'S%j;'S;=`%{<%lO%jnDuSo^Oy%jz;'S%j;'S;=`%{<%lO%jjEWU!}WOy%jz#a%j#a#bEj#b;'S%j;'S;=`%{<%lO%jbEoU!r`Oy%jz#d%j#d#eFR#e;'S%j;'S;=`%{<%lO%jbFWU!r`Oy%jz#c%j#c#dFj#d;'S%j;'S;=`%{<%lO%jbFoU!r`Oy%jz#f%j#f#gGR#g;'S%j;'S;=`%{<%lO%jbGWU!r`Oy%jz#h%j#h#iGj#i;'S%j;'S;=`%{<%lO%jbGoU!r`Oy%jz#T%j#T#UHR#U;'S%j;'S;=`%{<%lO%jbHWU!r`Oy%jz#b%j#b#cHj#c;'S%j;'S;=`%{<%lO%jbHoU!r`Oy%jz#h%j#h#iIR#i;'S%j;'S;=`%{<%lO%jbIYS$rQ!r`Oy%jz;'S%j;'S;=`%{<%lO%jjIkSsYOy%jz;'S%j;'S;=`%{<%lO%jfI|U$fUOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jjJeSrYOy%jz;'S%j;'S;=`%{<%lO%jfJvU#SQOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%j`K]P;=`<%l%Z",tokenizers:[F1,H1,G1,U1,1,2,3,4,new Pr("m~RRYZ[z{a~~g~aO$b~~dP!P!Qg~lO$c~~",28,155)],topRules:{StyleSheet:[0,6],Styles:[1,129]},dynamicPrecedences:{97:1},specialized:[{term:150,get:n=>J1[n]||-1},{term:151,get:n=>eb[n]||-1},{term:4,get:n=>tb[n]||-1},{term:28,get:n=>ib[n]||-1},{term:149,get:n=>nb[n]||-1}],tokenPrec:2444});let xs=null;function ks(){if(!xs&&typeof document=="object"&&document.body){let{style:n}=document.body,e=[],t=new Set;for(let i in n)i!="cssText"&&i!="cssFloat"&&typeof n[i]=="string"&&(/[A-Z]/.test(i)&&(i=i.replace(/[A-Z]/g,r=>"-"+r.toLowerCase())),t.has(i)||(e.push(i),t.add(i)));xs=e.sort().map(i=>({type:"property",label:i,apply:i+": "}))}return xs||[]}const vh=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map(n=>({type:"class",label:n})),Th=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map(n=>({type:"keyword",label:n})).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map(n=>({type:"constant",label:n}))),sb=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map(n=>({type:"type",label:n})),ob=["@charset","@color-profile","@container","@counter-style","@font-face","@font-feature-values","@font-palette-values","@import","@keyframes","@layer","@media","@namespace","@page","@position-try","@property","@scope","@starting-style","@supports","@view-transition"].map(n=>({type:"keyword",label:n})),ut=/^(\w[\w-]*|-\w[\w-]*|)$/,lb=/^-(-[\w-]*)?$/;function ab(n,e){var t;if((n.name=="("||n.type.isError)&&(n=n.parent||n),n.name!="ArgList")return!1;let i=(t=n.parent)===null||t===void 0?void 0:t.firstChild;return i?.name!="Callee"?!1:e.sliceString(i.from,i.to)=="var"}const Ch=new af,hb=["Declaration"];function cb(n){for(let e=n;;){if(e.type.isTop)return e;if(!(e=e.parent))return n}}function Ku(n,e,t){if(e.to-e.from>4096){let i=Ch.get(e);if(i)return i;let r=[],s=new Set,o=e.cursor(D.IncludeAnonymous);if(o.firstChild())do for(let l of Ku(n,o.node,t))s.has(l.label)||(s.add(l.label),r.push(l));while(o.nextSibling());return Ch.set(e,r),r}else{let i=[],r=new Set;return e.cursor().iterate(s=>{var o;if(t(s)&&s.matchContext(hb)&&((o=s.node.nextSibling)===null||o===void 0?void 0:o.name)==":"){let l=n.sliceString(s.from,s.to);r.has(l)||(r.add(l),i.push({label:l,type:"variable"}))}}),i}}const fb=n=>e=>{let{state:t,pos:i}=e,r=J(t).resolveInner(i,-1),s=r.type.isError&&r.from==r.to-1&&t.doc.sliceString(r.from,r.to)=="-";if(r.name=="PropertyName"||(s||r.name=="TagName")&&/^(Block|Styles)$/.test(r.resolve(r.to).name))return{from:r.from,options:ks(),validFor:ut};if(r.name=="ValueName")return{from:r.from,options:Th,validFor:ut};if(r.name=="PseudoClassName")return{from:r.from,options:vh,validFor:ut};if(n(r)||(e.explicit||s)&&ab(r,t.doc))return{from:n(r)||s?r.from:i,options:Ku(t.doc,cb(r),n),validFor:lb};if(r.name=="TagName"){for(let{parent:a}=r;a;a=a.parent)if(a.name=="Block")return{from:r.from,options:ks(),validFor:ut};return{from:r.from,options:sb,validFor:ut}}if(r.name=="AtKeyword")return{from:r.from,options:ob,validFor:ut};if(!e.explicit)return null;let o=r.resolve(i),l=o.childBefore(i);return l&&l.name==":"&&o.name=="PseudoClassSelector"?{from:i,options:vh,validFor:ut}:l&&l.name==":"&&o.name=="Declaration"||o.name=="ArgList"?{from:i,options:Th,validFor:ut}:o.name=="Block"||o.name=="Styles"?{from:i,options:ks(),validFor:ut}:null},ub=fb(n=>n.name=="VariableName"),Tr=mi.define({name:"css",parser:rb.configure({props:[Sn.add({Declaration:Kn()}),ki.add({"Block KeyframeList":gf})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function Ob(){return new rn(Tr,Tr.data.of({autocomplete:ub}))}const db=316,pb=317,Zh=1,mb=2,gb=3,Sb=4,bb=318,Qb=320,yb=321,xb=5,kb=6,wb=0,vo=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],Ju=125,$b=59,To=47,Pb=42,vb=43,Tb=45,Cb=60,Zb=44,Xb=63,Ab=46,Rb=91,Mb=new Yu({start:!1,shift(n,e){return e==xb||e==kb||e==Qb?n:e==yb},strict:!1}),jb=new Re((n,e)=>{let{next:t}=n;(t==Ju||t==-1||e.context)&&n.acceptToken(bb)},{contextual:!0,fallback:!0}),Lb=new Re((n,e)=>{let{next:t}=n,i;vo.indexOf(t)>-1||t==To&&((i=n.peek(1))==To||i==Pb)||t!=Ju&&t!=$b&&t!=-1&&!e.context&&n.acceptToken(db)},{contextual:!0}),Yb=new Re((n,e)=>{n.next==Rb&&!e.context&&n.acceptToken(pb)},{contextual:!0}),Eb=new Re((n,e)=>{let{next:t}=n;if(t==vb||t==Tb){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(Zh);n.acceptToken(i?Zh:mb)}}else t==Xb&&n.peek(1)==Ab&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(gb))},{contextual:!0});function ws(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const zb=new Re((n,e)=>{if(n.next!=Cb||!e.dialectEnabled(wb)||(n.advance(),n.next==To))return;let t=0;for(;vo.indexOf(n.next)>-1;)n.advance(),t++;if(ws(n.next,!0)){for(n.advance(),t++;ws(n.next,!1);)n.advance(),t++;for(;vo.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==Zb)return;for(let i=0;;i++){if(i==7){if(!ws(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(Sb,-t)}),_b=xi({"get set async static":m.modifier,"for while do if else switch try catch finally return throw break continue default case defer":m.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":m.operatorKeyword,"let var const using function class extends":m.definitionKeyword,"import export from":m.moduleKeyword,"with debugger new":m.keyword,TemplateString:m.special(m.string),super:m.atom,BooleanLiteral:m.bool,this:m.self,null:m.null,Star:m.modifier,VariableName:m.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":m.function(m.variableName),VariableDefinition:m.definition(m.variableName),Label:m.labelName,PropertyName:m.propertyName,PrivatePropertyName:m.special(m.propertyName),"CallExpression/MemberExpression/PropertyName":m.function(m.propertyName),"FunctionDeclaration/VariableDefinition":m.function(m.definition(m.variableName)),"ClassDeclaration/VariableDefinition":m.definition(m.className),"NewExpression/VariableName":m.className,PropertyDefinition:m.definition(m.propertyName),PrivatePropertyDefinition:m.definition(m.special(m.propertyName)),UpdateOp:m.updateOperator,"LineComment Hashbang":m.lineComment,BlockComment:m.blockComment,Number:m.number,String:m.string,Escape:m.escape,ArithOp:m.arithmeticOperator,LogicOp:m.logicOperator,BitOp:m.bitwiseOperator,CompareOp:m.compareOperator,RegExp:m.regexp,Equals:m.definitionOperator,Arrow:m.function(m.punctuation),": Spread":m.punctuation,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace,"InterpolationStart InterpolationEnd":m.special(m.brace),".":m.derefOperator,", ;":m.separator,"@":m.meta,TypeName:m.typeName,TypeDefinition:m.definition(m.typeName),"type enum interface implements namespace module declare":m.definitionKeyword,"abstract global Privacy readonly override":m.modifier,"is keyof unique infer asserts":m.operatorKeyword,JSXAttributeValue:m.attributeValue,JSXText:m.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":m.angleBracket,"JSXIdentifier JSXNameSpacedName":m.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":m.attributeName,"JSXBuiltin/JSXIdentifier":m.standard(m.tagName)}),Wb={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},Vb={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},Bb={__proto__:null,"<":193},qb=Qi.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOAuQ`O'#EnOBQQ!bO'#FeOOQ['#Cg'#CgOOQ!0Lb'#Dq'#DqOOQ!0Lb'#Jv'#JvO%[QlO'#JvOOQO'#Jy'#JyOOQO'#Ih'#IhOCQQpO'#EgOOQ!0Lb'#Ef'#EfOOQ!0Lb'#J}'#J}OC|Q!0MSO'#EgODWQpO'#EWOOQO'#Jx'#JxODlQpO'#JyOEyQpO'#EWODWQpO'#EgPFWO&2DjO'#CbPOOO)CD})CD}OOOO'#I`'#I`OFcO#tO,59UOOQ!0Lh,59U,59UOOOO'#Ia'#IaOFqO&jO,59UOGPQ!L^O'#DcOOOO'#Ic'#IcOGWO#@ItO,59{OOQ!0Lf,59{,59{OGfQlO'#IdOGyQ`O'#JtOIxQ!fO'#JtO+}QlO'#JtOJPQ`O,5:ROJgQ`O'#EpOJtQ`O'#KTOKPQ`O'#KSOKPQ`O'#KSOKXQ`O,5;^OK^Q`O'#KROOQ!0Ln,5:^,5:^OKeQlO,5:^OMcQ!0MxO,5:fONSQ`O,5:nONmQ!0LrO'#KQONtQ`O'#KPO9eQ`O'#KPO! YQ`O'#KPO! bQ`O,5;]O! gQ`O'#KPO!#lQ!fO'#JsOOQ!0Lh'#Ci'#CiO%[QlO'#ESO!$[Q!fO,5:sOOQS'#Jz'#JzOOQO-EtOOQ['#Jh'#JhOOQ[,5>u,5>uOOQ[-E<]-E<]O!TO`QlO,5>VO!LOQ`O,5>XO`QlO,5>ZO!LTQ`O,5>^O!LYQlO,5>dOOQ[,5>j,5>jO%[QlO,5>jO9uQ!0LrO,5>lOOQ[,5>n,5>nO#!dQ`O,5>nOOQ[,5>p,5>pO#!dQ`O,5>pOOQ[,5>r,5>rO##QQpO'#D_O%[QlO'#JvO##sQpO'#JvO##}QpO'#DmO#$`QpO'#DmO#&qQlO'#DmO#&xQ`O'#JuO#'QQ`O,5:WO#'VQ`O'#EtO#'eQ`O'#KUO#'mQ`O,5;_O#'rQpO'#DmO#(PQpO'#EVOOQ!0Lf,5:o,5:oO%[QlO,5:oO#(WQ`O,5:oO?YQ`O,5;YO!CUQpO,5;YO!C^QMhO,5;YO:dQMhO,5;YO#(`Q`O,5@bO#(eQ07dO,5:sOOQO-EPO$6^Q`O,5>POOQ[1G3i1G3iO`QlO1G3iOOQ[1G3o1G3oOOQ[1G3q1G3qO?TQ`O1G3sO$6cQlO1G3uO$:gQlO'#HtOOQ[1G3x1G3xO$:tQ`O'#HzO?YQ`O'#H|OOQ[1G4O1G4OO$:|QlO1G4OO9uQ!0LrO1G4UOOQ[1G4W1G4WOOQ!0Lb'#G_'#G_O9uQ!0LrO1G4YO9uQ!0LrO1G4[O$?TQ`O,5@bO!)[QlO,5;`O9eQ`O,5;`O?YQ`O,5:XO!)[QlO,5:XO!CUQpO,5:XO$?YQ?MtO,5:XOOQO,5;`,5;`O$?dQpO'#IeO$?zQ`O,5@aOOQ!0Lf1G/r1G/rO$@SQpO'#IkO$@^Q`O,5@pOOQ!0Lb1G0y1G0yO#$`QpO,5:XOOQO'#Ig'#IgO$@fQpO,5:qOOQ!0Ln,5:q,5:qO#(ZQ`O1G0ZOOQ!0Lf1G0Z1G0ZO%[QlO1G0ZOOQ!0Lf1G0t1G0tO?YQ`O1G0tO!CUQpO1G0tO!C^QMhO1G0tOOQ!0Lb1G5|1G5|O!ByQ!0LrO1G0^OOQO1G0m1G0mO%[QlO1G0mO$@mQ!0LrO1G0mO$@xQ!0LrO1G0mO!CUQpO1G0^ODWQpO1G0^O$AWQ!0LrO1G0mOOQO1G0^1G0^O$AlQ!0MxO1G0mPOOO-E<[-E<[POOO1G.h1G.hOOOO1G/i1G/iO$AvQ!bO,5QQpO,5@}OOQ!0Lb1G3c1G3cOOQ[7+$V7+$VO@zQ`O7+$VO9uQ!0LrO7+$VO%>]Q`O7+$VO%[QlO1G6lO%[QlO1G6mO%>bQ!0LrO1G6lO%>lQlO1G3kO%>sQ`O1G3kO%>xQlO1G3kOOQ[7+)T7+)TO9uQ!0LrO7+)_O`QlO7+)aOOQ['#Kh'#KhOOQ['#JS'#JSO%?PQlO,5>`OOQ[,5>`,5>`O%[QlO'#HuO%?^Q`O'#HwOOQ[,5>f,5>fO9eQ`O,5>fOOQ[,5>h,5>hOOQ[7+)j7+)jOOQ[7+)p7+)pOOQ[7+)t7+)tOOQ[7+)v7+)vO%?cQpO1G5|O%?}Q?MtO1G0zO%@XQ`O1G0zOOQO1G/s1G/sO%@dQ?MtO1G/sO?YQ`O1G/sO!)[QlO'#DmOOQO,5?P,5?POOQO-ERQ`O7+,WO&>WQ`O7+,XO%[QlO7+,WO%[QlO7+,XOOQ[7+)V7+)VO&>]Q`O7+)VO&>bQlO7+)VO&>iQ`O7+)VOOQ[<nQ`O,5>aOOQ[,5>c,5>cO&>sQ`O1G4QO9eQ`O7+&fO!)[QlO7+&fOOQO7+%_7+%_O&>xQ?MtO1G6ZO?YQ`O7+%_OOQ!0Lf<yQ?MvO,5?aO'@|Q?MvO,5?cO'CPQ?MvO7+'|O'DuQMjOG27TOOQO<VO!l$xO#jROe!iOpkOrPO(T)]O(VTO(YUO(aVO(o[O~O!]$_Oa$qa'z$qa'w$qa!k$qa!Y$qa!_$qa%i$qa!g$qa~Ol)dO~P!&zOh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Og(pP~P!,TO!Q)iO!g)hO!_$^X$Z$^X$]$^X$_$^X$f$^X~O!g)hO!_({X$Z({X$]({X$_({X$f({X~O!Q)iO~P!.^O!Q)iO!_({X$Z({X$]({X$_({X$f({X~O!_)kO$Z)oO$])jO$_)jO$f)pO~O![)sO~P!)[O$]$hO$_$gO$f)wO~On$zX!Q$zX#S$zX'y$zX(y$zX(z$zX~OgmXg$zXnmX!]mX#`mX~P!0SOx)yO(b)zO(c)|O~On*VO!Q*OO'y*PO(y$}O(z%PO~Og)}O~P!1WOg*WO~Oh%VOr%XOs$tOt$tOz%YO|%ZO!OVO!l$xO#jVO!l$xO#jROe!iOpkOrPO(VTO(YUO(aVO(o[O~O(T=QO~P#$qO!]-]O!^(iX~O!^-_O~O!g-VO#`-UO!]#hX!^#hX~O!]-`O!^(xX~O!^-bO~O!c-cO!d-cO(U!lO~P#$`O!^-fO~P'_On-iO!_'`O~O!Y-nO~Os!{a!b!{a!c!{a!d!{a#T!{a#U!{a#V!{a#W!{a#X!{a#[!{a#]!{a(U!{a(V!{a(Y!{a(e!{a(o!{a~P!#vO!p-sO#`-qO~PChO!c-uO!d-uO(U!lO~PDWOa%nO#`-qO'z%nO~Oa%nO!g#vO#`-qO'z%nO~Oa%nO!g#vO!p-sO#`-qO'z%nO(r'pO~O(P'xO(Q'xO(R-zO~Ov-{O~O!Y'Wa!]'Wa~P!:tO![.PO!Y'WX!]'WX~P%[O!](VO!Y(ha~O!Y(ha~PHRO!](^O!Y(va~O!S%hO![.TO!_%iO(T%gO!Y'^X!]'^X~O#`.VO!](ta!k(taa(ta'z(ta~O!g#vO~P#,wO!](jO!k(sa~O!S%hO!_%iO#j.ZO(T%gO~Op.`O!S%hO![.]O!_%iO!|]O#i._O#j.]O(T%gO!]'aX!k'aX~OR.dO!l#xO~Oh%VOn.gO!_'`O%i.fO~Oa#ci!]#ci'z#ci'w#ci!Y#ci!k#civ#ci!_#ci%i#ci!g#ci~P!:tOn>]O!Q*OO'y*PO(y$}O(z%PO~O#k#_aa#_a#`#_a'z#_a!]#_a!k#_a!_#_a!Y#_a~P#/sO#k(`XP(`XR(`X[(`Xa(`Xj(`Xr(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X'z(`X(a(`X(r(`X!k(`X!Y(`X'w(`Xv(`X!_(`X%i(`X!g(`X~P!6kO!].tO!k(kX~P!:tO!k.wO~O!Y.yO~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mia#mij#mir#mi!]#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#n#mi~P#3cO#n$OO~P#3cOP$[OR#zOr$aO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO[#mia#mij#mi!]#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#r#mi~P#6QO#r$QO~P#6QOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO(aVOa#mi!]#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#v#mi~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO(aVO(z#}Oa#mi!]#mi#z#mi#{#mi'z#mi(r#mi(y#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#x$UO~P#;VO#x#mi~P#;VO#v$SO~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO(aVO(y#|O(z#}Oa#mi!]#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#z#mi~P#={O#z$WO~P#={OP]XR]X[]Xj]Xr]X!Q]X!S]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X!]]X!^]X~O$O]X~P#@jOP$[OR#zO[]O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P#EyO!]/POg(pX~P!1WOg/RO~Oa$Pi!]$Pi'z$Pi'w$Pi!Y$Pi!k$Piv$Pi!_$Pi%i$Pi!g$Pi~P!:tO$]/SO$_/SO~O$]/TO$_/TO~O!g)hO#`/UO!_$cX$Z$cX$]$cX$_$cX$f$cX~O![/VO~O!_)kO$Z/XO$])jO$_)jO$f/YO~O!]VO!l$xO#j^O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P&,QO#S$dOP(`XR(`X[(`Xj(`Xn(`Xr(`X!Q(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X$O(`X'y(`X(a(`X(r(`X(y(`X(z(`X!](`X!^(`X~O$O$Pi!]$Pi!^$Pi~P#BwO$O!ri!^!ri~P$+oOg']a!]']a~P!1WO!^7nO~O!]'da!^'da~P#BwO!Y7oO~P#/sO!g#vO(r'pO!]'ea!k'ea~O!]/pO!k)Oi~O!]/pO!g#vO!k)Oi~Og$|q!]$|q#`$|q$O$|q~P!1WO!Y'ga!]'ga~P#/sO!g7vO~O!]/yO!Y)Pi~P#/sO!]/yO!Y)Pi~O!Y7yO~Oh%VOr8OO!l%eO(r'pO~Oj8QO!g#vO~Or8TO!g#vO(r'pO~O!Q*OO'y*PO(z%POn'ja(y'ja!]'ja#`'ja~Og'ja$O'ja~P&5RO!Q*OO'y*POn'la(y'la(z'la!]'la#`'la~Og'la$O'la~P&5tOg(_q!](_q~P!1WO#`8VOg(_q!](_q~P!1WO!Y8WO~Og%Oq!]%Oq#`%Oq$O%Oq~P!1WOa$oy!]$oy'z$oy'w$oy!Y$oy!k$oyv$oy!_$oy%i$oy!g$oy~P!:tO!g6rO~O!]5[O!_)Qa~O!_'`OP$TaR$Ta[$Taj$Tar$Ta!Q$Ta!S$Ta!]$Ta!l$Ta!p$Ta#R$Ta#n$Ta#o$Ta#p$Ta#q$Ta#r$Ta#s$Ta#t$Ta#u$Ta#v$Ta#x$Ta#z$Ta#{$Ta(a$Ta(r$Ta(y$Ta(z$Ta~O%i7WO~P&8fO%^8[Oa%[i!_%[i'z%[i!]%[i~Oa#cy!]#cy'z#cy'w#cy!Y#cy!k#cyv#cy!_#cy%i#cy!g#cy~P!:tO[8^O~Ob8`O(T+qO(VTO(YUO~O!]1TO!^)Xi~O`8dO~O(e(|O!]'pX!^'pX~O!]5uO!^)Ua~O!^8nO~P%;eO(o!sO~P$&YO#[8oO~O!_1oO~O!_1oO%i8qO~On8tO!_1oO%i8qO~O[8yO!]'sa!^'sa~O!]1zO!^)Vi~O!k8}O~O!k9OO~O!k9RO~O!k9RO~P%[Oa9TO~O!g9UO~O!k9VO~O!](wi!^(wi~P#BwOa%nO#`9_O'z%nO~O!](ty!k(tya(ty'z(ty~P!:tO!](jO!k(sy~O%i9bO~P&8fO!_'`O%i9bO~O#k$|qP$|qR$|q[$|qa$|qj$|qr$|q!S$|q!]$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q'z$|q(a$|q(r$|q!k$|q!Y$|q'w$|q#`$|qv$|q!_$|q%i$|q!g$|q~P#/sO#k'jaP'jaR'ja['jaa'jaj'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja'z'ja(a'ja(r'ja!k'ja!Y'ja'w'jav'ja!_'ja%i'ja!g'ja~P&5RO#k'laP'laR'la['laa'laj'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la'z'la(a'la(r'la!k'la!Y'la'w'lav'la!_'la%i'la!g'la~P&5tO#k%OqP%OqR%Oq[%Oqa%Oqj%Oqr%Oq!S%Oq!]%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq'z%Oq(a%Oq(r%Oq!k%Oq!Y%Oq'w%Oq#`%Oqv%Oq!_%Oq%i%Oq!g%Oq~P#/sO!]'Yi!k'Yi~P!:tO$O#cq!]#cq!^#cq~P#BwO(y$}OP%aaR%aa[%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa$O%aa(a%aa(r%aa!]%aa!^%aa~On%aa!Q%aa'y%aa(z%aa~P&IyO(z%POP%caR%ca[%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca$O%ca(a%ca(r%ca!]%ca!^%ca~On%ca!Q%ca'y%ca(y%ca~P&LQOn>^O!Q*OO'y*PO(z%PO~P&IyOn>^O!Q*OO'y*PO(y$}O~P&LQOR0kO!Q0kO!S0lO#S$dOP}a[}aj}an}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a$O}a'y}a(a}a(r}a(y}a(z}a!]}a!^}a~O!Q*OO'y*POP$saR$sa[$saj$san$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa$O$sa(a$sa(r$sa(y$sa(z$sa!]$sa!^$sa~O!Q*OO'y*POP$uaR$ua[$uaj$uan$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua$O$ua(a$ua(r$ua(y$ua(z$ua!]$ua!^$ua~On>^O!Q*OO'y*PO(y$}O(z%PO~OP%TaR%Ta[%Taj%Tar%Ta!S%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta$O%Ta(a%Ta(r%Ta!]%Ta!^%Ta~P''VO$O$mq!]$mq!^$mq~P#BwO$O$oq!]$oq!^$oq~P#BwO!^9oO~O$O9pO~P!1WO!g#vO!]'ei!k'ei~O!g#vO(r'pO!]'ei!k'ei~O!]/pO!k)Oq~O!Y'gi!]'gi~P#/sO!]/yO!Y)Pq~Or9wO!g#vO(r'pO~O[9yO!Y9xO~P#/sO!Y9xO~Oj:PO!g#vO~Og(_y!](_y~P!1WO!]'na!_'na~P#/sOa%[q!_%[q'z%[q!]%[q~P#/sO[:UO~O!]1TO!^)Xq~O`:YO~O#`:ZO!]'pa!^'pa~O!]5uO!^)Ui~P#BwO!S:]O~O!_1oO%i:`O~O(VTO(YUO(e:eO~O!]1zO!^)Vq~O!k:hO~O!k:iO~O!k:jO~O!k:jO~P%[O#`:mO!]#hy!^#hy~O!]#hy!^#hy~P#BwO%i:rO~P&8fO!_'`O%i:rO~O$O#|y!]#|y!^#|y~P#BwOP$|iR$|i[$|ij$|ir$|i!S$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i$O$|i(a$|i(r$|i!]$|i!^$|i~P''VO!Q*OO'y*PO(z%POP'iaR'ia['iaj'ian'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia$O'ia(a'ia(r'ia(y'ia!]'ia!^'ia~O!Q*OO'y*POP'kaR'ka['kaj'kan'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka$O'ka(a'ka(r'ka(y'ka(z'ka!]'ka!^'ka~O(y$}OP%aiR%ai[%aij%ain%air%ai!Q%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai$O%ai'y%ai(a%ai(r%ai(z%ai!]%ai!^%ai~O(z%POP%ciR%ci[%cij%cin%cir%ci!Q%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci$O%ci'y%ci(a%ci(r%ci(y%ci!]%ci!^%ci~O$O$oy!]$oy!^$oy~P#BwO$O#cy!]#cy!^#cy~P#BwO!g#vO!]'eq!k'eq~O!]/pO!k)Oy~O!Y'gq!]'gq~P#/sOr:|O!g#vO(r'pO~O[;QO!Y;PO~P#/sO!Y;PO~Og(_!R!](_!R~P!1WOa%[y!_%[y'z%[y!]%[y~P#/sO!]1TO!^)Xy~O!]5uO!^)Uq~O(T;XO~O!_1oO%i;[O~O!k;_O~O%i;dO~P&8fOP$|qR$|q[$|qj$|qr$|q!S$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q$O$|q(a$|q(r$|q!]$|q!^$|q~P''VO!Q*OO'y*PO(z%POP'jaR'ja['jaj'jan'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja$O'ja(a'ja(r'ja(y'ja!]'ja!^'ja~O!Q*OO'y*POP'laR'la['laj'lan'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la$O'la(a'la(r'la(y'la(z'la!]'la!^'la~OP%OqR%Oq[%Oqj%Oqr%Oq!S%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq$O%Oq(a%Oq(r%Oq!]%Oq!^%Oq~P''VOg%e!Z!]%e!Z#`%e!Z$O%e!Z~P!1WO!Y;hO~P#/sOr;iO!g#vO(r'pO~O[;kO!Y;hO~P#/sO!]'pq!^'pq~P#BwO!]#h!Z!^#h!Z~P#BwO#k%e!ZP%e!ZR%e!Z[%e!Za%e!Zj%e!Zr%e!Z!S%e!Z!]%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z'z%e!Z(a%e!Z(r%e!Z!k%e!Z!Y%e!Z'w%e!Z#`%e!Zv%e!Z!_%e!Z%i%e!Z!g%e!Z~P#/sOr;tO!g#vO(r'pO~O!Y;uO~P#/sOr;|O!g#vO(r'pO~O!Y;}O~P#/sOP%e!ZR%e!Z[%e!Zj%e!Zr%e!Z!S%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z$O%e!Z(a%e!Z(r%e!Z!]%e!Z!^%e!Z~P''VOrROe!iOpkOrPO(T)]O(VTO(YUO(aVO(o[O~O!]WO!l$xO#jgPPP!>oI[PPPPPPPPP!BOP!C]PPI[!DnPI[PI[I[I[I[I[PI[!FQP!I[P!LbP!Lf!Lp!Lt!LtP!IXP!Lx!LxP#!OP#!SI[PI[#!Y#%_CjA^PA^PA^A^P#&lA^A^#)OA^#+vA^#.SA^A^#.r#1W#1W#1]#1f#1W#1qPP#1WPA^#2ZA^#6YA^A^6mPPP#:_PPP#:x#:xP#:xP#;`#:xPP#;fP#;]P#;]#;y#;]#P#>V#>]#>k#>q#>{#?R#?]#?c#?s#?y#@k#@}#AT#AZ#Ai#BO#Cs#DR#DY#Et#FS#Gt#HS#HY#H`#Hf#Hp#Hv#H|#IW#Ij#IpPPPPPPPPPPP#IvPPPPPPP#Jk#Mx$ b$ i$ qPPP$']P$'f$*_$0x$0{$1O$1}$2Q$2X$2aP$2g$2jP$3W$3[$4S$5b$5g$5}PP$6S$6Y$6^$6a$6e$6i$7e$7|$8e$8i$8l$8o$8y$8|$9Q$9UR!|RoqOXst!Z#d%m&r&t&u&w,s,x2[2_Y!vQ'`-e1o5{Q%tvQ%|yQ&T|Q&j!VS'W!e-]Q'f!iS'l!r!yU*k$|*Z*oQ+o%}S+|&V&WQ,d&dQ-c'_Q-m'gQ-u'mQ0[*qQ1b,OQ1y,eR<{SU+P%]S!S!nQ!r!v!y!z$|'W'_'`'l'm'n*k*o*q*r-]-c-e-u0[0_1o5{5}%[$ti#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;kP>X>Y>]>^Q&X|Q'U!eS'[%i-`Q+t&PQ,P&WQ,f&gQ0n+SQ1Y+uQ1_+{Q2Q,jQ2R,kQ5f1TQ5o1aQ6[1zQ6_1|Q6`2PQ8`5gQ8c5lQ8|6bQ:X8dQ:f8yQ;V:YR<}*ZrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R,h&k&z^OPXYstuvwz!Z!`!g!j!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'b'r(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mR>S[#]WZ#W#Z'X(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ%wxQ%{yW&Q|&V&W,OQ&_!TQ'c!hQ'e!iQ(q#sS+n%|%}Q+r&PQ,_&bQ,c&dS-l'f'gQ.i(rQ1R+oQ1X+uQ1Z+vQ1^+zQ1t,`S1x,d,eQ2|-mQ5e1TQ5i1WQ5n1`Q6Z1yQ8_5gQ8b5kQ8f5pQ:T8^R;T:U!U$zi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y!^%yy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{Q+h%wQ,T&[Q,W&]Q,b&dQ.h(qQ1s,_U1w,c,d,eQ3e.iQ6U1tS6Y1x1yQ8x6Z#f>T#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^o>UPS&[!Q&iQ&]!RQ&^!SU*}%[%d=sR,R&Y%]%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;kP>X>Y>]>^T)z$u){V+P%]S$i$^c#Y#e%q%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.|.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`SQ'Y!eR2q-]!W!nQ!e!r!v!y!z$|'W'_'`'l'm'n*Z*k*o*q*r-]-c-e-u0[0_1o5{5}R1l,ZnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&y!^Q'v!xS(s#u<^Q+l%zQ,]&_Q,^&aQ-j'dQ-w'oS.r(x=PS0q+X=ZQ1P+mQ1n,[Q2c,zQ2e,{Q2m-WQ2z-kQ2}-oS5Y0r=eQ5a1QS5d1S=fQ6t2oQ6x2{Q6}3SQ8]5bQ9Y6vQ9Z6yQ9^7OR:l9V$d$]c#Y#e%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`SS#q]SU$fd)_,mS(p#p'iU*v%R(w4OU0m+O.n7gQ5^0xQ7V3`Q9d7YR:s9em!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}Q't!uS(f#g2US-s'k'wQ/s*]Q0R*jQ3U-vQ4f/tQ4r0TQ4s0UQ4x0^Q7r4`S7}4t4vS8R4y4{Q9r7sQ9v7yQ9{8OQ:Q8TS:{9w9xS;g:|;PS;s;h;iS;{;t;uSSR=o>R%^bOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Q%fj!^%xy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{S&Oz!jQ+k%yQ,a&dW1v,b,c,d,eU6X1w1x1yS8w6Y6ZQ:d8x!r=j$Z$n'X)s-U-X/V2p4T5w6s:Z:mSQ=t>QR=u>R%QeOPXYstuvw!Z!`!g!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Y#bWZ#W#Z(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ,n&o!p=k$Z$n)s-U-X/V2p4T5w6s:Z:mSR=n'XU']!e%i*ZR2s-`%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:mSQ,m&oQ0x+gQ3`.gQ7Y3dR9e7[!b$Tc#Y%q(S(Y(t(y)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:oS)^)q-Z.|2k2n3p4P4X6u7b7k7l8k9X9g9m9n;W;`=vQ>X>ZR>Y>['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mSS$oh$pR4U/U'XgOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mST$kf$qQ$ifS)j$l)nR)v$qT$jf$qT)l$l)n'XhOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mST$oh$pQ$rhR)u$p%^jOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_!s>Q$Z$n'X)s-U-X/V2p4T5w6s:Z:mS#glOPXZst!Z!`!o#S#d#o#{$n%m&k&n&o&r&t&u&w&{'T'b)O)s*i+]+g,p,s,x-i.g/V/n0]0l1r2S2T2V2X2[2_2a3d4T4z6T6e6f6i7[8t9T!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^Q+T%aQ/c*Oo4OP>X>YQ*c$zU*l$|*Z*oQ+U%bQ0W*m#f=q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^n=rTQ=x>UQ=y>VR=z>W!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^o4OP>X>Y>]>^Q,U&]Q1h,WQ5s1gR8h5tV*n$|*Z*oU*n$|*Z*oT5z1o5{S0P*i/nQ4w0]T8S4z:]Q+j%xQ0V*lQ1O+kQ1u,aQ6W1vQ8v6XQ:c8wR;^:d!U%Oi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Yx*R$v)e*S*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>OS0`*t0a#f]>^nZ>[`=T3}7c7f7j9h:t:w;yS=_.l3iT=`7e9k!U%Qi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y|*T$v)e*U*t+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>OS0b*u0c#f]>^nZ>[d=V3}7d7e7j9h9i:t:u:w;yS=a.m3jT=b7f9lrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q&f!UR,p&ornOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R&f!UQ,Y&^R1d,RsnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q1p,_S6R1s1tU8p6P6Q6US:_8r8sS;Y:^:aQ;m;ZR;w;nQ&m!VR,i&iR6_1|R:f8yW&Q|&V&W,OR1Z+vQ&r!WR,s&sR,y&xT2],x2_R,}&yQ,|&yR2f,}Q'y!{R-y'ySsOtQ#dXT%ps#dQ#OTR'{#OQ#RUR'}#RQ){$uR/`){Q#UVR(Q#UQ#XWU(W#X(X.QQ(X#YR.Q(YQ-^'YR2r-^Q.u(yS3m.u3nR3n.vQ-e'`R2v-eY!rQ'`-e1o5{R'j!rQ/Q)eR4S/QU#_W%h*YU(_#_(`.RQ(`#`R.R(ZQ-a']R2t-at`OXst!V!Z#d%m&i&k&r&t&u&w,s,x2[2_S#hZ%eU#r`#h.[R.[(jQ(k#jQ.X(gW.a(k.X3X7RQ3X.YR7R3YQ)n$lR/W)nQ$phR)t$pQ$`cU)a$`-|O>Z>[Q/z*eU4k/z4m7xQ4m/|R7x4lS*o$|*ZR0Y*ox*S$v)e*t*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>O!d.j(u)c*[*e.l.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/h*S.j7ca7c3}7e7f7j9h:t:w;yQ0a*tQ3i.lU4}0a3i9kR9k7e|*U$v)e*t*u+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>O!h.k(u)c*[*e.l.m.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/j*U.k7de7d3}7e7f7j9h9i:t:u:w;yQ0c*uQ3j.mU5P0c3j9lR9l7fQ*z%UR0g*zQ5]0vR8Y5]Q+_%kR0u+_Q5v1jS8j5v:[R:[8kQ,[&_R1m,[Q5{1oR8m5{Q1{,fS6]1{8zR8z6_Q1U+rW5h1U5j8a:VQ5j1XQ8a5iR:V8bQ+w&QR1[+wQ2_,xR6m2_YrOXst#dQ&v!ZQ+a%mQ,r&rQ,t&tQ,u&uQ,w&wQ2Y,sS2],x2_R6l2[Q%opQ&z!_Q&}!aQ'P!bQ'R!cQ'q!uQ+`%lQ+l%zQ,Q&XQ,h&mQ-P&|W-p'k's't'wQ-w'oQ0X*nQ1P+mQ1c,PS2O,i,lQ2g-OQ2h-RQ2i-SQ2}-oW3P-r-s-v-xQ5a1QQ5m1_Q5q1eQ6V1uQ6a2QQ6k2ZU6z3O3R3UQ6}3SQ8]5bQ8e5oQ8g5rQ8l5zQ8u6WQ8{6`S9[6{7PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:Mb,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[_b],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rp)wU(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)rp*^P;=`<%l)r'[*dP;=`<%l(r#S*nX(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g#S+^P;=`<%l*g(n+dP;=`<%l%Z07[+rq$i&j(Wp(Z!b'|0/lOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p$f%Z$f$g+g$g#BY%Z#BY#BZ+g#BZ$IS%Z$IS$I_+g$I_$JT%Z$JT$JU+g$JU$KV%Z$KV$KW+g$KW&FU%Z&FU&FV+g&FV;'S%Z;'S;=`+a<%l?HT%Z?HT?HU+g?HUO%Z07[.ST(X#S$i&j'}0/lO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c07[.n_$i&j(Wp(Z!b'}0/lOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)3p/x`$i&j!p),Q(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW1V`#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`2X!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW2d_#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At3l_(V':f$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k(^4r_$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k&z5vX$i&jOr5qrs6cs!^5q!^!_6y!_#o5q#o#p6y#p;'S5q;'S;=`7h<%lO5q&z6jT$d`$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c`6|TOr6yrs7]s;'S6y;'S;=`7b<%lO6y`7bO$d``7eP;=`<%l6y&z7kP;=`<%l5q(^7w]$d`$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!r8uZ(Z!bOY8pYZ6yZr8prs9hsw8pwx6yx#O8p#O#P6y#P;'S8p;'S;=`:R<%lO8p!r9oU$d`(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!r:UP;=`<%l8p(^:[P;=`<%l4k%9[:hh$i&j(Wp(Z!bOY%ZYZ&cZq%Zqr`#P#o`x!^=^!^!_?q!_#O=^#O#P>`#P#o=^#o#p?q#p;'S=^;'S;=`@h<%lO=^&n>gXWS$i&jOY>`YZ&cZ!^>`!^!_?S!_#o>`#o#p?S#p;'S>`;'S;=`?k<%lO>`S?XSWSOY?SZ;'S?S;'S;=`?e<%lO?SS?hP;=`<%l?S&n?nP;=`<%l>`!f?xWWS(Z!bOY?qZw?qwx?Sx#O?q#O#P?S#P;'S?q;'S;=`@b<%lO?q!f@eP;=`<%l?q(Q@kP;=`<%l=^'`@w]WS$i&j(WpOY@nYZ&cZr@nrs>`s!^@n!^!_Ap!_#O@n#O#P>`#P#o@n#o#pAp#p;'S@n;'S;=`Bg<%lO@ntAwWWS(WpOYApZrAprs?Ss#OAp#O#P?S#P;'SAp;'S;=`Ba<%lOAptBdP;=`<%lAp'`BjP;=`<%l@n#WBvYWS(Wp(Z!bOYBmZrBmrs?qswBmwxApx#OBm#O#P?S#P;'SBm;'S;=`Cf<%lOBm#WCiP;=`<%lBm(rCoP;=`<%l^!Q^$i&j!X7`OY!=yYZ&cZ!P!=y!P!Q!>|!Q!^!=y!^!_!@c!_!}!=y!}#O!CW#O#P!Dy#P#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y|#X#Z&c#Z#[!>|#[#]&c#]#^!>|#^#a&c#a#b!>|#b#g&c#g#h!>|#h#i&c#i#j!>|#j#k!>|#k#m&c#m#n!>|#n#o&c#p;'S&c;'S;=`&w<%lO&c7`!@hX!X7`OY!@cZ!P!@c!P!Q!AT!Q!}!@c!}#O!Ar#O#P!Bq#P;'S!@c;'S;=`!CQ<%lO!@c7`!AYW!X7`#W#X!AT#Z#[!AT#]#^!AT#a#b!AT#g#h!AT#i#j!AT#j#k!AT#m#n!AT7`!AuVOY!ArZ#O!Ar#O#P!B[#P#Q!@c#Q;'S!Ar;'S;=`!Bk<%lO!Ar7`!B_SOY!ArZ;'S!Ar;'S;=`!Bk<%lO!Ar7`!BnP;=`<%l!Ar7`!BtSOY!@cZ;'S!@c;'S;=`!CQ<%lO!@c7`!CTP;=`<%l!@c^!Ezl$i&j(Z!b!X7`OY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#W&}#W#X!Eq#X#Z&}#Z#[!Eq#[#]&}#]#^!Eq#^#a&}#a#b!Eq#b#g&}#g#h!Eq#h#i&}#i#j!Eq#j#k!Eq#k#m&}#m#n!Eq#n#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}8r!GyZ(Z!b!X7`OY!GrZw!Grwx!@cx!P!Gr!P!Q!Hl!Q!}!Gr!}#O!JU#O#P!Bq#P;'S!Gr;'S;=`!J|<%lO!Gr8r!Hse(Z!b!X7`OY'}Zw'}x#O'}#P#W'}#W#X!Hl#X#Z'}#Z#[!Hl#[#]'}#]#^!Hl#^#a'}#a#b!Hl#b#g'}#g#h!Hl#h#i'}#i#j!Hl#j#k!Hl#k#m'}#m#n!Hl#n;'S'};'S;=`(f<%lO'}8r!JZX(Z!bOY!JUZw!JUwx!Arx#O!JU#O#P!B[#P#Q!Gr#Q;'S!JU;'S;=`!Jv<%lO!JU8r!JyP;=`<%l!JU8r!KPP;=`<%l!Gr>^!KZ^$i&j(Z!bOY!KSYZ&cZw!KSwx!CWx!^!KS!^!_!JU!_#O!KS#O#P!DR#P#Q!^!LYP;=`<%l!KS>^!L`P;=`<%l!_#c#d#Bq#d#l%Z#l#m#Es#m#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#>j_$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#?rd$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#A]f$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Bzc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Dbe$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#E|g$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Gpi$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x#Il_!g$b$i&j$O)Lv(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)[#Jv_al$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f#LS^h#)`#R-v$?V_!^(CdvBr$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z?O$@a_!q7`$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$Aq|$i&j(Wp(Z!b'|0/l$]#t(T,2j(e$I[OX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[Lb,Yb,Eb,zb,2,3,4,5,6,7,8,9,10,11,12,13,14,jb,new Pr("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new Pr("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>Wb[n]||-1},{term:343,get:n=>Vb[n]||-1},{term:95,get:n=>Bb[n]||-1}],tokenPrec:15201}),eO=[xe("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),xe("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),xe("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),xe("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),xe("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),xe(`try { +`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=kr.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new B(this.parser.nodeSet.types[e],bi,bi,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements($o(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?$u(this.ranges,0,e.topNode,this.ranges[0].from,this.reusePlaceholders):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=$o(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(x.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?z(this.parser.getNodeType(e),t,i,r):new Tu(e,t)}get buffer(){return new vu(this.parser.nodeSet)}}function $u(n,e,t,i,r){let s=n[e].to,o=[],l=[],a=t.from+i;function h(c,f){for(;f?c>=s:c>s;){let u=n[e+1].from-s;i+=u,c+=u,e++,s=n[e].to}}for(let c=t.firstChild;c;c=c.nextSibling){h(c.from+i,!0);let f=c.from+i,u,O=r.get(c.tree);O?u=O:c.to+i>s?(u=$u(n,e,c,i,r),h(c.to+i,!1)):u=c.toTree(),o.push(u),l.push(f-a)}return h(t.to+i,!1),new B(t.type,o,l,t.to+i-a,t.tree?t.tree.propValues:void 0)}class qr extends Fo{constructor(e,t,i,r,s,o,l,a,h){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=s,this.skipContextMarkup=o,this.inlineParsers=l,this.inlineNames=a,this.wrappers=h,this.nodeTypes=Object.create(null);for(let c of e.types)this.nodeTypes[c.name]=c.id}createParse(e,t,i){let r=new xS(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}configure(e){let t=wo(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,s=this.blockParsers.slice(),o=this.leafBlockParsers.slice(),l=this.blockNames.slice(),a=this.inlineParsers.slice(),h=this.inlineNames.slice(),c=this.endLeafBlock.slice(),f=this.wrappers;if(Mi(t.defineNodes)){r=Object.assign({},r);let u=i.types.slice(),O;for(let d of t.defineNodes){let{name:p,block:g,composite:S,style:b}=typeof d=="string"?{name:d}:d;if(u.some(k=>k.name==p))continue;S&&(r[u.length]=(k,v,T)=>S(v,T,k.value));let Q=u.length,w=S?["Block","BlockContext"]:g?Q>=x.ATXHeading1&&Q<=x.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;u.push(se.define({id:Q,name:p,props:w&&[[R.group,w]]})),b&&(O||(O={}),Array.isArray(b)||b instanceof Ze?O[p]=b:Object.assign(O,b))}i=new gn(u),O&&(i=i.extend(xi(O)))}if(Mi(t.props)&&(i=i.extend(...t.props)),Mi(t.remove))for(let u of t.remove){let O=this.blockNames.indexOf(u),d=this.inlineNames.indexOf(u);O>-1&&(s[O]=o[O]=void 0),d>-1&&(a[d]=void 0)}if(Mi(t.parseBlock))for(let u of t.parseBlock){let O=l.indexOf(u.name);if(O>-1)s[O]=u.parse,o[O]=u.leaf;else{let d=u.before?In(l,u.before):u.after?In(l,u.after)+1:l.length-1;s.splice(d,0,u.parse),o.splice(d,0,u.leaf),l.splice(d,0,u.name)}u.endLeaf&&c.push(u.endLeaf)}if(Mi(t.parseInline))for(let u of t.parseInline){let O=h.indexOf(u.name);if(O>-1)a[O]=u.parse;else{let d=u.before?In(h,u.before):u.after?In(h,u.after)+1:h.length-1;a.splice(d,0,u.parse),h.splice(d,0,u.name)}}return t.wrap&&(f=f.concat(t.wrap)),new qr(i,s,o,l,c,r,a,h,f)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new pl(this,e,t);e:for(let r=t;r=0){r=l;continue e}}r++}return i.resolveMarkers(0)}}function Mi(n){return n!=null&&n.length>0}function wo(n){if(!Array.isArray(n))return n;if(n.length==0)return null;let e=wo(n[0]);if(n.length==1)return e;let t=wo(n.slice(1));if(!t||!e)return e||t;let i=(o,l)=>(o||bi).concat(l||bi),r=e.wrap,s=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?s?(o,l,a,h)=>r(s(o,l,a,h),l,a,h):r:s}}function In(n,e){let t=n.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}let Pu=[se.none];for(let n=1,e;e=x[n];n++)Pu[n]=se.define({id:n,name:e,props:n>=x.Escape?[]:[[R.group,n in pu?["Block","BlockContext"]:["Block","LeafBlock"]]],top:e=="Document"});const bi=[];class vu{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return this.content.push(e,t,i,4+r*4),this}writeElements(e,t=0){for(let i of e)i.writeTo(this,t);return this}finish(e,t){return B.build({buffer:this.content,nodeSet:this.nodeSet,reused:this.nodes,topID:e,length:t})}}let an=class{constructor(e,t,i,r=bi){this.type=e,this.from=t,this.to=i,this.children=r}writeTo(e,t){let i=e.content.length;e.writeElements(this.children,t),e.content.push(this.type,this.from+t,this.to+t,e.content.length+4-i)}toTree(e){return new vu(e).writeElements(this.children,-this.from).finish(this.type,this.to-this.from)}};class Tu{constructor(e,t){this.tree=e,this.from=t}get to(){return this.from+this.tree.length}get type(){return this.tree.type.id}get children(){return bi}writeTo(e,t){e.nodes.push(this.tree),e.content.push(e.nodes.length-1,this.from+t,this.to+t,-1)}toTree(){return this.tree}}function z(n,e,t,i){return new an(n,e,t,i)}const Cu={resolve:"Emphasis",mark:"EmphasisMark"},Zu={resolve:"Emphasis",mark:"EmphasisMark"},Et={},wr={};class Ce{constructor(e,t,i,r){this.type=e,this.from=t,this.to=i,this.side=r}}const ih="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";let hn=/[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\u2010-\u2027]/;try{hn=new RegExp("[\\p{S}|\\p{P}]","u")}catch{}const Ss={Escape(n,e,t){if(e!=92||t==n.end-1)return-1;let i=n.char(t+1);for(let r=0;r]+|[a-z\d.!#$%&'*+/=?^_`{|}~-]+@[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?)*)>/i.exec(i);if(r)return n.append(z(x.Autolink,t,t+1+r[0].length,[z(x.LinkMark,t,t+1),z(x.URL,t+1,t+r[0].length),z(x.LinkMark,t+r[0].length,t+1+r[0].length)]));let s=/^!--[^>](?:-[^-]|[^-])*?-->/i.exec(i);if(s)return n.append(z(x.Comment,t,t+1+s[0].length));let o=/^\?[^]*?\?>/.exec(i);if(o)return n.append(z(x.ProcessingInstruction,t,t+1+o[0].length));let l=/^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(i);return l?n.append(z(x.HTMLTag,t,t+1+l[0].length)):-1},Emphasis(n,e,t){if(e!=95&&e!=42)return-1;let i=t+1;for(;n.char(i)==e;)i++;let r=n.slice(t-1,t),s=n.slice(i,i+1),o=hn.test(r),l=hn.test(s),a=/\s|^$/.test(r),h=/\s|^$/.test(s),c=!h&&(!l||a||o),f=!a&&(!o||h||l),u=c&&(e==42||!f||o),O=f&&(e==42||!c||l);return n.append(new Ce(e==95?Cu:Zu,t,i,(u?1:0)|(O?2:0)))},HardBreak(n,e,t){if(e==92&&n.char(t+1)==10)return n.append(z(x.HardBreak,t,t+2));if(e==32){let i=t+1;for(;n.char(i)==32;)i++;if(n.char(i)==10&&i>=t+2)return n.append(z(x.HardBreak,t,i+1))}return-1},Link(n,e,t){return e==91?n.append(new Ce(Et,t,t+1,1)):-1},Image(n,e,t){return e==33&&n.char(t+1)==91?n.append(new Ce(wr,t,t+2,1)):-1},LinkEnd(n,e,t){if(e!=93)return-1;for(let i=n.parts.length-1;i>=0;i--){let r=n.parts[i];if(r instanceof Ce&&(r.type==Et||r.type==wr)){if(!r.side||n.skipSpace(r.to)==t&&!/[(\[]/.test(n.slice(t+1,t+2)))return n.parts[i]=null,-1;let s=n.takeContent(i),o=n.parts[i]=kS(n,s,r.type==Et?x.Link:x.Image,r.from,t+1);if(r.type==Et)for(let l=0;le?z(x.URL,e+t,s+t):s==n.length?null:!1}}function Au(n,e,t){let i=n.charCodeAt(e);if(i!=39&&i!=34&&i!=40)return!1;let r=i==40?41:i;for(let s=e+1,o=!1;s=this.end?-1:this.text.charCodeAt(e-this.offset)}get end(){return this.offset+this.text.length}slice(e,t){return this.text.slice(e-this.offset,t-this.offset)}append(e){return this.parts.push(e),e.to}addDelimiter(e,t,i,r,s){return this.append(new Ce(e,t,i,(r?1:0)|(s?2:0)))}get hasOpenLink(){for(let e=this.parts.length-1;e>=0;e--){let t=this.parts[e];if(t instanceof Ce&&(t.type==Et||t.type==wr))return!0}return!1}addElement(e){return this.append(e)}resolveMarkers(e){for(let i=e;i=e;a--){let p=this.parts[a];if(p instanceof Ce&&p.side&1&&p.type==r.type&&!(s&&(r.side&1||p.side&2)&&(p.to-p.from+o)%3==0&&((p.to-p.from)%3||o%3))){l=p;break}}if(!l)continue;let h=r.type.resolve,c=[],f=l.from,u=r.to;if(s){let p=Math.min(2,l.to-l.from,o);f=l.to-p,u=r.from+p,h=p==1?"Emphasis":"StrongEmphasis"}l.type.mark&&c.push(this.elt(l.type.mark,f,l.to));for(let p=a+1;p=0;t--){let i=this.parts[t];if(i instanceof Ce&&i.type==e&&i.side&1)return t}return null}takeContent(e){let t=this.resolveMarkers(e);return this.parts.length=e,t}getDelimiterAt(e){let t=this.parts[e];return t instanceof Ce?t:null}skipSpace(e){return Ii(this.text,e-this.offset)+this.offset}elt(e,t,i,r){return typeof e=="string"?z(this.parser.getNodeType(e),t,i,r):new Tu(e,t)}}pl.linkStart=Et;pl.imageStart=wr;function $o(n,e){if(!e.length)return n;if(!n.length)return e;let t=n.slice(),i=0;for(let r of e){for(;i(e?e-1:0))return!1;if(this.fragmentEnd<0){let s=this.fragment.to;for(;s>0&&this.input.read(s-1,s)!=` +`;)s--;this.fragmentEnd=s?s-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(R.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),s=e.absoluteLineStart,o=s,l=e.block.children.length,a=o,h=l;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=Mu(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let f=new B(e.parser.nodeSet.types[x.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(f,t.tree),e.addNode(f,c)}if(t.type.is("Block")&&(wS.indexOf(t.type.id)<0?(o=t.to-i,l=e.block.children.length):(o=a,l=h),a=t.to-i,h=e.block.children.length),!t.nextSibling())break}for(;e.block.children.length>l;)e.block.children.pop(),e.block.positions.pop();return o-s}};function Mu(n,e){let t=n;for(let i=1;iDn[n]),Object.keys(Dn).map(n=>wu[n]),Object.keys(Dn),QS,pu,Object.keys(Ss).map(n=>Ss[n]),Object.keys(Ss),[]);function TS(n,e,t){let i=[];for(let r=n.firstChild,s=e;;r=r.nextSibling){let o=r?r.from:t;if(o>s&&i.push({from:s,to:o}),!r)break;s=r.to}return i}function CS(n){let{codeParser:e,htmlParser:t}=n;return{wrap:cf((r,s)=>{let o=r.type.id;if(e&&(o==x.CodeBlock||o==x.FencedCode)){let l="";if(o==x.FencedCode){let h=r.node.getChild(x.CodeInfo);h&&(l=s.read(h.from,h.to))}let a=e(l);if(a)return{parser:a,overlay:h=>h.type.id==x.CodeText,bracketed:o==x.FencedCode}}else if(t&&(o==x.HTMLBlock||o==x.HTMLTag||o==x.CommentBlock))return{parser:t,overlay:TS(r.node,r.from,r.to)};return null})}}const ZS={resolve:"Strikethrough",mark:"StrikethroughMark"},XS={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":m.strikethrough}},{name:"StrikethroughMark",style:m.processingInstruction}],parseInline:[{name:"Strikethrough",parse(n,e,t){if(e!=126||n.char(t+1)!=126||n.char(t+2)==126)return-1;let i=n.slice(t-1,t),r=n.slice(t+2,t+3),s=/\s|^$/.test(i),o=/\s|^$/.test(r),l=hn.test(i),a=hn.test(r);return n.addDelimiter(ZS,t,t+2,!o&&(!a||s||l),!s&&(!l||o||a))},after:"Emphasis"}]};function Ni(n,e,t=0,i,r=0){let s=0,o=!0,l=-1,a=-1,h=!1,c=()=>{i.push(n.elt("TableCell",r+l,r+a,n.parser.parseInline(e.slice(l,a),r+l)))};for(let f=t;f-1)&&s++,o=!1,i&&(l>-1&&c(),i.push(n.elt("TableDelimiter",f+r,f+r+1))),l=a=-1):(h||u!=32&&u!=9)&&(l<0&&(l=f),a=f+1),h=!h&&u==92}return l>-1&&(s++,i&&c()),s}function nh(n,e){for(let t=e;t\s]*\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/;class rh{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&ju.test(r=t.text.slice(t.pos))){let s=[];Ni(e,i.content,0,s,i.start)==Ni(e,r,0)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,s),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];Ni(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}}const AS={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":m.heading}},"TableRow",{name:"TableCell",style:m.content},{name:"TableDelimiter",style:m.processingInstruction}],parseBlock:[{name:"Table",leaf(n,e){return nh(e.content,0)?new rh:null},endLeaf(n,e,t){if(t.parsers.some(r=>r instanceof rh)||!nh(e.text,e.basePos))return!1;let i=n.peekLine();return ju.test(i)&&Ni(n,e.text,e.basePos)==Ni(n,i,e.basePos)},before:"SetextHeading"}]};class RS{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}}const MS={defineNodes:[{name:"Task",block:!0,style:m.list},{name:"TaskMarker",style:m.atom}],parseBlock:[{name:"TaskList",leaf(n,e){return/^\[[ xX]\][ \t]/.test(e.content)&&n.parentType().name=="ListItem"?new RS:null},after:"SetextHeading"}]},sh=/(www\.)|(https?:\/\/)|([\w.+-]{1,100}@)|(mailto:|xmpp:)/gy,oh=/[\w-]+(\.[\w-]+)+(:\d+)?(\/[^\s<]*)?/gy,jS=/[\w-]+\.[\w-]+($|[/:])/,lh=/[\w.+-]+@[\w-]+(\.[\w.-]+)+/gy,ah=/\/[a-zA-Z\d@.]+/gy;function hh(n,e,t,i){let r=0;for(let s=e;s-1)return-1;let i=e+t[0].length;for(;;){let r=n[i-1],s;if(/[?!.,:*_~]/.test(r)||r==")"&&hh(n,e,i,")")>hh(n,e,i,"("))i--;else if(r==";"&&(s=/&(?:#\d+|#x[a-f\d]+|\w+);$/.exec(n.slice(e,i))))i=e+s.index;else break}return i}function ch(n,e){lh.lastIndex=e;let t=lh.exec(n);if(!t)return-1;let i=t[0][t[0].length-1];return i=="_"||i=="-"?-1:e+t[0].length-(i=="."?1:0)}const YS={parseInline:[{name:"Autolink",parse(n,e,t){let i=t-n.offset;if(i&&/\w/.test(n.text[i-1]))return-1;sh.lastIndex=i;let r=sh.exec(n.text),s=-1;if(!r)return-1;if(r[1]||r[2]){if(s=LS(n.text,i+r[0].length),s>-1&&n.hasOpenLink){let o=/([^\[\]]|\[[^\]]*\])*/.exec(n.text.slice(i,s));s=i+o[0].length}}else r[3]?s=ch(n.text,i):(s=ch(n.text,i+r[0].length),s>-1&&r[0]=="xmpp:"&&(ah.lastIndex=s,r=ah.exec(n.text),r&&(s=r.index+r[0].length)));return s<0?-1:(n.addElement(n.elt("URL",t,s+n.offset)),s+n.offset)}}]},ES=[AS,MS,XS,YS];function Lu(n,e,t){return(i,r,s)=>{if(r!=n||i.char(s+1)==n)return-1;let o=[i.elt(t,s,s+1)];for(let l=s+1;lt%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let r=e.parser.context;return new $r(e,[],t,i,i,0,[],0,r?new uh(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,r=e&65535,{parser:s}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[r])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(r,h)}storeNode(e,t,i,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!s||this.pos==i)this.buffer.push(e,t,i,r);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=r}}shift(e,t,i,r){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let s=e,{parser:o}=this.p;this.pos=r;let l=o.stateFlag(s,1);!l&&(r>i||t<=o.maxNode)&&(this.reducePos=r),this.pushState(s,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,r,4)}else this.pos=r,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,r,4)}apply(e,t,i,r){e&65536?this.reduce(e):this.shift(e,t,i,r)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(i,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new $r(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new VS(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let r=[];for(let s=0,o;sa&1&&l==o)||r.push(t[s],o)}t=r}let i=[];for(let r=0;r>19,r=t&65535,s=this.stack.length-i*3;if(s<0||e.getGoto(this.stack[s],r,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(r,s)=>{if(!t.includes(r))return t.push(r),e.allActions(r,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-s;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,s+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}}class uh{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class VS{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class Pr{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new Pr(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new Pr(this.stack,this.pos,this.index)}}function zi(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,r=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),s+=a,l)break;s*=46}t?t[r++]=s:t=new e(s)}return t}class er{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const Oh=new er;class BS{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Oh,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,r=this.rangeIndex,s=this.pos+e;for(;si.to:s>=i.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-i.to,i=o}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,r;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),r=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),r}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Oh,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(i+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return i}}class fi{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;Yu(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}fi.prototype.contextual=fi.prototype.fallback=fi.prototype.extend=!1;class vr{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?zi(e):e}token(e,t){let i=e.pos,r=0;for(;;){let s=e.next<0,o=e.resolveOffset(1,1);if(Yu(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(s||r++,o==null)break;e.reset(o,e.token)}r&&(e.reset(i,e.token),e.acceptToken(this.elseToken,r))}}vr.prototype.contextual=fi.prototype.fallback=fi.prototype.extend=!1;class Ae{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function Yu(n,e,t,i,r,s){let o=0,l=1<0){let d=n[O];if(a.allows(d)&&(e.token.value==-1||e.token.value==d||qS(d,e.token.value,r,s))){e.acceptToken(d);break}}let c=e.next,f=0,u=n[o+2];if(e.next<0&&u>f&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;f>1,d=h+O+(O<<1),p=n[d],g=n[d+1]||65536;if(c=g)f=O+1;else{o=n[d+2],e.advance();continue e}}break}}function dh(n,e,t){for(let i=e,r;(r=n[i])!=65535;i++)if(r==t)return i-e;return-1}function qS(n,e,t,i){let r=dh(t,i,e);return r<0||dh(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class DS{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?ph(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?ph(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(s instanceof B){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}}class IS{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new er)}getActions(e){let t=0,i=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),f.value!=0)){let u=t;if(f.extended>-1&&(t=this.addActions(e,f.extended,f.end,t)),t=this.addActions(e,f.value,f.end,t),!c.extend&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new er,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new er,{pos:i,p:r}=e;return t.start=i,t.end=Math.min(i+1,r.stream.end),t.value=i==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,i){let r=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(r,e),i),e.value>-1){let{parser:s}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,i,r){for(let s=0;se.bufferLength*4?new DS(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],r,s;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{r||(r=[],s=[]),r.push(l);let a=this.tokens.getMainToken(l);s.push(a.value,a.end)}}break}}if(!i.length){let o=r&&US(r);if(o)return Pe&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Pe&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,i);if(o)return Pe&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let f=this.fragments.nodeAt(r);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?s.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(R.contextHash)||0)==c))return e.useNode(f,u),Pe&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(f.type.id)})`),!0;if(!(f instanceof B)||f.children.length==0||f.positions[0]>0)break;let O=f.children[0];if(O instanceof B&&f.positions[0]==0)f=O;else break}}let l=s.stateSlot(e.state,4);if(l>0)return e.reduce(l),Pe&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hr?t.push(d):i.push(d)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return mh(e,t),!0}}runRecovery(e,t,i){let r=null,s=!1;for(let o=0;o ":"";if(l.deadEnd&&(s||(s=!0,l.restart(),Pe&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let O=0;O<10&&f.forceReduce()&&(Pe&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));O++)Pe&&(u=this.stackID(f)+" -> ");for(let O of l.recoverByInsert(a))Pe&&console.log(c+this.stackID(O)+" (via recover-insert)"),this.advanceFully(O,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),Pe&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),mh(l,i)):(!r||r.scoren;class Eu{constructor(e){this.start=e.start,this.shift=e.shift||Qs,this.reduce=e.reduce||Qs,this.reuse=e.reuse||Qs,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Qi extends Fo{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;le.topRules[l][1]),r=[];for(let l=0;l=0)s(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)s(l[h++],a,f);h++}}}this.nodeSet=new gn(t.map((l,a)=>se.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:r[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=sf;let o=zi(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new fi(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let r=new NS(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}getGoto(e,t,i=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],l=o&1,a=r[s++];if(l&&i)return a;for(let h=s+(o>>1);s0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),r=i?t(i):void 0;for(let s=this.stateSlot(e,1);r==null;s+=3){if(this.data[s]==65535)if(this.data[s+1]==1)s=dt(this.data,s+2);else break;r=t(dt(this.data,s+1))}return r}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=dt(this.data,i+2);else break;if((this.data[i+2]&1)==0){let r=this.data[i+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[i],r)}}return t}configure(e){let t=Object.assign(Object.create(Qi.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let r=e.tokenizers.find(s=>s.from==i);return r?r.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,r)=>{let s=e.specializers.find(l=>l.from==i.external);if(!s)return i;let o=Object.assign(Object.assign({},i),{external:s.to});return t.specializers[r]=gh(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(i[o]=!0)}let r=null;for(let s=0;si)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const FS=55,HS=1,KS=56,JS=2,e1=57,t1=3,Sh=4,i1=5,ml=6,zu=7,_u=8,Wu=9,Vu=10,n1=11,r1=12,s1=13,ys=58,o1=14,l1=15,bh=59,Bu=21,a1=23,qu=24,h1=25,Po=27,Du=28,c1=29,f1=32,u1=35,O1=37,d1=38,p1=0,m1=1,g1={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},S1={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},Qh={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function b1(n){return n==45||n==46||n==58||n>=65&&n<=90||n==95||n>=97&&n<=122||n>=161}let yh=null,xh=null,kh=0;function vo(n,e){let t=n.pos+e;if(kh==t&&xh==n)return yh;let i=n.peek(e),r="";for(;b1(i);)r+=String.fromCharCode(i),i=n.peek(++e);return xh=n,kh=t,yh=r?r.toLowerCase():i==Q1||i==y1?void 0:null}const Iu=60,Tr=62,gl=47,Q1=63,y1=33,x1=45;function wh(n,e){this.name=n,this.parent=e}const k1=[ml,Vu,zu,_u,Wu],w1=new Eu({start:null,shift(n,e,t,i){return k1.indexOf(e)>-1?new wh(vo(i,1)||"",n):n},reduce(n,e){return e==Bu&&n?n.parent:n},reuse(n,e,t,i){let r=e.type.id;return r==ml||r==O1?new wh(vo(i,1)||"",n):n},strict:!1}),$1=new Ae((n,e)=>{if(n.next!=Iu){n.next<0&&e.context&&n.acceptToken(ys);return}n.advance();let t=n.next==gl;t&&n.advance();let i=vo(n,0);if(i===void 0)return;if(!i)return n.acceptToken(t?l1:o1);let r=e.context?e.context.name:null;if(t){if(i==r)return n.acceptToken(n1);if(r&&S1[r])return n.acceptToken(ys,-2);if(e.dialectEnabled(p1))return n.acceptToken(r1);for(let s=e.context;s;s=s.parent)if(s.name==i)return;n.acceptToken(s1)}else{if(i=="script")return n.acceptToken(zu);if(i=="style")return n.acceptToken(_u);if(i=="textarea")return n.acceptToken(Wu);if(g1.hasOwnProperty(i))return n.acceptToken(Vu);r&&Qh[r]&&Qh[r][i]?n.acceptToken(ys,-1):n.acceptToken(ml)}},{contextual:!0}),P1=new Ae(n=>{for(let e=0,t=0;;t++){if(n.next<0){t&&n.acceptToken(bh);break}if(n.next==x1)e++;else if(n.next==Tr&&e>=2){t>=3&&n.acceptToken(bh,-2);break}else e=0;n.advance()}});function v1(n){for(;n;n=n.parent)if(n.name=="svg"||n.name=="math")return!0;return!1}const T1=new Ae((n,e)=>{if(n.next==gl&&n.peek(1)==Tr){let t=e.dialectEnabled(m1)||v1(e.context);n.acceptToken(t?i1:Sh,2)}else n.next==Tr&&n.acceptToken(Sh,1)});function Sl(n,e,t){let i=2+n.length;return new Ae(r=>{for(let s=0,o=0,l=0;;l++){if(r.next<0){l&&r.acceptToken(e);break}if(s==0&&r.next==Iu||s==1&&r.next==gl||s>=2&&so?r.acceptToken(e,-o):r.acceptToken(t,-(o-2));break}else if((r.next==10||r.next==13)&&l){r.acceptToken(e,1);break}else s=o=0;r.advance()}})}const C1=Sl("script",FS,HS),Z1=Sl("style",KS,JS),X1=Sl("textarea",e1,t1),A1=xi({"Text RawText IncompleteTag IncompleteCloseTag":m.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":m.angleBracket,TagName:m.tagName,"MismatchedCloseTag/TagName":[m.tagName,m.invalid],AttributeName:m.attributeName,"AttributeValue UnquotedAttributeValue":m.attributeValue,Is:m.definitionOperator,"EntityReference CharacterReference":m.character,Comment:m.blockComment,ProcessingInst:m.processingInstruction,DoctypeDecl:m.documentMeta}),R1=Qi.deserialize({version:14,states:",xOVO!rOOO!ZQ#tO'#CrO!`Q#tO'#C{O!eQ#tO'#DOO!jQ#tO'#DRO!oQ#tO'#DTO!tOaO'#CqO#PObO'#CqO#[OdO'#CqO$kO!rO'#CqOOO`'#Cq'#CqO$rO$fO'#DUO$zQ#tO'#DWO%PQ#tO'#DXOOO`'#Dl'#DlOOO`'#DZ'#DZQVO!rOOO%UQ&rO,59^O%aQ&rO,59gO%lQ&rO,59jO%wQ&rO,59mO&SQ&rO,59oOOOa'#D_'#D_O&_OaO'#CyO&jOaO,59]OOOb'#D`'#D`O&rObO'#C|O&}ObO,59]OOOd'#Da'#DaO'VOdO'#DPO'bOdO,59]OOO`'#Db'#DbO'jO!rO,59]O'qQ#tO'#DSOOO`,59],59]OOOp'#Dc'#DcO'vO$fO,59pOOO`,59p,59pO(OQ#|O,59rO(TQ#|O,59sOOO`-E7X-E7XO(YQ&rO'#CtOOQW'#D['#D[O(hQ&rO1G.xOOOa1G.x1G.xOOO`1G/Z1G/ZO(sQ&rO1G/ROOOb1G/R1G/RO)OQ&rO1G/UOOOd1G/U1G/UO)ZQ&rO1G/XOOO`1G/X1G/XO)fQ&rO1G/ZOOOa-E7]-E7]O)qQ#tO'#CzOOO`1G.w1G.wOOOb-E7^-E7^O)vQ#tO'#C}OOOd-E7_-E7_O){Q#tO'#DQOOO`-E7`-E7`O*QQ#|O,59nOOOp-E7a-E7aOOO`1G/[1G/[OOO`1G/^1G/^OOO`1G/_1G/_O*VQ,UO,59`OOQW-E7Y-E7YOOOa7+$d7+$dOOO`7+$u7+$uOOOb7+$m7+$mOOOd7+$p7+$pOOO`7+$s7+$sO*bQ#|O,59fO*gQ#|O,59iO*lQ#|O,59lOOO`1G/Y1G/YO*qO7[O'#CwO+SOMhO'#CwOOQW1G.z1G.zOOO`1G/Q1G/QOOO`1G/T1G/TOOO`1G/W1G/WOOOO'#D]'#D]O+eO7[O,59cOOQW,59c,59cOOOO'#D^'#D^O+vOMhO,59cOOOO-E7Z-E7ZOOQW1G.}1G.}OOOO-E7[-E7[",stateData:",c~O!_OS~OUSOVPOWQOXROYTO[]O][O^^O_^Oa^Ob^Oc^Od^Oy^O|_O!eZO~OgaO~OgbO~OgcO~OgdO~OgeO~O!XfOPmP![mP~O!YiOQpP![pP~O!ZlORsP![sP~OUSOVPOWQOXROYTOZqO[]O][O^^O_^Oa^Ob^Oc^Od^Oy^O!eZO~O![rO~P#gO!]sO!fuO~OgvO~OgwO~OS|OT}OiyO~OS!POT}OiyO~OS!ROT}OiyO~OS!TOT}OiyO~OS}OT}OiyO~O!XfOPmX![mX~OP!WO![!XO~O!YiOQpX![pX~OQ!ZO![!XO~O!ZlORsX![sX~OR!]O![!XO~O![!XO~P#gOg!_O~O!]sO!f!aO~OS!bO~OS!cO~Oj!dOShXThXihX~OS!fOT!gOiyO~OS!hOT!gOiyO~OS!iOT!gOiyO~OS!jOT!gOiyO~OS!gOT!gOiyO~Og!kO~Og!lO~Og!mO~OS!nO~Ol!qO!a!oO!c!pO~OS!rO~OS!sO~OS!tO~Ob!uOc!uOd!uO!a!wO!b!uO~Ob!xOc!xOd!xO!c!wO!d!xO~Ob!uOc!uOd!uO!a!{O!b!uO~Ob!xOc!xOd!xO!c!{O!d!xO~OT~cbd!ey|!e~",goto:"%q!aPPPPPPPPPPPPPPPPPPPPP!b!hP!nPP!zP!}#Q#T#Z#^#a#g#j#m#s#y!bP!b!bP$P$V$m$s$y%P%V%]%cPPPPPPPP%iX^OX`pXUOX`pezabcde{!O!Q!S!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ!ObQ!QcQ!SdQ!UeZ!e{!O!Q!S!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag EndTag SelfClosingEndTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:68,context:w1,nodeProps:[["closedBy",-10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,22,31,34,37,"CloseTag"],["openedBy",4,"StartTag StartCloseTag",5,"StartTag",-4,30,33,36,38,"OpenTag"],["group",-10,14,15,18,19,20,21,40,41,42,43,"Entity",17,"Entity TextContent",-3,29,32,35,"TextContent Entity"],["isolate",-11,22,30,31,33,34,36,37,38,39,42,43,"ltr",-3,27,28,40,""]],propSources:[A1],skippedNodes:[0],repeatNodeCount:9,tokenData:"!]tw8twx7Sx!P8t!P!Q5u!Q!]8t!]!^/^!^!a7S!a#S8t#S#T;{#T#s8t#s$f5u$f;'S8t;'S;=`>V<%l?Ah8t?Ah?BY5u?BY?Mn8t?MnO5u!Z5zblWOX5uXZ7SZ[5u[^7S^p5uqr5urs7Sst+Ptw5uwx7Sx!]5u!]!^7w!^!a7S!a#S5u#S#T7S#T;'S5u;'S;=`8n<%lO5u!R7VVOp7Sqs7St!]7S!]!^7l!^;'S7S;'S;=`7q<%lO7S!R7qOb!R!R7tP;=`<%l7S!Z8OYlWb!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!Z8qP;=`<%l5u!_8{iiSlWOX5uXZ7SZ[5u[^7S^p5uqr8trs7Sst/^tw8twx7Sx!P8t!P!Q5u!Q!]8t!]!^:j!^!a7S!a#S8t#S#T;{#T#s8t#s$f5u$f;'S8t;'S;=`>V<%l?Ah8t?Ah?BY5u?BY?Mn8t?MnO5u!_:sbiSlWb!ROX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!a#S/^#S#T0m#T#s/^#s$f+P$f;'S/^;'S;=`1e<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+P!VP<%l?Ah;{?Ah?BY7S?BY?Mn;{?MnO7S!V=dXiSb!Rqr0msw0mx!P0m!Q!^0m!a#s0m$f;'S0m;'S;=`1_<%l?Ah0m?BY?Mn0m!V>SP;=`<%l;{!_>YP;=`<%l8t!_>dhiSlWOX@OXZAYZ[@O[^AY^p@OqrBwrsAYswBwwxAYx!PBw!P!Q@O!Q!]Bw!]!^/^!^!aAY!a#SBw#S#TE{#T#sBw#s$f@O$f;'SBw;'S;=`HS<%l?AhBw?Ah?BY@O?BY?MnBw?MnO@O!Z@TalWOX@OXZAYZ[@O[^AY^p@Oqr@OrsAYsw@OwxAYx!]@O!]!^Az!^!aAY!a#S@O#S#TAY#T;'S@O;'S;=`Bq<%lO@O!RA]UOpAYq!]AY!]!^Ao!^;'SAY;'S;=`At<%lOAY!RAtOc!R!RAwP;=`<%lAY!ZBRYlWc!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!ZBtP;=`<%l@O!_COhiSlWOX@OXZAYZ[@O[^AY^p@OqrBwrsAYswBwwxAYx!PBw!P!Q@O!Q!]Bw!]!^Dj!^!aAY!a#SBw#S#TE{#T#sBw#s$f@O$f;'SBw;'S;=`HS<%l?AhBw?Ah?BY@O?BY?MnBw?MnO@O!_DsbiSlWc!ROX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!a#S/^#S#T0m#T#s/^#s$f+P$f;'S/^;'S;=`1e<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+P!VFQbiSOpAYqrE{rsAYswE{wxAYx!PE{!P!QAY!Q!]E{!]!^GY!^!aAY!a#sE{#s$fAY$f;'SE{;'S;=`G|<%l?AhE{?Ah?BYAY?BY?MnE{?MnOAY!VGaXiSc!Rqr0msw0mx!P0m!Q!^0m!a#s0m$f;'S0m;'S;=`1_<%l?Ah0m?BY?Mn0m!VHPP;=`<%lE{!_HVP;=`<%lBw!ZHcW!cxaP!b`Or(trs'ksv(tw!^(t!^!_)e!_;'S(t;'S;=`*P<%lO(t!aIYliSaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx}-_}!OKQ!O!P-_!P!Q$q!Q!^-_!^!_*V!_!a&X!a#S-_#S#T1k#T#s-_#s$f$q$f;'S-_;'S;=`3X<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q!aK_kiSaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx!P-_!P!Q$q!Q!^-_!^!_*V!_!`&X!`!aMS!a#S-_#S#T1k#T#s-_#s$f$q$f;'S-_;'S;=`3X<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q!TM_XaP!b`!dp!fQOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X!aNZ!ZiSgQaPlW!b`!dpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx}-_}!OMz!O!PMz!P!Q$q!Q![Mz![!]Mz!]!^-_!^!_*V!_!a&X!a!c-_!c!}Mz!}#R-_#R#SMz#S#T1k#T#oMz#o#s-_#s$f$q$f$}-_$}%OMz%O%W-_%W%oMz%o%p-_%p&aMz&a&b-_&b1pMz1p4UMz4U4dMz4d4e-_4e$ISMz$IS$I`-_$I`$IbMz$Ib$Je-_$Je$JgMz$Jg$Kh-_$Kh%#tMz%#t&/x-_&/x&EtMz&Et&FV-_&FV;'SMz;'S;:j!#|;:j;=`3X<%l?&r-_?&r?AhMz?Ah?BY$q?BY?MnMz?MnO$q!a!$PP;=`<%lMz!R!$ZY!b`!dpOq*Vqr!$yrs(Vsv*Vwx)ex!a*V!a!b!4t!b;'S*V;'S;=`*s<%lO*V!R!%Q]!b`!dpOr*Vrs(Vsv*Vwx)ex}*V}!O!%y!O!f*V!f!g!']!g#W*V#W#X!0`#X;'S*V;'S;=`*s<%lO*V!R!&QX!b`!dpOr*Vrs(Vsv*Vwx)ex}*V}!O!&m!O;'S*V;'S;=`*s<%lO*V!R!&vV!b`!dp!ePOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!'dX!b`!dpOr*Vrs(Vsv*Vwx)ex!q*V!q!r!(P!r;'S*V;'S;=`*s<%lO*V!R!(WX!b`!dpOr*Vrs(Vsv*Vwx)ex!e*V!e!f!(s!f;'S*V;'S;=`*s<%lO*V!R!(zX!b`!dpOr*Vrs(Vsv*Vwx)ex!v*V!v!w!)g!w;'S*V;'S;=`*s<%lO*V!R!)nX!b`!dpOr*Vrs(Vsv*Vwx)ex!{*V!{!|!*Z!|;'S*V;'S;=`*s<%lO*V!R!*bX!b`!dpOr*Vrs(Vsv*Vwx)ex!r*V!r!s!*}!s;'S*V;'S;=`*s<%lO*V!R!+UX!b`!dpOr*Vrs(Vsv*Vwx)ex!g*V!g!h!+q!h;'S*V;'S;=`*s<%lO*V!R!+xY!b`!dpOr!+qrs!,hsv!+qvw!-Swx!.[x!`!+q!`!a!/j!a;'S!+q;'S;=`!0Y<%lO!+qq!,mV!dpOv!,hvx!-Sx!`!,h!`!a!-q!a;'S!,h;'S;=`!.U<%lO!,hP!-VTO!`!-S!`!a!-f!a;'S!-S;'S;=`!-k<%lO!-SP!-kO|PP!-nP;=`<%l!-Sq!-xS!dp|POv(Vx;'S(V;'S;=`(h<%lO(Vq!.XP;=`<%l!,ha!.aX!b`Or!.[rs!-Ssv!.[vw!-Sw!`!.[!`!a!.|!a;'S!.[;'S;=`!/d<%lO!.[a!/TT!b`|POr)esv)ew;'S)e;'S;=`)y<%lO)ea!/gP;=`<%l!.[!R!/sV!b`!dp|POr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!0]P;=`<%l!+q!R!0gX!b`!dpOr*Vrs(Vsv*Vwx)ex#c*V#c#d!1S#d;'S*V;'S;=`*s<%lO*V!R!1ZX!b`!dpOr*Vrs(Vsv*Vwx)ex#V*V#V#W!1v#W;'S*V;'S;=`*s<%lO*V!R!1}X!b`!dpOr*Vrs(Vsv*Vwx)ex#h*V#h#i!2j#i;'S*V;'S;=`*s<%lO*V!R!2qX!b`!dpOr*Vrs(Vsv*Vwx)ex#m*V#m#n!3^#n;'S*V;'S;=`*s<%lO*V!R!3eX!b`!dpOr*Vrs(Vsv*Vwx)ex#d*V#d#e!4Q#e;'S*V;'S;=`*s<%lO*V!R!4XX!b`!dpOr*Vrs(Vsv*Vwx)ex#X*V#X#Y!+q#Y;'S*V;'S;=`*s<%lO*V!R!4{Y!b`!dpOr!4trs!5ksv!4tvw!6Vwx!8]x!a!4t!a!b!:]!b;'S!4t;'S;=`!;r<%lO!4tq!5pV!dpOv!5kvx!6Vx!a!5k!a!b!7W!b;'S!5k;'S;=`!8V<%lO!5kP!6YTO!a!6V!a!b!6i!b;'S!6V;'S;=`!7Q<%lO!6VP!6lTO!`!6V!`!a!6{!a;'S!6V;'S;=`!7Q<%lO!6VP!7QOyPP!7TP;=`<%l!6Vq!7]V!dpOv!5kvx!6Vx!`!5k!`!a!7r!a;'S!5k;'S;=`!8V<%lO!5kq!7yS!dpyPOv(Vx;'S(V;'S;=`(h<%lO(Vq!8YP;=`<%l!5ka!8bX!b`Or!8]rs!6Vsv!8]vw!6Vw!a!8]!a!b!8}!b;'S!8];'S;=`!:V<%lO!8]a!9SX!b`Or!8]rs!6Vsv!8]vw!6Vw!`!8]!`!a!9o!a;'S!8];'S;=`!:V<%lO!8]a!9vT!b`yPOr)esv)ew;'S)e;'S;=`)y<%lO)ea!:YP;=`<%l!8]!R!:dY!b`!dpOr!4trs!5ksv!4tvw!6Vwx!8]x!`!4t!`!a!;S!a;'S!4t;'S;=`!;r<%lO!4t!R!;]V!b`!dpyPOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!;uP;=`<%l!4t!V!{let h=l.type.id;if(h==c1)return xs(l,a,t);if(h==f1)return xs(l,a,i);if(h==u1)return xs(l,a,r);if(h==Bu&&s.length){let c=l.node,f=c.firstChild,u=f&&$h(f,a),O;if(u){for(let d of s)if(d.tag==u&&(!d.attrs||d.attrs(O||(O=Nu(f,a))))){let p=c.lastChild,g=p.type.id==d1?p.from:c.to;if(g>f.to)return{parser:d.parser,overlay:[{from:f.to,to:g}]}}}}if(o&&h==qu){let c=l.node,f;if(f=c.firstChild){let u=o[a.read(f.from,f.to)];if(u)for(let O of u){if(O.tagName&&O.tagName!=$h(c.parent,a))continue;let d=c.lastChild;if(d.type.id==Po){let p=d.from+1,g=d.lastChild,S=d.to-(g&&g.isError?0:1);if(S>p)return{parser:O.parser,overlay:[{from:p,to:S}],bracketed:!0}}else if(d.type.id==Du)return{parser:O.parser,overlay:[{from:d.from,to:d.to}]}}}}return null})}const M1=148,Ph=1,j1=149,L1=150,Uu=2,Y1=151,E1=3,z1=4,Fu=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],_1=58,W1=40,Hu=95,V1=91,tr=45,B1=46,q1=35,D1=37,I1=38,N1=92,G1=10,U1=42;function cn(n){return n>=65&&n<=90||n>=97&&n<=122||n>=161}function bl(n){return n>=48&&n<=57}function vh(n){return bl(n)||n>=97&&n<=102||n>=65&&n<=70}const Ku=(n,e,t)=>(i,r)=>{for(let s=!1,o=0,l=0;;l++){let{next:a}=i;if(cn(a)||a==tr||a==Hu||s&&bl(a))!s&&(a!=tr||l>0)&&(s=!0),o===l&&a==tr&&o++,i.advance();else if(a==N1&&i.peek(1)!=G1){if(i.advance(),vh(i.next)){do i.advance();while(vh(i.next));i.next==32&&i.advance()}else i.next>-1&&i.advance();s=!0}else{s&&i.acceptToken(o==2&&r.canShift(Uu)?e:a==W1?t:n);break}}},F1=new Ae(Ku(j1,Uu,L1),{contextual:!0}),H1=new Ae(Ku(Y1,E1,z1),{contextual:!0}),K1=new Ae(n=>{if(Fu.includes(n.peek(-1))){let{next:e}=n;(cn(e)||e==Hu||e==q1||e==B1||e==U1||e==V1||e==_1&&cn(n.peek(1))||e==tr||e==I1)&&n.acceptToken(M1)}}),J1=new Ae(n=>{if(!Fu.includes(n.peek(-1))){let{next:e}=n;if(e==D1&&(n.advance(),n.acceptToken(Ph)),cn(e)){do n.advance();while(cn(n.next)||bl(n.next));n.acceptToken(Ph)}}}),eb=xi({"AtKeyword import charset namespace keyframes media supports font-feature-values":m.definitionKeyword,"from to selector scope MatchFlag":m.keyword,NamespaceName:m.namespace,KeyframeName:m.labelName,KeyframeRangeName:m.operatorKeyword,TagName:m.tagName,ClassName:m.className,PseudoClassName:m.constant(m.className),IdName:m.labelName,"FeatureName PropertyName":m.propertyName,AttributeName:m.attributeName,NumberLiteral:m.number,KeywordQuery:m.keyword,UnaryQueryOp:m.operatorKeyword,"CallTag ValueName FontName":m.atom,VariableName:m.variableName,Callee:m.operatorKeyword,Unit:m.unit,"UniversalSelector NestingSelector":m.definitionOperator,"MatchOp CompareOp":m.compareOperator,"ChildOp SiblingOp, LogicOp":m.logicOperator,BinOp:m.arithmeticOperator,Important:m.modifier,Comment:m.blockComment,ColorLiteral:m.color,"ParenthesizedContent StringLiteral":m.string,":":m.punctuation,"PseudoOp #":m.derefOperator,"; , |":m.separator,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace}),tb={__proto__:null,lang:44,"nth-child":44,"nth-last-child":44,"nth-of-type":44,"nth-last-of-type":44,dir:44,"host-context":44,if:90,url:158,"url-prefix":158,domain:158,regexp:158},ib={__proto__:null,or:104,and:104,not:112,only:112,layer:212},nb={__proto__:null,selector:118,style:124,layer:208},rb={__proto__:null,"@import":204,"@media":216,"@charset":220,"@namespace":224,"@keyframes":230,"@supports":242,"@scope":246,"@font-feature-values":252},sb={__proto__:null,to:249},ob=Qi.deserialize({version:14,states:"MrQYQdOOO#}QdOOP$UO`OOO%OQaO'#CfOOQP'#Ce'#CeO%VQdO'#CgO%[Q`O'#CgO%aQaO'#FqO&XQdO'#CkO&xQaO'#CcO'SQdO'#CnO'_QdO'#ERO'dQdO'#ETO'oQdO'#E[O'oQdO'#E_OOQP'#Fq'#FqO)RQhO'#FQOOQS'#Fp'#FpOOQS'#FT'#FTQYQdOOO)YQdO'#EeO*iQhO'#EkO)YQdO'#EmO*pQdO'#EoO*{QdO'#ErO)}QhO'#ExO+TQdO'#EzO+`QdO'#E}O+eQaO'#CfO+lQ`O'#EbO+qQ`O'#F}O+|QdO'#F}QOQ`OOP,WO&jO'#CaPOOO)CA`)CA`OOQP'#Ci'#CiOOQP,59R,59RO%VQdO,59ROOQP'#Cm'#CmOOQP,59V,59VO&XQdO,59VO,cQdO,59YO'_QdO,5:mO'dQdO,5:oO'oQdO,5:vO'oQdO,5:xO'oQdO,5:yO'oQdO'#F[O,nQ`O,58}O,vQdO'#EaOOQS,58},58}OOQP'#Cq'#CqOOQO'#EP'#EPOOQP,59Y,59YO,}Q`O,59YO-SQ`O,59YOOQP'#ES'#ESOOQP,5:m,5:mO-XQpO'#EUO-dQdO'#EVO-iQ`O'#EVO-nQpO,5:oO.XQaO,5:vO.oQaO,5:yOOQW'#D^'#D^O/nQhO'#DgO0RQhO,5;lO)}QhO'#DeO0`Q`O'#DnO0eQhO'#D{OOQW'#Fw'#FwOOQS,5;l,5;lO0jQ`O'#DhO0oQ`O'#DkOOQS-E9R-E9ROOQ['#Cv'#CvO0tQdO'#CwO1[QdO'#C}O1rQdO'#DQO2YQ!pO'#DSO4fQ!jO,5;POOQO'#DX'#DXO-SQ`O'#DWO4vQ!nO'#FtO6|Q`O'#DYO7RQ`O'#D|OOQ['#Ft'#FtO7WQhO'#GQO7fQ`O,5;VO7kQ!bO,5;XOOQS'#Eq'#EqO7sQ`O,5;ZO7xQdO,5;ZOOQO'#Et'#EtO8QQ`O,5;^O8VQhO,5;dO'oQdO'#DjOOQS,5;f,5;fO0jQ`O,5;fO8_QdO,5;fOOQS'#Fc'#FcO8gQdO'#FPO7fQ`O,5;iO8oQdO,5:|O9PQdO'#F^O9^Q`O,5lQhO'#DoOOQW,5:Y,5:YOOQW,5:g,5:gOOQW,5:S,5:SO>vQhO,5:VO?bQ!fO'#FuOOQS'#Fu'#FuOOQS'#FV'#FVO@rQdO,59cOOQ[,59c,59cOAYQdO,59iOOQ[,59i,59iOApQdO,59lOOQ[,59l,59lOOQ[,59n,59nO)YQdO,59pOBWQhO'#EgOOQW'#Eg'#EgOBuQ`O1G0kO4oQhO1G0kOOQ[,59r,59rO)}QhO'#D[OOQ[,59t,59tOBzQ#tO,5:hOCVQhO'#F`OCdQ`O,5vQhO'#DmOI_QhO'#DsOIgQhO'#DuOIlQ!jO'#FzOOQO'#Fz'#FzOIwQ`O'#DxOJPQ!bO'#DzOOQO'#Fy'#FyOJUQ`O1G/qOOQS-E9T-E9TOOQ[1G.}1G.}OOQ[1G/T1G/TOOQ[1G/W1G/WOOQ[1G/[1G/[OJZQdO,5;ROOQS7+&V7+&VOJ`Q`O7+&VOJeQhO'#D]OJmQ`O,59vO)}QhO,59vOOQ[1G0S1G0SOJuQ`O1G0SOJzQhO,5;zOOQO-E9^-E9^OOQS7+&a7+&aOKYQbO'#DSOOQO'#Ew'#EwOKhQ`O'#EvOOQO'#Ev'#EvOKsQ`O'#FaOK{QdO,5;aOOQS,5;a,5;aOOQ[1G/p1G/pOOQS7+&l7+&lO7fQ`O7+&lOLWQ!fO'#F]O)YQdO'#F]OM_QdO7+&SOOQO7+&S7+&SOOQO,5;O,5;OOOQO1G1d1G1dOMrQ!bO<vQhO'#DtOOQO,5:_,5:_O! sQhO,5:aO! {QhO,5:fO)YQdO,5:dOOQW7+%]7+%]OOQO'#Ei'#EiO!!SQ`O1G0mOOQS<{AN>{O!$^Q`OAN>{O!$cQaO,5;uOOQO-E9X-E9XO!$mQdO,5;tOOQO-E9W-E9WOOQW<vQhO'#DwOOQO1G/{1G/{O!&aQ!bO1G0QO!&iQdO1G0OOJZQdO'#F_O!&pQ`O7+&XOOQW7+&X7+&XO!&xQ!bO1G/cOOQ[7+$|7+$|O!'TQhO7+$|P!'[Q`O'#FWOOQO,5;|,5;|OOQO-E9`-E9`OOQS1G1g1G1gOOQPG24gG24gO!'aQ`OAN>ZO)YQdO1G1_O!'fQ`O7+'mOOQO1G/z1G/zO!'nQ`O,5:cO!'sQhO7+%lOOQO,5;y,5;yOOQO-E9]-E9]OOQW<Q!]!^>|!^!_?_!_!`@Z!`!a@n!a!b%Z!b!cAo!c!k%Z!k!lC|!l!u%Z!u!vC|!v!}%Z!}#OD_#O#P%Z#P#QDp#Q#R2X#R#]%Z#]#^ER#^#g%Z#g#hC|#h#o%Z#o#pIf#p#qIw#q#rJ`#r#sJq#s#y%Z#y#z&R#z$f%Z$f$g&R$g#BY%Z#BY#BZ&R#BZ$IS%Z$IS$I_&R$I_$I|%Z$I|$JO&R$JO$JT%Z$JT$JU&R$JU$KV%Z$KV$KW&R$KW&FU%Z&FU&FV&R&FV;'S%Z;'S;=`KY<%lO%Z`%^SOy%jz;'S%j;'S;=`%{<%lO%j`%oS!r`Oy%jz;'S%j;'S;=`%{<%lO%j`&OP;=`<%l%j~&Wh$_~OX%jX^'r^p%jpq'rqy%jz#y%j#y#z'r#z$f%j$f$g'r$g#BY%j#BY#BZ'r#BZ$IS%j$IS$I_'r$I_$I|%j$I|$JO'r$JO$JT%j$JT$JU'r$JU$KV%j$KV$KW'r$KW&FU%j&FU&FV'r&FV;'S%j;'S;=`%{<%lO%j~'yh$_~!r`OX%jX^'r^p%jpq'rqy%jz#y%j#y#z'r#z$f%j$f$g'r$g#BY%j#BY#BZ'r#BZ$IS%j$IS$I_'r$I_$I|%j$I|$JO'r$JO$JT%j$JT$JU'r$JU$KV%j$KV$KW'r$KW&FU%j&FU&FV'r&FV;'S%j;'S;=`%{<%lO%jj)jS$sYOy%jz;'S%j;'S;=`%{<%lO%j~)yWOY)vZr)vrs*cs#O)v#O#P*h#P;'S)v;'S;=`+d<%lO)v~*hOw~~*kRO;'S)v;'S;=`*t;=`O)v~*wXOY)vZr)vrs*cs#O)v#O#P*h#P;'S)v;'S;=`+d;=`<%l)v<%lO)v~+gP;=`<%l)vj+oYmYOy%jz!Q%j!Q![,_![!c%j!c!i,_!i#T%j#T#Z,_#Z;'S%j;'S;=`%{<%lO%jj,dY!r`Oy%jz!Q%j!Q![-S![!c%j!c!i-S!i#T%j#T#Z-S#Z;'S%j;'S;=`%{<%lO%jj-XY!r`Oy%jz!Q%j!Q![-w![!c%j!c!i-w!i#T%j#T#Z-w#Z;'S%j;'S;=`%{<%lO%jj.OYuY!r`Oy%jz!Q%j!Q![.n![!c%j!c!i.n!i#T%j#T#Z.n#Z;'S%j;'S;=`%{<%lO%jj.uYuY!r`Oy%jz!Q%j!Q![/e![!c%j!c!i/e!i#T%j#T#Z/e#Z;'S%j;'S;=`%{<%lO%jj/jY!r`Oy%jz!Q%j!Q![0Y![!c%j!c!i0Y!i#T%j#T#Z0Y#Z;'S%j;'S;=`%{<%lO%jj0aYuY!r`Oy%jz!Q%j!Q![1P![!c%j!c!i1P!i#T%j#T#Z1P#Z;'S%j;'S;=`%{<%lO%jj1UY!r`Oy%jz!Q%j!Q![1t![!c%j!c!i1t!i#T%j#T#Z1t#Z;'S%j;'S;=`%{<%lO%jj1{SuY!r`Oy%jz;'S%j;'S;=`%{<%lO%jd2[UOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jd2uS!|S!r`Oy%jz;'S%j;'S;=`%{<%lO%jb3WS^QOy%jz;'S%j;'S;=`%{<%lO%j~3gWOY3dZw3dwx*cx#O3d#O#P4P#P;'S3d;'S;=`4{<%lO3d~4SRO;'S3d;'S;=`4];=`O3d~4`XOY3dZw3dwx*cx#O3d#O#P4P#P;'S3d;'S;=`4{;=`<%l3d<%lO3d~5OP;=`<%l3dj5WShYOy%jz;'S%j;'S;=`%{<%lO%j~5iOg~n5pUWQyWOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jj6ZWyW#SQOy%jz!O%j!O!P6s!P!Q%j!Q![9x![;'S%j;'S;=`%{<%lO%jj6xU!r`Oy%jz!Q%j!Q![7[![;'S%j;'S;=`%{<%lO%jj7cY!r`$jYOy%jz!Q%j!Q![7[![!g%j!g!h8R!h#X%j#X#Y8R#Y;'S%j;'S;=`%{<%lO%jj8WY!r`Oy%jz{%j{|8v|}%j}!O8v!O!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj8{U!r`Oy%jz!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj9fU!r`$jYOy%jz!Q%j!Q![9_![;'S%j;'S;=`%{<%lO%jj:P[!r`$jYOy%jz!O%j!O!P7[!P!Q%j!Q![9x![!g%j!g!h8R!h#X%j#X#Y8R#Y;'S%j;'S;=`%{<%lO%jj:zS!eYOy%jz;'S%j;'S;=`%{<%lO%jj;]WyWOy%jz!O%j!O!P6s!P!Q%j!Q![9x![;'S%j;'S;=`%{<%lO%jj;zU`YOy%jz!Q%j!Q![7[![;'S%j;'S;=`%{<%lO%j~VUcYOy%jz![%j![!]>i!];'S%j;'S;=`%{<%lO%jj>pSdY!r`Oy%jz;'S%j;'S;=`%{<%lO%jj?RSnYOy%jz;'S%j;'S;=`%{<%lO%jh?dU!WWOy%jz!_%j!_!`?v!`;'S%j;'S;=`%{<%lO%jh?}S!WW!r`Oy%jz;'S%j;'S;=`%{<%lO%jl@bS!WW!|SOy%jz;'S%j;'S;=`%{<%lO%jj@uV#PQ!WWOy%jz!_%j!_!`?v!`!aA[!a;'S%j;'S;=`%{<%lO%jbAcS#PQ!r`Oy%jz;'S%j;'S;=`%{<%lO%jjArYOy%jz}%j}!OBb!O!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jjBgW!r`Oy%jz!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jjCW[lY!r`Oy%jz}%j}!OCP!O!Q%j!Q![CP![!c%j!c!}CP!}#T%j#T#oCP#o;'S%j;'S;=`%{<%lO%jhDRS!}WOy%jz;'S%j;'S;=`%{<%lO%jjDdSpYOy%jz;'S%j;'S;=`%{<%lO%jnDuSo^Oy%jz;'S%j;'S;=`%{<%lO%jjEWU!}WOy%jz#a%j#a#bEj#b;'S%j;'S;=`%{<%lO%jbEoU!r`Oy%jz#d%j#d#eFR#e;'S%j;'S;=`%{<%lO%jbFWU!r`Oy%jz#c%j#c#dFj#d;'S%j;'S;=`%{<%lO%jbFoU!r`Oy%jz#f%j#f#gGR#g;'S%j;'S;=`%{<%lO%jbGWU!r`Oy%jz#h%j#h#iGj#i;'S%j;'S;=`%{<%lO%jbGoU!r`Oy%jz#T%j#T#UHR#U;'S%j;'S;=`%{<%lO%jbHWU!r`Oy%jz#b%j#b#cHj#c;'S%j;'S;=`%{<%lO%jbHoU!r`Oy%jz#h%j#h#iIR#i;'S%j;'S;=`%{<%lO%jbIYS$rQ!r`Oy%jz;'S%j;'S;=`%{<%lO%jjIkSsYOy%jz;'S%j;'S;=`%{<%lO%jfI|U$fUOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%jjJeSrYOy%jz;'S%j;'S;=`%{<%lO%jfJvU#SQOy%jz!_%j!_!`2n!`;'S%j;'S;=`%{<%lO%j`K]P;=`<%l%Z",tokenizers:[K1,J1,F1,H1,1,2,3,4,new vr("m~RRYZ[z{a~~g~aO$b~~dP!P!Qg~lO$c~~",28,155)],topRules:{StyleSheet:[0,6],Styles:[1,129]},dynamicPrecedences:{97:1},specialized:[{term:150,get:n=>tb[n]||-1},{term:151,get:n=>ib[n]||-1},{term:4,get:n=>nb[n]||-1},{term:28,get:n=>rb[n]||-1},{term:149,get:n=>sb[n]||-1}],tokenPrec:2444});let ks=null;function ws(){if(!ks&&typeof document=="object"&&document.body){let{style:n}=document.body,e=[],t=new Set;for(let i in n)i!="cssText"&&i!="cssFloat"&&typeof n[i]=="string"&&(/[A-Z]/.test(i)&&(i=i.replace(/[A-Z]/g,r=>"-"+r.toLowerCase())),t.has(i)||(e.push(i),t.add(i)));ks=e.sort().map(i=>({type:"property",label:i,apply:i+": "}))}return ks||[]}const Th=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map(n=>({type:"class",label:n})),Ch=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map(n=>({type:"keyword",label:n})).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map(n=>({type:"constant",label:n}))),lb=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map(n=>({type:"type",label:n})),ab=["@charset","@color-profile","@container","@counter-style","@font-face","@font-feature-values","@font-palette-values","@import","@keyframes","@layer","@media","@namespace","@page","@position-try","@property","@scope","@starting-style","@supports","@view-transition"].map(n=>({type:"keyword",label:n})),Ot=/^(\w[\w-]*|-\w[\w-]*|)$/,hb=/^-(-[\w-]*)?$/;function cb(n,e){var t;if((n.name=="("||n.type.isError)&&(n=n.parent||n),n.name!="ArgList")return!1;let i=(t=n.parent)===null||t===void 0?void 0:t.firstChild;return i?.name!="Callee"?!1:e.sliceString(i.from,i.to)=="var"}const Zh=new hf,fb=["Declaration"];function ub(n){for(let e=n;;){if(e.type.isTop)return e;if(!(e=e.parent))return n}}function Ju(n,e,t){if(e.to-e.from>4096){let i=Zh.get(e);if(i)return i;let r=[],s=new Set,o=e.cursor(D.IncludeAnonymous);if(o.firstChild())do for(let l of Ju(n,o.node,t))s.has(l.label)||(s.add(l.label),r.push(l));while(o.nextSibling());return Zh.set(e,r),r}else{let i=[],r=new Set;return e.cursor().iterate(s=>{var o;if(t(s)&&s.matchContext(fb)&&((o=s.node.nextSibling)===null||o===void 0?void 0:o.name)==":"){let l=n.sliceString(s.from,s.to);r.has(l)||(r.add(l),i.push({label:l,type:"variable"}))}}),i}}const Ob=n=>e=>{let{state:t,pos:i}=e,r=J(t).resolveInner(i,-1),s=r.type.isError&&r.from==r.to-1&&t.doc.sliceString(r.from,r.to)=="-";if(r.name=="PropertyName"||(s||r.name=="TagName")&&/^(Block|Styles)$/.test(r.resolve(r.to).name))return{from:r.from,options:ws(),validFor:Ot};if(r.name=="ValueName")return{from:r.from,options:Ch,validFor:Ot};if(r.name=="PseudoClassName")return{from:r.from,options:Th,validFor:Ot};if(n(r)||(e.explicit||s)&&cb(r,t.doc))return{from:n(r)||s?r.from:i,options:Ju(t.doc,ub(r),n),validFor:hb};if(r.name=="TagName"){for(let{parent:a}=r;a;a=a.parent)if(a.name=="Block")return{from:r.from,options:ws(),validFor:Ot};return{from:r.from,options:lb,validFor:Ot}}if(r.name=="AtKeyword")return{from:r.from,options:ab,validFor:Ot};if(!e.explicit)return null;let o=r.resolve(i),l=o.childBefore(i);return l&&l.name==":"&&o.name=="PseudoClassSelector"?{from:i,options:Th,validFor:Ot}:l&&l.name==":"&&o.name=="Declaration"||o.name=="ArgList"?{from:i,options:Ch,validFor:Ot}:o.name=="Block"||o.name=="Styles"?{from:i,options:ws(),validFor:Ot}:null},db=Ob(n=>n.name=="VariableName"),Cr=mi.define({name:"css",parser:ob.configure({props:[bn.add({Declaration:Jn()}),ki.add({"Block KeyframeList":Sf})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function pb(){return new sn(Cr,Cr.data.of({autocomplete:db}))}const mb=316,gb=317,Xh=1,Sb=2,bb=3,Qb=4,yb=318,xb=320,kb=321,wb=5,$b=6,Pb=0,To=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],eO=125,vb=59,Co=47,Tb=42,Cb=43,Zb=45,Xb=60,Ab=44,Rb=63,Mb=46,jb=91,Lb=new Eu({start:!1,shift(n,e){return e==wb||e==$b||e==xb?n:e==kb},strict:!1}),Yb=new Ae((n,e)=>{let{next:t}=n;(t==eO||t==-1||e.context)&&n.acceptToken(yb)},{contextual:!0,fallback:!0}),Eb=new Ae((n,e)=>{let{next:t}=n,i;To.indexOf(t)>-1||t==Co&&((i=n.peek(1))==Co||i==Tb)||t!=eO&&t!=vb&&t!=-1&&!e.context&&n.acceptToken(mb)},{contextual:!0}),zb=new Ae((n,e)=>{n.next==jb&&!e.context&&n.acceptToken(gb)},{contextual:!0}),_b=new Ae((n,e)=>{let{next:t}=n;if(t==Cb||t==Zb){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(Xh);n.acceptToken(i?Xh:Sb)}}else t==Rb&&n.peek(1)==Mb&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(bb))},{contextual:!0});function $s(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const Wb=new Ae((n,e)=>{if(n.next!=Xb||!e.dialectEnabled(Pb)||(n.advance(),n.next==Co))return;let t=0;for(;To.indexOf(n.next)>-1;)n.advance(),t++;if($s(n.next,!0)){for(n.advance(),t++;$s(n.next,!1);)n.advance(),t++;for(;To.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==Ab)return;for(let i=0;;i++){if(i==7){if(!$s(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(Qb,-t)}),Vb=xi({"get set async static":m.modifier,"for while do if else switch try catch finally return throw break continue default case defer":m.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":m.operatorKeyword,"let var const using function class extends":m.definitionKeyword,"import export from":m.moduleKeyword,"with debugger new":m.keyword,TemplateString:m.special(m.string),super:m.atom,BooleanLiteral:m.bool,this:m.self,null:m.null,Star:m.modifier,VariableName:m.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":m.function(m.variableName),VariableDefinition:m.definition(m.variableName),Label:m.labelName,PropertyName:m.propertyName,PrivatePropertyName:m.special(m.propertyName),"CallExpression/MemberExpression/PropertyName":m.function(m.propertyName),"FunctionDeclaration/VariableDefinition":m.function(m.definition(m.variableName)),"ClassDeclaration/VariableDefinition":m.definition(m.className),"NewExpression/VariableName":m.className,PropertyDefinition:m.definition(m.propertyName),PrivatePropertyDefinition:m.definition(m.special(m.propertyName)),UpdateOp:m.updateOperator,"LineComment Hashbang":m.lineComment,BlockComment:m.blockComment,Number:m.number,String:m.string,Escape:m.escape,ArithOp:m.arithmeticOperator,LogicOp:m.logicOperator,BitOp:m.bitwiseOperator,CompareOp:m.compareOperator,RegExp:m.regexp,Equals:m.definitionOperator,Arrow:m.function(m.punctuation),": Spread":m.punctuation,"( )":m.paren,"[ ]":m.squareBracket,"{ }":m.brace,"InterpolationStart InterpolationEnd":m.special(m.brace),".":m.derefOperator,", ;":m.separator,"@":m.meta,TypeName:m.typeName,TypeDefinition:m.definition(m.typeName),"type enum interface implements namespace module declare":m.definitionKeyword,"abstract global Privacy readonly override":m.modifier,"is keyof unique infer asserts":m.operatorKeyword,JSXAttributeValue:m.attributeValue,JSXText:m.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":m.angleBracket,"JSXIdentifier JSXNameSpacedName":m.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":m.attributeName,"JSXBuiltin/JSXIdentifier":m.standard(m.tagName)}),Bb={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},qb={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},Db={__proto__:null,"<":193},Ib=Qi.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOAuQ`O'#EnOBQQ!bO'#FeOOQ['#Cg'#CgOOQ!0Lb'#Dq'#DqOOQ!0Lb'#Jv'#JvO%[QlO'#JvOOQO'#Jy'#JyOOQO'#Ih'#IhOCQQpO'#EgOOQ!0Lb'#Ef'#EfOOQ!0Lb'#J}'#J}OC|Q!0MSO'#EgODWQpO'#EWOOQO'#Jx'#JxODlQpO'#JyOEyQpO'#EWODWQpO'#EgPFWO&2DjO'#CbPOOO)CD})CD}OOOO'#I`'#I`OFcO#tO,59UOOQ!0Lh,59U,59UOOOO'#Ia'#IaOFqO&jO,59UOGPQ!L^O'#DcOOOO'#Ic'#IcOGWO#@ItO,59{OOQ!0Lf,59{,59{OGfQlO'#IdOGyQ`O'#JtOIxQ!fO'#JtO+}QlO'#JtOJPQ`O,5:ROJgQ`O'#EpOJtQ`O'#KTOKPQ`O'#KSOKPQ`O'#KSOKXQ`O,5;^OK^Q`O'#KROOQ!0Ln,5:^,5:^OKeQlO,5:^OMcQ!0MxO,5:fONSQ`O,5:nONmQ!0LrO'#KQONtQ`O'#KPO9eQ`O'#KPO! YQ`O'#KPO! bQ`O,5;]O! gQ`O'#KPO!#lQ!fO'#JsOOQ!0Lh'#Ci'#CiO%[QlO'#ESO!$[Q!fO,5:sOOQS'#Jz'#JzOOQO-EtOOQ['#Jh'#JhOOQ[,5>u,5>uOOQ[-E<]-E<]O!TO`QlO,5>VO!LOQ`O,5>XO`QlO,5>ZO!LTQ`O,5>^O!LYQlO,5>dOOQ[,5>j,5>jO%[QlO,5>jO9uQ!0LrO,5>lOOQ[,5>n,5>nO#!dQ`O,5>nOOQ[,5>p,5>pO#!dQ`O,5>pOOQ[,5>r,5>rO##QQpO'#D_O%[QlO'#JvO##sQpO'#JvO##}QpO'#DmO#$`QpO'#DmO#&qQlO'#DmO#&xQ`O'#JuO#'QQ`O,5:WO#'VQ`O'#EtO#'eQ`O'#KUO#'mQ`O,5;_O#'rQpO'#DmO#(PQpO'#EVOOQ!0Lf,5:o,5:oO%[QlO,5:oO#(WQ`O,5:oO?YQ`O,5;YO!CUQpO,5;YO!C^QMhO,5;YO:dQMhO,5;YO#(`Q`O,5@bO#(eQ07dO,5:sOOQO-EPO$6^Q`O,5>POOQ[1G3i1G3iO`QlO1G3iOOQ[1G3o1G3oOOQ[1G3q1G3qO?TQ`O1G3sO$6cQlO1G3uO$:gQlO'#HtOOQ[1G3x1G3xO$:tQ`O'#HzO?YQ`O'#H|OOQ[1G4O1G4OO$:|QlO1G4OO9uQ!0LrO1G4UOOQ[1G4W1G4WOOQ!0Lb'#G_'#G_O9uQ!0LrO1G4YO9uQ!0LrO1G4[O$?TQ`O,5@bO!)[QlO,5;`O9eQ`O,5;`O?YQ`O,5:XO!)[QlO,5:XO!CUQpO,5:XO$?YQ?MtO,5:XOOQO,5;`,5;`O$?dQpO'#IeO$?zQ`O,5@aOOQ!0Lf1G/r1G/rO$@SQpO'#IkO$@^Q`O,5@pOOQ!0Lb1G0y1G0yO#$`QpO,5:XOOQO'#Ig'#IgO$@fQpO,5:qOOQ!0Ln,5:q,5:qO#(ZQ`O1G0ZOOQ!0Lf1G0Z1G0ZO%[QlO1G0ZOOQ!0Lf1G0t1G0tO?YQ`O1G0tO!CUQpO1G0tO!C^QMhO1G0tOOQ!0Lb1G5|1G5|O!ByQ!0LrO1G0^OOQO1G0m1G0mO%[QlO1G0mO$@mQ!0LrO1G0mO$@xQ!0LrO1G0mO!CUQpO1G0^ODWQpO1G0^O$AWQ!0LrO1G0mOOQO1G0^1G0^O$AlQ!0MxO1G0mPOOO-E<[-E<[POOO1G.h1G.hOOOO1G/i1G/iO$AvQ!bO,5QQpO,5@}OOQ!0Lb1G3c1G3cOOQ[7+$V7+$VO@zQ`O7+$VO9uQ!0LrO7+$VO%>]Q`O7+$VO%[QlO1G6lO%[QlO1G6mO%>bQ!0LrO1G6lO%>lQlO1G3kO%>sQ`O1G3kO%>xQlO1G3kOOQ[7+)T7+)TO9uQ!0LrO7+)_O`QlO7+)aOOQ['#Kh'#KhOOQ['#JS'#JSO%?PQlO,5>`OOQ[,5>`,5>`O%[QlO'#HuO%?^Q`O'#HwOOQ[,5>f,5>fO9eQ`O,5>fOOQ[,5>h,5>hOOQ[7+)j7+)jOOQ[7+)p7+)pOOQ[7+)t7+)tOOQ[7+)v7+)vO%?cQpO1G5|O%?}Q?MtO1G0zO%@XQ`O1G0zOOQO1G/s1G/sO%@dQ?MtO1G/sO?YQ`O1G/sO!)[QlO'#DmOOQO,5?P,5?POOQO-ERQ`O7+,WO&>WQ`O7+,XO%[QlO7+,WO%[QlO7+,XOOQ[7+)V7+)VO&>]Q`O7+)VO&>bQlO7+)VO&>iQ`O7+)VOOQ[<nQ`O,5>aOOQ[,5>c,5>cO&>sQ`O1G4QO9eQ`O7+&fO!)[QlO7+&fOOQO7+%_7+%_O&>xQ?MtO1G6ZO?YQ`O7+%_OOQ!0Lf<yQ?MvO,5?aO'@|Q?MvO,5?cO'CPQ?MvO7+'|O'DuQMjOG27TOOQO<VO!l$xO#jROe!iOpkOrPO(T)]O(VTO(YUO(aVO(o[O~O!]$_Oa$qa'z$qa'w$qa!k$qa!Y$qa!_$qa%i$qa!g$qa~Ol)dO~P!&zOh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Og(pP~P!,TO!Q)iO!g)hO!_$^X$Z$^X$]$^X$_$^X$f$^X~O!g)hO!_({X$Z({X$]({X$_({X$f({X~O!Q)iO~P!.^O!Q)iO!_({X$Z({X$]({X$_({X$f({X~O!_)kO$Z)oO$])jO$_)jO$f)pO~O![)sO~P!)[O$]$hO$_$gO$f)wO~On$zX!Q$zX#S$zX'y$zX(y$zX(z$zX~OgmXg$zXnmX!]mX#`mX~P!0SOx)yO(b)zO(c)|O~On*VO!Q*OO'y*PO(y$}O(z%PO~Og)}O~P!1WOg*WO~Oh%VOr%XOs$tOt$tOz%YO|%ZO!OVO!l$xO#jVO!l$xO#jROe!iOpkOrPO(VTO(YUO(aVO(o[O~O(T=QO~P#$qO!]-]O!^(iX~O!^-_O~O!g-VO#`-UO!]#hX!^#hX~O!]-`O!^(xX~O!^-bO~O!c-cO!d-cO(U!lO~P#$`O!^-fO~P'_On-iO!_'`O~O!Y-nO~Os!{a!b!{a!c!{a!d!{a#T!{a#U!{a#V!{a#W!{a#X!{a#[!{a#]!{a(U!{a(V!{a(Y!{a(e!{a(o!{a~P!#vO!p-sO#`-qO~PChO!c-uO!d-uO(U!lO~PDWOa%nO#`-qO'z%nO~Oa%nO!g#vO#`-qO'z%nO~Oa%nO!g#vO!p-sO#`-qO'z%nO(r'pO~O(P'xO(Q'xO(R-zO~Ov-{O~O!Y'Wa!]'Wa~P!:tO![.PO!Y'WX!]'WX~P%[O!](VO!Y(ha~O!Y(ha~PHRO!](^O!Y(va~O!S%hO![.TO!_%iO(T%gO!Y'^X!]'^X~O#`.VO!](ta!k(taa(ta'z(ta~O!g#vO~P#,wO!](jO!k(sa~O!S%hO!_%iO#j.ZO(T%gO~Op.`O!S%hO![.]O!_%iO!|]O#i._O#j.]O(T%gO!]'aX!k'aX~OR.dO!l#xO~Oh%VOn.gO!_'`O%i.fO~Oa#ci!]#ci'z#ci'w#ci!Y#ci!k#civ#ci!_#ci%i#ci!g#ci~P!:tOn>]O!Q*OO'y*PO(y$}O(z%PO~O#k#_aa#_a#`#_a'z#_a!]#_a!k#_a!_#_a!Y#_a~P#/sO#k(`XP(`XR(`X[(`Xa(`Xj(`Xr(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X'z(`X(a(`X(r(`X!k(`X!Y(`X'w(`Xv(`X!_(`X%i(`X!g(`X~P!6kO!].tO!k(kX~P!:tO!k.wO~O!Y.yO~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mia#mij#mir#mi!]#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#n#mi~P#3cO#n$OO~P#3cOP$[OR#zOr$aO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO[#mia#mij#mi!]#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#r#mi~P#6QO#r$QO~P#6QOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO(aVOa#mi!]#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#v#mi~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO(aVO(z#}Oa#mi!]#mi#z#mi#{#mi'z#mi(r#mi(y#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#x$UO~P#;VO#x#mi~P#;VO#v$SO~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO(aVO(y#|O(z#}Oa#mi!]#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#z#mi~P#={O#z$WO~P#={OP]XR]X[]Xj]Xr]X!Q]X!S]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X!]]X!^]X~O$O]X~P#@jOP$[OR#zO[]O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P#EyO!]/POg(pX~P!1WOg/RO~Oa$Pi!]$Pi'z$Pi'w$Pi!Y$Pi!k$Piv$Pi!_$Pi%i$Pi!g$Pi~P!:tO$]/SO$_/SO~O$]/TO$_/TO~O!g)hO#`/UO!_$cX$Z$cX$]$cX$_$cX$f$cX~O![/VO~O!_)kO$Z/XO$])jO$_)jO$f/YO~O!]VO!l$xO#j^O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P&,QO#S$dOP(`XR(`X[(`Xj(`Xn(`Xr(`X!Q(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X$O(`X'y(`X(a(`X(r(`X(y(`X(z(`X!](`X!^(`X~O$O$Pi!]$Pi!^$Pi~P#BwO$O!ri!^!ri~P$+oOg']a!]']a~P!1WO!^7nO~O!]'da!^'da~P#BwO!Y7oO~P#/sO!g#vO(r'pO!]'ea!k'ea~O!]/pO!k)Oi~O!]/pO!g#vO!k)Oi~Og$|q!]$|q#`$|q$O$|q~P!1WO!Y'ga!]'ga~P#/sO!g7vO~O!]/yO!Y)Pi~P#/sO!]/yO!Y)Pi~O!Y7yO~Oh%VOr8OO!l%eO(r'pO~Oj8QO!g#vO~Or8TO!g#vO(r'pO~O!Q*OO'y*PO(z%POn'ja(y'ja!]'ja#`'ja~Og'ja$O'ja~P&5RO!Q*OO'y*POn'la(y'la(z'la!]'la#`'la~Og'la$O'la~P&5tOg(_q!](_q~P!1WO#`8VOg(_q!](_q~P!1WO!Y8WO~Og%Oq!]%Oq#`%Oq$O%Oq~P!1WOa$oy!]$oy'z$oy'w$oy!Y$oy!k$oyv$oy!_$oy%i$oy!g$oy~P!:tO!g6rO~O!]5[O!_)Qa~O!_'`OP$TaR$Ta[$Taj$Tar$Ta!Q$Ta!S$Ta!]$Ta!l$Ta!p$Ta#R$Ta#n$Ta#o$Ta#p$Ta#q$Ta#r$Ta#s$Ta#t$Ta#u$Ta#v$Ta#x$Ta#z$Ta#{$Ta(a$Ta(r$Ta(y$Ta(z$Ta~O%i7WO~P&8fO%^8[Oa%[i!_%[i'z%[i!]%[i~Oa#cy!]#cy'z#cy'w#cy!Y#cy!k#cyv#cy!_#cy%i#cy!g#cy~P!:tO[8^O~Ob8`O(T+qO(VTO(YUO~O!]1TO!^)Xi~O`8dO~O(e(|O!]'pX!^'pX~O!]5uO!^)Ua~O!^8nO~P%;eO(o!sO~P$&YO#[8oO~O!_1oO~O!_1oO%i8qO~On8tO!_1oO%i8qO~O[8yO!]'sa!^'sa~O!]1zO!^)Vi~O!k8}O~O!k9OO~O!k9RO~O!k9RO~P%[Oa9TO~O!g9UO~O!k9VO~O!](wi!^(wi~P#BwOa%nO#`9_O'z%nO~O!](ty!k(tya(ty'z(ty~P!:tO!](jO!k(sy~O%i9bO~P&8fO!_'`O%i9bO~O#k$|qP$|qR$|q[$|qa$|qj$|qr$|q!S$|q!]$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q'z$|q(a$|q(r$|q!k$|q!Y$|q'w$|q#`$|qv$|q!_$|q%i$|q!g$|q~P#/sO#k'jaP'jaR'ja['jaa'jaj'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja'z'ja(a'ja(r'ja!k'ja!Y'ja'w'jav'ja!_'ja%i'ja!g'ja~P&5RO#k'laP'laR'la['laa'laj'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la'z'la(a'la(r'la!k'la!Y'la'w'lav'la!_'la%i'la!g'la~P&5tO#k%OqP%OqR%Oq[%Oqa%Oqj%Oqr%Oq!S%Oq!]%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq'z%Oq(a%Oq(r%Oq!k%Oq!Y%Oq'w%Oq#`%Oqv%Oq!_%Oq%i%Oq!g%Oq~P#/sO!]'Yi!k'Yi~P!:tO$O#cq!]#cq!^#cq~P#BwO(y$}OP%aaR%aa[%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa$O%aa(a%aa(r%aa!]%aa!^%aa~On%aa!Q%aa'y%aa(z%aa~P&IyO(z%POP%caR%ca[%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca$O%ca(a%ca(r%ca!]%ca!^%ca~On%ca!Q%ca'y%ca(y%ca~P&LQOn>^O!Q*OO'y*PO(z%PO~P&IyOn>^O!Q*OO'y*PO(y$}O~P&LQOR0kO!Q0kO!S0lO#S$dOP}a[}aj}an}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a$O}a'y}a(a}a(r}a(y}a(z}a!]}a!^}a~O!Q*OO'y*POP$saR$sa[$saj$san$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa$O$sa(a$sa(r$sa(y$sa(z$sa!]$sa!^$sa~O!Q*OO'y*POP$uaR$ua[$uaj$uan$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua$O$ua(a$ua(r$ua(y$ua(z$ua!]$ua!^$ua~On>^O!Q*OO'y*PO(y$}O(z%PO~OP%TaR%Ta[%Taj%Tar%Ta!S%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta$O%Ta(a%Ta(r%Ta!]%Ta!^%Ta~P''VO$O$mq!]$mq!^$mq~P#BwO$O$oq!]$oq!^$oq~P#BwO!^9oO~O$O9pO~P!1WO!g#vO!]'ei!k'ei~O!g#vO(r'pO!]'ei!k'ei~O!]/pO!k)Oq~O!Y'gi!]'gi~P#/sO!]/yO!Y)Pq~Or9wO!g#vO(r'pO~O[9yO!Y9xO~P#/sO!Y9xO~Oj:PO!g#vO~Og(_y!](_y~P!1WO!]'na!_'na~P#/sOa%[q!_%[q'z%[q!]%[q~P#/sO[:UO~O!]1TO!^)Xq~O`:YO~O#`:ZO!]'pa!^'pa~O!]5uO!^)Ui~P#BwO!S:]O~O!_1oO%i:`O~O(VTO(YUO(e:eO~O!]1zO!^)Vq~O!k:hO~O!k:iO~O!k:jO~O!k:jO~P%[O#`:mO!]#hy!^#hy~O!]#hy!^#hy~P#BwO%i:rO~P&8fO!_'`O%i:rO~O$O#|y!]#|y!^#|y~P#BwOP$|iR$|i[$|ij$|ir$|i!S$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i$O$|i(a$|i(r$|i!]$|i!^$|i~P''VO!Q*OO'y*PO(z%POP'iaR'ia['iaj'ian'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia$O'ia(a'ia(r'ia(y'ia!]'ia!^'ia~O!Q*OO'y*POP'kaR'ka['kaj'kan'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka$O'ka(a'ka(r'ka(y'ka(z'ka!]'ka!^'ka~O(y$}OP%aiR%ai[%aij%ain%air%ai!Q%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai$O%ai'y%ai(a%ai(r%ai(z%ai!]%ai!^%ai~O(z%POP%ciR%ci[%cij%cin%cir%ci!Q%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci$O%ci'y%ci(a%ci(r%ci(y%ci!]%ci!^%ci~O$O$oy!]$oy!^$oy~P#BwO$O#cy!]#cy!^#cy~P#BwO!g#vO!]'eq!k'eq~O!]/pO!k)Oy~O!Y'gq!]'gq~P#/sOr:|O!g#vO(r'pO~O[;QO!Y;PO~P#/sO!Y;PO~Og(_!R!](_!R~P!1WOa%[y!_%[y'z%[y!]%[y~P#/sO!]1TO!^)Xy~O!]5uO!^)Uq~O(T;XO~O!_1oO%i;[O~O!k;_O~O%i;dO~P&8fOP$|qR$|q[$|qj$|qr$|q!S$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q$O$|q(a$|q(r$|q!]$|q!^$|q~P''VO!Q*OO'y*PO(z%POP'jaR'ja['jaj'jan'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja$O'ja(a'ja(r'ja(y'ja!]'ja!^'ja~O!Q*OO'y*POP'laR'la['laj'lan'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la$O'la(a'la(r'la(y'la(z'la!]'la!^'la~OP%OqR%Oq[%Oqj%Oqr%Oq!S%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq$O%Oq(a%Oq(r%Oq!]%Oq!^%Oq~P''VOg%e!Z!]%e!Z#`%e!Z$O%e!Z~P!1WO!Y;hO~P#/sOr;iO!g#vO(r'pO~O[;kO!Y;hO~P#/sO!]'pq!^'pq~P#BwO!]#h!Z!^#h!Z~P#BwO#k%e!ZP%e!ZR%e!Z[%e!Za%e!Zj%e!Zr%e!Z!S%e!Z!]%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z'z%e!Z(a%e!Z(r%e!Z!k%e!Z!Y%e!Z'w%e!Z#`%e!Zv%e!Z!_%e!Z%i%e!Z!g%e!Z~P#/sOr;tO!g#vO(r'pO~O!Y;uO~P#/sOr;|O!g#vO(r'pO~O!Y;}O~P#/sOP%e!ZR%e!Z[%e!Zj%e!Zr%e!Z!S%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z$O%e!Z(a%e!Z(r%e!Z!]%e!Z!^%e!Z~P''VOrROe!iOpkOrPO(T)]O(VTO(YUO(aVO(o[O~O!]WO!l$xO#jgPPP!>oI[PPPPPPPPP!BOP!C]PPI[!DnPI[PI[I[I[I[I[PI[!FQP!I[P!LbP!Lf!Lp!Lt!LtP!IXP!Lx!LxP#!OP#!SI[PI[#!Y#%_CjA^PA^PA^A^P#&lA^A^#)OA^#+vA^#.SA^A^#.r#1W#1W#1]#1f#1W#1qPP#1WPA^#2ZA^#6YA^A^6mPPP#:_PPP#:x#:xP#:xP#;`#:xPP#;fP#;]P#;]#;y#;]#P#>V#>]#>k#>q#>{#?R#?]#?c#?s#?y#@k#@}#AT#AZ#Ai#BO#Cs#DR#DY#Et#FS#Gt#HS#HY#H`#Hf#Hp#Hv#H|#IW#Ij#IpPPPPPPPPPPP#IvPPPPPPP#Jk#Mx$ b$ i$ qPPP$']P$'f$*_$0x$0{$1O$1}$2Q$2X$2aP$2g$2jP$3W$3[$4S$5b$5g$5}PP$6S$6Y$6^$6a$6e$6i$7e$7|$8e$8i$8l$8o$8y$8|$9Q$9UR!|RoqOXst!Z#d%m&r&t&u&w,s,x2[2_Y!vQ'`-e1o5{Q%tvQ%|yQ&T|Q&j!VS'W!e-]Q'f!iS'l!r!yU*k$|*Z*oQ+o%}S+|&V&WQ,d&dQ-c'_Q-m'gQ-u'mQ0[*qQ1b,OQ1y,eR<{SU+P%]S!S!nQ!r!v!y!z$|'W'_'`'l'm'n*k*o*q*r-]-c-e-u0[0_1o5{5}%[$ti#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;kP>X>Y>]>^Q&X|Q'U!eS'[%i-`Q+t&PQ,P&WQ,f&gQ0n+SQ1Y+uQ1_+{Q2Q,jQ2R,kQ5f1TQ5o1aQ6[1zQ6_1|Q6`2PQ8`5gQ8c5lQ8|6bQ:X8dQ:f8yQ;V:YR<}*ZrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R,h&k&z^OPXYstuvwz!Z!`!g!j!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'b'r(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mR>S[#]WZ#W#Z'X(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ%wxQ%{yW&Q|&V&W,OQ&_!TQ'c!hQ'e!iQ(q#sS+n%|%}Q+r&PQ,_&bQ,c&dS-l'f'gQ.i(rQ1R+oQ1X+uQ1Z+vQ1^+zQ1t,`S1x,d,eQ2|-mQ5e1TQ5i1WQ5n1`Q6Z1yQ8_5gQ8b5kQ8f5pQ:T8^R;T:U!U$zi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y!^%yy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{Q+h%wQ,T&[Q,W&]Q,b&dQ.h(qQ1s,_U1w,c,d,eQ3e.iQ6U1tS6Y1x1yQ8x6Z#f>T#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^o>UPS&[!Q&iQ&]!RQ&^!SU*}%[%d=sR,R&Y%]%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;kP>X>Y>]>^T)z$u){V+P%]S$i$^c#Y#e%q%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.|.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`SQ'Y!eR2q-]!W!nQ!e!r!v!y!z$|'W'_'`'l'm'n*Z*k*o*q*r-]-c-e-u0[0_1o5{5}R1l,ZnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&y!^Q'v!xS(s#u<^Q+l%zQ,]&_Q,^&aQ-j'dQ-w'oS.r(x=PS0q+X=ZQ1P+mQ1n,[Q2c,zQ2e,{Q2m-WQ2z-kQ2}-oS5Y0r=eQ5a1QS5d1S=fQ6t2oQ6x2{Q6}3SQ8]5bQ9Y6vQ9Z6yQ9^7OR:l9V$d$]c#Y#e%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`SS#q]SU$fd)_,mS(p#p'iU*v%R(w4OU0m+O.n7gQ5^0xQ7V3`Q9d7YR:s9em!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}Q't!uS(f#g2US-s'k'wQ/s*]Q0R*jQ3U-vQ4f/tQ4r0TQ4s0UQ4x0^Q7r4`S7}4t4vS8R4y4{Q9r7sQ9v7yQ9{8OQ:Q8TS:{9w9xS;g:|;PS;s;h;iS;{;t;uSSR=o>R%^bOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Q%fj!^%xy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{S&Oz!jQ+k%yQ,a&dW1v,b,c,d,eU6X1w1x1yS8w6Y6ZQ:d8x!r=j$Z$n'X)s-U-X/V2p4T5w6s:Z:mSQ=t>QR=u>R%QeOPXYstuvw!Z!`!g!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Y#bWZ#W#Z(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ,n&o!p=k$Z$n)s-U-X/V2p4T5w6s:Z:mSR=n'XU']!e%i*ZR2s-`%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:mSQ,m&oQ0x+gQ3`.gQ7Y3dR9e7[!b$Tc#Y%q(S(Y(t(y)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:oS)^)q-Z.|2k2n3p4P4X6u7b7k7l8k9X9g9m9n;W;`=vQ>X>ZR>Y>['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mSS$oh$pR4U/U'XgOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mST$kf$qQ$ifS)j$l)nR)v$qT$jf$qT)l$l)n'XhOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:mST$oh$pQ$rhR)u$p%^jOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_!s>Q$Z$n'X)s-U-X/V2p4T5w6s:Z:mS#glOPXZst!Z!`!o#S#d#o#{$n%m&k&n&o&r&t&u&w&{'T'b)O)s*i+]+g,p,s,x-i.g/V/n0]0l1r2S2T2V2X2[2_2a3d4T4z6T6e6f6i7[8t9T!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^Q+T%aQ/c*Oo4OP>X>YQ*c$zU*l$|*Z*oQ+U%bQ0W*m#f=q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^n=rTQ=x>UQ=y>VR=z>W!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k]>^o4OP>X>Y>]>^Q,U&]Q1h,WQ5s1gR8h5tV*n$|*Z*oU*n$|*Z*oT5z1o5{S0P*i/nQ4w0]T8S4z:]Q+j%xQ0V*lQ1O+kQ1u,aQ6W1vQ8v6XQ:c8wR;^:d!U%Oi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Yx*R$v)e*S*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>OS0`*t0a#f]>^nZ>[`=T3}7c7f7j9h:t:w;yS=_.l3iT=`7e9k!U%Qi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y|*T$v)e*U*t+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>OS0b*u0c#f]>^nZ>[d=V3}7d7e7j9h9i:t:u:w;yS=a.m3jT=b7f9lrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q&f!UR,p&ornOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R&f!UQ,Y&^R1d,RsnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q1p,_S6R1s1tU8p6P6Q6US:_8r8sS;Y:^:aQ;m;ZR;w;nQ&m!VR,i&iR6_1|R:f8yW&Q|&V&W,OR1Z+vQ&r!WR,s&sR,y&xT2],x2_R,}&yQ,|&yR2f,}Q'y!{R-y'ySsOtQ#dXT%ps#dQ#OTR'{#OQ#RUR'}#RQ){$uR/`){Q#UVR(Q#UQ#XWU(W#X(X.QQ(X#YR.Q(YQ-^'YR2r-^Q.u(yS3m.u3nR3n.vQ-e'`R2v-eY!rQ'`-e1o5{R'j!rQ/Q)eR4S/QU#_W%h*YU(_#_(`.RQ(`#`R.R(ZQ-a']R2t-at`OXst!V!Z#d%m&i&k&r&t&u&w,s,x2[2_S#hZ%eU#r`#h.[R.[(jQ(k#jQ.X(gW.a(k.X3X7RQ3X.YR7R3YQ)n$lR/W)nQ$phR)t$pQ$`cU)a$`-|O>Z>[Q/z*eU4k/z4m7xQ4m/|R7x4lS*o$|*ZR0Y*ox*S$v)e*t*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>O!d.j(u)c*[*e.l.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/h*S.j7ca7c3}7e7f7j9h:t:w;yQ0a*tQ3i.lU4}0a3i9kR9k7e|*U$v)e*t*u+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>O!h.k(u)c*[*e.l.m.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/j*U.k7de7d3}7e7f7j9h9i:t:u:w;yQ0c*uQ3j.mU5P0c3j9lR9l7fQ*z%UR0g*zQ5]0vR8Y5]Q+_%kR0u+_Q5v1jS8j5v:[R:[8kQ,[&_R1m,[Q5{1oR8m5{Q1{,fS6]1{8zR8z6_Q1U+rW5h1U5j8a:VQ5j1XQ8a5iR:V8bQ+w&QR1[+wQ2_,xR6m2_YrOXst#dQ&v!ZQ+a%mQ,r&rQ,t&tQ,u&uQ,w&wQ2Y,sS2],x2_R6l2[Q%opQ&z!_Q&}!aQ'P!bQ'R!cQ'q!uQ+`%lQ+l%zQ,Q&XQ,h&mQ-P&|W-p'k's't'wQ-w'oQ0X*nQ1P+mQ1c,PS2O,i,lQ2g-OQ2h-RQ2i-SQ2}-oW3P-r-s-v-xQ5a1QQ5m1_Q5q1eQ6V1uQ6a2QQ6k2ZU6z3O3R3UQ6}3SQ8]5bQ8e5oQ8g5rQ8l5zQ8u6WQ8{6`S9[6{7PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:Lb,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[Vb],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rp)wU(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)rp*^P;=`<%l)r'[*dP;=`<%l(r#S*nX(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g#S+^P;=`<%l*g(n+dP;=`<%l%Z07[+rq$i&j(Wp(Z!b'|0/lOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p$f%Z$f$g+g$g#BY%Z#BY#BZ+g#BZ$IS%Z$IS$I_+g$I_$JT%Z$JT$JU+g$JU$KV%Z$KV$KW+g$KW&FU%Z&FU&FV+g&FV;'S%Z;'S;=`+a<%l?HT%Z?HT?HU+g?HUO%Z07[.ST(X#S$i&j'}0/lO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c07[.n_$i&j(Wp(Z!b'}0/lOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)3p/x`$i&j!p),Q(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW1V`#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`2X!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW2d_#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At3l_(V':f$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k(^4r_$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k&z5vX$i&jOr5qrs6cs!^5q!^!_6y!_#o5q#o#p6y#p;'S5q;'S;=`7h<%lO5q&z6jT$d`$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c`6|TOr6yrs7]s;'S6y;'S;=`7b<%lO6y`7bO$d``7eP;=`<%l6y&z7kP;=`<%l5q(^7w]$d`$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!r8uZ(Z!bOY8pYZ6yZr8prs9hsw8pwx6yx#O8p#O#P6y#P;'S8p;'S;=`:R<%lO8p!r9oU$d`(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!r:UP;=`<%l8p(^:[P;=`<%l4k%9[:hh$i&j(Wp(Z!bOY%ZYZ&cZq%Zqr`#P#o`x!^=^!^!_?q!_#O=^#O#P>`#P#o=^#o#p?q#p;'S=^;'S;=`@h<%lO=^&n>gXWS$i&jOY>`YZ&cZ!^>`!^!_?S!_#o>`#o#p?S#p;'S>`;'S;=`?k<%lO>`S?XSWSOY?SZ;'S?S;'S;=`?e<%lO?SS?hP;=`<%l?S&n?nP;=`<%l>`!f?xWWS(Z!bOY?qZw?qwx?Sx#O?q#O#P?S#P;'S?q;'S;=`@b<%lO?q!f@eP;=`<%l?q(Q@kP;=`<%l=^'`@w]WS$i&j(WpOY@nYZ&cZr@nrs>`s!^@n!^!_Ap!_#O@n#O#P>`#P#o@n#o#pAp#p;'S@n;'S;=`Bg<%lO@ntAwWWS(WpOYApZrAprs?Ss#OAp#O#P?S#P;'SAp;'S;=`Ba<%lOAptBdP;=`<%lAp'`BjP;=`<%l@n#WBvYWS(Wp(Z!bOYBmZrBmrs?qswBmwxApx#OBm#O#P?S#P;'SBm;'S;=`Cf<%lOBm#WCiP;=`<%lBm(rCoP;=`<%l^!Q^$i&j!X7`OY!=yYZ&cZ!P!=y!P!Q!>|!Q!^!=y!^!_!@c!_!}!=y!}#O!CW#O#P!Dy#P#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y|#X#Z&c#Z#[!>|#[#]&c#]#^!>|#^#a&c#a#b!>|#b#g&c#g#h!>|#h#i&c#i#j!>|#j#k!>|#k#m&c#m#n!>|#n#o&c#p;'S&c;'S;=`&w<%lO&c7`!@hX!X7`OY!@cZ!P!@c!P!Q!AT!Q!}!@c!}#O!Ar#O#P!Bq#P;'S!@c;'S;=`!CQ<%lO!@c7`!AYW!X7`#W#X!AT#Z#[!AT#]#^!AT#a#b!AT#g#h!AT#i#j!AT#j#k!AT#m#n!AT7`!AuVOY!ArZ#O!Ar#O#P!B[#P#Q!@c#Q;'S!Ar;'S;=`!Bk<%lO!Ar7`!B_SOY!ArZ;'S!Ar;'S;=`!Bk<%lO!Ar7`!BnP;=`<%l!Ar7`!BtSOY!@cZ;'S!@c;'S;=`!CQ<%lO!@c7`!CTP;=`<%l!@c^!Ezl$i&j(Z!b!X7`OY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#W&}#W#X!Eq#X#Z&}#Z#[!Eq#[#]&}#]#^!Eq#^#a&}#a#b!Eq#b#g&}#g#h!Eq#h#i&}#i#j!Eq#j#k!Eq#k#m&}#m#n!Eq#n#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}8r!GyZ(Z!b!X7`OY!GrZw!Grwx!@cx!P!Gr!P!Q!Hl!Q!}!Gr!}#O!JU#O#P!Bq#P;'S!Gr;'S;=`!J|<%lO!Gr8r!Hse(Z!b!X7`OY'}Zw'}x#O'}#P#W'}#W#X!Hl#X#Z'}#Z#[!Hl#[#]'}#]#^!Hl#^#a'}#a#b!Hl#b#g'}#g#h!Hl#h#i'}#i#j!Hl#j#k!Hl#k#m'}#m#n!Hl#n;'S'};'S;=`(f<%lO'}8r!JZX(Z!bOY!JUZw!JUwx!Arx#O!JU#O#P!B[#P#Q!Gr#Q;'S!JU;'S;=`!Jv<%lO!JU8r!JyP;=`<%l!JU8r!KPP;=`<%l!Gr>^!KZ^$i&j(Z!bOY!KSYZ&cZw!KSwx!CWx!^!KS!^!_!JU!_#O!KS#O#P!DR#P#Q!^!LYP;=`<%l!KS>^!L`P;=`<%l!_#c#d#Bq#d#l%Z#l#m#Es#m#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#>j_$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#?rd$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#A]f$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Bzc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Dbe$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#E|g$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Gpi$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x#Il_!g$b$i&j$O)Lv(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)[#Jv_al$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f#LS^h#)`#R-v$?V_!^(CdvBr$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z?O$@a_!q7`$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$Aq|$i&j(Wp(Z!b'|0/l$]#t(T,2j(e$I[OX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[Eb,zb,_b,Wb,2,3,4,5,6,7,8,9,10,11,12,13,14,Yb,new vr("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new vr("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>Bb[n]||-1},{term:343,get:n=>qb[n]||-1},{term:95,get:n=>Db[n]||-1}],tokenPrec:15201}),tO=[ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),ye(`try { \${} } catch (\${error}) { \${} -}`,{label:"try",detail:"/ catch block",type:"keyword"}),xe("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),xe(`if (\${}) { +}`,{label:"try",detail:"/ catch block",type:"keyword"}),ye("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),ye(`if (\${}) { \${} } else { \${} -}`,{label:"if",detail:"/ else block",type:"keyword"}),xe(`class \${name} { +}`,{label:"if",detail:"/ else block",type:"keyword"}),ye(`class \${name} { constructor(\${params}) { \${} } -}`,{label:"class",detail:"definition",type:"keyword"}),xe('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),xe('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Db=eO.concat([xe("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),xe("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),xe("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Xh=new af,tO=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function Mi(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const Ib=["FunctionDeclaration"],Nb={FunctionDeclaration:Mi("function"),ClassDeclaration:Mi("class"),ClassExpression:()=>!0,EnumDeclaration:Mi("constant"),TypeAliasDeclaration:Mi("type"),NamespaceDeclaration:Mi("namespace"),VariableDefinition(n,e){n.matchContext(Ib)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function iO(n,e){let t=Xh.get(e);if(t)return t;let i=[],r=!0;function s(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(D.IncludeAnonymous).iterate(o=>{if(r)r=!1;else if(o.name){let l=Nb[o.name];if(l&&l(o,s)||tO.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of iO(n,o.node))i.push(l);return!1}}),Xh.set(e,i),i}const Ah=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,nO=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Gb(n){let e=J(n.state).resolveInner(n.pos,-1);if(nO.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Ah.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let r=e;r;r=r.parent)tO.has(r.name)&&(i=i.concat(iO(n.state.doc,r)));return{options:i,from:t?e.from:n.pos,validFor:Ah}}const lt=mi.define({name:"javascript",parser:qb.configure({props:[Sn.add({IfStatement:Kn({except:/^\s*({|else\b)/}),TryStatement:Kn({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:Im,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:Dm({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Kn({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),ki.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":gf,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),rO={test:n=>/^JSX/.test(n.name),facet:Fo({commentTokens:{block:{open:"{/*",close:"*/}"}}})},sO=lt.configure({dialect:"ts"},"typescript"),oO=lt.configure({dialect:"jsx",props:[Ho.add(n=>n.isTop?[rO]:void 0)]}),lO=lt.configure({dialect:"jsx ts",props:[Ho.add(n=>n.isTop?[rO]:void 0)]},"typescript");let aO=n=>({label:n,type:"keyword"});const hO="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(aO),Ub=hO.concat(["declare","implements","private","protected","public"].map(aO));function Fb(n={}){let e=n.jsx?n.typescript?lO:oO:n.typescript?sO:lt,t=n.typescript?Db.concat(Ub):eO.concat(hO);return new rn(e,[lt.data.of({autocomplete:Z0(nO,lu(t))}),lt.data.of({autocomplete:Gb}),n.jsx?Jb:[]])}function Hb(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function Rh(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const Kb=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Jb=C.inputHandler.of((n,e,t,i,r)=>{if((Kb?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!lt.isActiveAt(n.state,e,-1))return!1;let s=r(),{state:o}=s,l=o.changeByRange(a=>{var h;let{head:c}=a,f=J(o).resolveInner(c-1,-1),u;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(c-1,c)!=i||f.name=="JSXAttributeValue"&&f.to>c)){if(i==">"&&f.name=="JSXFragmentTag")return{range:a,changes:{from:c,insert:""}};if(i=="/"&&f.name=="JSXStartCloseTag"){let O=f.parent,d=O.parent;if(d&&O.from==c-2&&((u=Rh(o.doc,d.firstChild,c))||((h=d.firstChild)===null||h===void 0?void 0:h.name)=="JSXFragmentTag")){let p=`${u}>`;return{range:y.cursor(c+p.length,-1),changes:{from:c,insert:p}}}}else if(i==">"){let O=Hb(f);if(O&&O.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(c,c+2))&&(u=Rh(o.doc,O,c)))return{range:a,changes:{from:c,insert:``}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([s,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ji=["_blank","_self","_top","_parent"],$s=["ascii","utf-8","utf-16","latin1","latin1"],Ps=["get","post","put","delete"],vs=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],Te=["true","false"],X={},eQ={a:{attrs:{href:null,ping:null,type:null,media:null,target:ji,hreflang:null}},abbr:X,address:X,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:X,aside:X,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:X,base:{attrs:{href:null,target:ji}},bdi:X,bdo:X,blockquote:{attrs:{cite:null}},body:X,br:X,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:vs,formmethod:Ps,formnovalidate:["novalidate"],formtarget:ji,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:X,center:X,cite:X,code:X,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:X,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:X,div:X,dl:X,dt:X,em:X,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:X,figure:X,footer:X,form:{attrs:{action:null,name:null,"accept-charset":$s,autocomplete:["on","off"],enctype:vs,method:Ps,novalidate:["novalidate"],target:ji}},h1:X,h2:X,h3:X,h4:X,h5:X,h6:X,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:X,hgroup:X,hr:X,html:{attrs:{manifest:null}},i:X,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:vs,formmethod:Ps,formnovalidate:["novalidate"],formtarget:ji,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:X,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:X,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:X,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:$s,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:X,noscript:X,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:X,param:{attrs:{name:null,value:null}},pre:X,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:X,rt:X,ruby:X,samp:X,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:$s}},section:X,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:X,source:{attrs:{src:null,type:null,media:null}},span:X,strong:X,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:X,summary:X,sup:X,table:X,tbody:X,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:X,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:X,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:X,time:{attrs:{datetime:null}},title:X,tr:X,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:X,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:X},cO={accesskey:null,class:null,contenteditable:Te,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:Te,autocorrect:Te,autocapitalize:Te,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":Te,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Te,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Te,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Te,"aria-hidden":Te,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Te,"aria-multiselectable":Te,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Te,"aria-relevant":null,"aria-required":Te,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},fO="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(n=>"on"+n);for(let n of fO)cO[n]=null;class cn{constructor(e,t){this.tags={...eQ,...e},this.globalAttrs={...cO,...t},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}cn.default=new cn;function It(n,e,t=n.length){if(!e)return"";let i=e.firstChild,r=i&&i.getChild("TagName");return r?n.sliceString(r.from,Math.min(r.to,t)):""}function yi(n,e=!1){for(;n;n=n.parent)if(n.name=="Element")if(e)e=!1;else return n;return null}function uO(n,e,t){let i=t.tags[It(n,yi(e))];return i?.children||t.allTags}function bl(n,e){let t=[];for(let i=yi(e);i&&!i.type.isTop;i=yi(i.parent)){let r=It(n,i);if(r&&i.lastChild.name=="CloseTag")break;r&&t.indexOf(r)<0&&(e.name=="EndTag"||e.from>=i.firstChild.to)&&t.push(r)}return t}const OO=/^[:\-\.\w\u00b7-\uffff]*$/;function Mh(n,e,t,i,r){let s=/\s*>/.test(n.sliceDoc(r,r+5))?"":">",o=yi(t,t.name=="StartTag"||t.name=="TagName");return{from:i,to:r,options:uO(n.doc,o,e).map(l=>({label:l,type:"type"})).concat(bl(n.doc,t).map((l,a)=>({label:"/"+l,apply:"/"+l+s,type:"type",boost:99-a}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function jh(n,e,t,i){let r=/\s*>/.test(n.sliceDoc(i,i+5))?"":">";return{from:t,to:i,options:bl(n.doc,e).map((s,o)=>({label:s,apply:s+r,type:"type",boost:99-o})),validFor:OO}}function tQ(n,e,t,i){let r=[],s=0;for(let o of uO(n.doc,t,e))r.push({label:"<"+o,type:"type"});for(let o of bl(n.doc,t))r.push({label:"",type:"type",boost:99-s++});return{from:i,to:i,options:r,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function iQ(n,e,t,i,r){let s=yi(t),o=s?e.tags[It(n.doc,s)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],a=o&&o.globalAttrs===!1?l:l.length?l.concat(e.globalAttrNames):e.globalAttrNames;return{from:i,to:r,options:a.map(h=>({label:h,type:"property"})),validFor:OO}}function nQ(n,e,t,i,r){var s;let o=(s=t.parent)===null||s===void 0?void 0:s.getChild("AttributeName"),l=[],a;if(o){let h=n.sliceDoc(o.from,o.to),c=e.globalAttrs[h];if(!c){let f=yi(t),u=f?e.tags[It(n.doc,f)]:null;c=u?.attrs&&u.attrs[h]}if(c){let f=n.sliceDoc(i,r).toLowerCase(),u='"',O='"';/^['"]/.test(f)?(a=f[0]=='"'?/^[^"]*$/:/^[^']*$/,u="",O=n.sliceDoc(r,r+1)==f[0]?"":f[0],f=f.slice(1),i++):a=/^[^\s<>='"]*$/;for(let d of c)l.push({label:d,apply:u+d+O,type:"constant"})}}return{from:i,to:r,options:l,validFor:a}}function dO(n,e){let{state:t,pos:i}=e,r=J(t).resolveInner(i,-1),s=r.resolve(i);for(let o=i,l;s==r&&(l=r.childBefore(o));){let a=l.lastChild;if(!a||!a.type.isError||a.fromdO(i,r)}const oQ=lt.parser.configure({top:"SingleExpression"}),pO=[{tag:"script",attrs:n=>n.type=="text/typescript"||n.lang=="ts",parser:sO.parser},{tag:"script",attrs:n=>n.type=="text/babel"||n.type=="text/jsx",parser:oO.parser},{tag:"script",attrs:n=>n.type=="text/typescript-jsx",parser:lO.parser},{tag:"script",attrs(n){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(n.type)},parser:oQ},{tag:"script",attrs(n){return!n.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(n.type)},parser:lt.parser},{tag:"style",attrs(n){return(!n.lang||n.lang=="css")&&(!n.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(n.type))},parser:Tr.parser}],mO=[{name:"style",parser:Tr.parser.configure({top:"Styles"})}].concat(fO.map(n=>({name:n,parser:lt.parser}))),gO=mi.define({name:"html",parser:X1.configure({props:[Sn.add({Element(n){let e=/^(\s*)(<\/)?/.exec(n.textAfter);return n.node.to<=n.pos+e[0].length?n.continue():n.lineIndent(n.node.from)+(e[2]?0:n.unit)},"OpenTag CloseTag SelfClosingTag"(n){return n.column(n.node.from)+n.unit},Document(n){if(n.pos+/\s*/.exec(n.textAfter)[0].lengthn.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:""}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),tr=gO.configure({wrap:Nu(pO,mO)});function lQ(n={}){let e="",t;n.matchClosingTags===!1&&(e="noMatch"),n.selfClosingTags===!0&&(e=(e?e+" ":"")+"selfClosing"),(n.nestedLanguages&&n.nestedLanguages.length||n.nestedAttributes&&n.nestedAttributes.length)&&(t=Nu((n.nestedLanguages||[]).concat(pO),(n.nestedAttributes||[]).concat(mO)));let i=t?gO.configure({wrap:t,dialect:e}):e?tr.configure({dialect:e}):tr;return new rn(i,[tr.data.of({autocomplete:sQ(n)}),n.autoCloseTags!==!1?hQ:[],Fb().support,Ob().support])}const Lh=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" "));function aQ(n,e,t){for(var i;;){if(((i=e.lastChild)===null||i===void 0?void 0:i.name)!="CloseTag")return!1;let r=e.parent;if(!r||It(n,r)!=t)return!0;e=r}}const hQ=C.inputHandler.of((n,e,t,i,r)=>{if(n.composing||n.state.readOnly||e!=t||i!=">"&&i!="/"||!tr.isActiveAt(n.state,e,-1))return!1;let s=r(),{state:o}=s,l=o.changeByRange(a=>{var h;let c=o.doc.sliceString(a.from-1,a.to)==i,{head:f}=a,u=J(o).resolveInner(f,-1),O;if(c&&i==">"&&u.name=="EndTag"){let d=u.parent;if((O=It(o.doc,d.parent,f))&&!Lh.has(O)&&!aQ(o.doc,d.parent,O)){let p=f+(o.doc.sliceString(f,f+1)===">"?1:0),g=``;return{range:a,changes:{from:f,to:p,insert:g}}}}else if(c&&i=="/"&&u.name=="IncompleteCloseTag"){let d=u.parent;if(u.from==f-2&&((h=d.lastChild)===null||h===void 0?void 0:h.name)!="CloseTag"&&(O=It(o.doc,d,f))&&!Lh.has(O)){let p=f+(o.doc.sliceString(f,f+1)===">"?1:0),g=`${O}>`;return{range:y.cursor(f+g.length,-1),changes:{from:f,to:p,insert:g}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([s,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),SO=Fo({commentTokens:{block:{open:""}}}),bO=new R,QO=$S.configure({props:[ki.add(n=>!n.is("Block")||n.is("Document")||Co(n)!=null||cQ(n)?void 0:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})),bO.add(Co),Sn.add({Document:()=>null}),_t.add({Document:SO})]});function Co(n){let e=/^(?:ATX|Setext)Heading(\d)$/.exec(n.name);return e?+e[1]:void 0}function cQ(n){return n.name=="OrderedList"||n.name=="BulletList"}function fQ(n,e){let t=n;for(;;){let i=t.nextSibling,r;if(!i||(r=Co(i.type))!=null&&r<=e)break;t=i}return t.to}const uQ=mf.of((n,e,t)=>{for(let i=J(n).resolveInner(t,-1);i&&!(i.fromt)return{from:t,to:s}}return null});function Ql(n){return new Ye(SO,n,[],"markdown")}const OQ=Ql(QO),dQ=QO.configure([LS,ES,YS,zS,{props:[ki.add({Table:(n,e)=>({from:e.doc.lineAt(n.from).to,to:n.to})})]}]),Cr=Ql(dQ);function pQ(n,e){return t=>{if(t&&n){let i=null;if(t=/\S*/.exec(t)[0],typeof n=="function"?i=n(t):i=mr.matchLanguageName(n,t,!0),i instanceof mr)return i.support?i.support.language.parser:nn.getSkippingParser(i.load());if(i)return i.parser}return e?e.parser:null}}class Ts{constructor(e,t,i,r,s,o,l){this.node=e,this.from=t,this.to=i,this.spaceBefore=r,this.spaceAfter=s,this.type=o,this.item=l}blank(e,t=!0){let i=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(e!=null){for(;i.length0;r--)i+=" ";return i+(t?this.spaceAfter:"")}}marker(e,t){let i=this.node.name=="OrderedList"?String(+xO(this.item,e)[2]+t):"";return this.spaceBefore+i+this.type+this.spaceAfter}}function yO(n,e){let t=[],i=[];for(let r=n;r;r=r.parent){if(r.name=="FencedCode")return i;(r.name=="ListItem"||r.name=="Blockquote")&&t.push(r)}for(let r=t.length-1;r>=0;r--){let s=t[r],o,l=e.lineAt(s.from),a=s.from-l.from;if(s.name=="Blockquote"&&(o=/^ *>( ?)/.exec(l.text.slice(a))))i.push(new Ts(s,a,a+o[0].length,"",o[1],">",null));else if(s.name=="ListItem"&&s.parent.name=="OrderedList"&&(o=/^( *)\d+([.)])( *)/.exec(l.text.slice(a)))){let h=o[3],c=o[0].length;h.length>=4&&(h=h.slice(0,h.length-4),c-=4),i.push(new Ts(s.parent,a,a+c,o[1],h,o[2],s))}else if(s.name=="ListItem"&&s.parent.name=="BulletList"&&(o=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(a)))){let h=o[4],c=o[0].length;h.length>4&&(h=h.slice(0,h.length-4),c-=4);let f=o[2];o[3]&&(f+=o[3].replace(/[xX]/," ")),i.push(new Ts(s.parent,a,a+c,o[1],h,f,s))}}return i}function xO(n,e){return/^(\s*)(\d+)(?=[.)])/.exec(e.sliceString(n.from,n.from+10))}function Cs(n,e,t,i=0){for(let r=-1,s=n;;){if(s.name=="ListItem"){let l=xO(s,e),a=+l[2];if(r>=0){if(a!=r+1)return;t.push({from:s.from+l[1].length,to:s.from+l[0].length,insert:String(r+2+i)})}r=a}let o=s.nextSibling;if(!o)break;s=o}}function yl(n,e){let t=/^[ \t]*/.exec(n)[0].length;if(!t||e.facet(gn)!=" ")return n;let i=St(n,4,t),r="";for(let s=i;s>0;)s>=4?(r+=" ",s-=4):(r+=" ",s--);return r+n.slice(t)}const mQ=(n={})=>({state:e,dispatch:t})=>{let i=J(e),{doc:r}=e,s=null,o=e.changeByRange(l=>{if(!l.empty||!Cr.isActiveAt(e,l.from,-1)&&!Cr.isActiveAt(e,l.from,1))return s={range:l};let a=l.from,h=r.lineAt(a),c=yO(i.resolveInner(a,-1),r);for(;c.length&&c[c.length-1].from>a-h.from;)c.pop();if(!c.length)return s={range:l};let f=c[c.length-1];if(f.to-f.spaceAfter.length>a-h.from)return s={range:l};let u=a>=f.to-f.spaceAfter.length&&!/\S/.test(h.text.slice(f.to));if(f.item&&u){if(f.item.from]*$/.test(h.text.slice(0,f.to)))return s={range:l};let S=f.node.firstChild,b=f.node.getChild("ListItem","ListItem");if(S.to>=a||b&&b.to0&&!/[^\s>]/.test(r.lineAt(h.from-1).text)||n.nonTightLists===!1){let Q=c.length>1?c[c.length-2]:null,w,k="";Q&&Q.item?(w=h.from+Q.from,k=Q.marker(r,1)):w=h.from+(Q?Q.to:0);let v=[{from:w,to:a,insert:k}];return f.node.name=="OrderedList"&&Cs(f.item,r,v,-2),Q&&Q.node.name=="OrderedList"&&Cs(Q.item,r,v),{range:y.cursor(w+k.length),changes:v}}else{let Q=Eh(c,e,h);return{range:y.cursor(a+Q.length+1),changes:{from:h.from,insert:Q+e.lineBreak}}}}if(f.node.name=="Blockquote"&&u&&h.from){let S=r.lineAt(h.from-1),b=/>\s*$/.exec(S.text);if(b&&b.index==f.from){let Q=e.changes([{from:S.from+b.index,to:S.to},{from:h.from+f.from,to:h.to}]);return{range:l.map(Q),changes:Q}}}let O=[];f.node.name=="OrderedList"&&Cs(f.item,r,O);let d=f.item&&f.item.from]*/.exec(h.text)[0].length>=f.to)for(let S=0,b=c.length-1;S<=b;S++)p+=S==b&&!d?c[S].marker(r,1):c[S].blank(Sh.from&&/\s/.test(h.text.charAt(g-h.from-1));)g--;return p=yl(p,e),SQ(f.node,e.doc)&&(p=Eh(c,e,h)+e.lineBreak+p),O.push({from:g,to:a,insert:e.lineBreak+p}),{range:y.cursor(g+p.length+1),changes:O}});return s?!1:(t(e.update(o,{scrollIntoView:!0,userEvent:"input"})),!0)},gQ=mQ();function Yh(n){return n.name=="QuoteMark"||n.name=="ListMark"}function SQ(n,e){if(n.name!="OrderedList"&&n.name!="BulletList")return!1;let t=n.firstChild,i=n.getChild("ListItem","ListItem");if(!i)return!1;let r=e.lineAt(t.to),s=e.lineAt(i.from),o=/^[\s>]*$/.test(r.text);return r.number+(o?0:1){let t=J(n),i=null,r=n.changeByRange(s=>{let o=s.from,{doc:l}=n;if(s.empty&&Cr.isActiveAt(n,s.from)){let a=l.lineAt(o),h=yO(bQ(t,o),l);if(h.length){let c=h[h.length-1],f=c.to-c.spaceAfter.length+(c.spaceAfter?1:0);if(o-a.from>f&&!/\S/.test(a.text.slice(f,o-a.from)))return{range:y.cursor(a.from+f),changes:{from:a.from+f,to:o}};if(o-a.from==f&&(c.item&&a.from<=c.item.from||/^[\s>]*$/.test(a.text.slice(0,c.to)))){let u=a.from+c.from;if(c.item&&c.node.from{var t;let{main:i}=e.state.selection;if(i.empty)return!1;let r=(t=n.clipboardData)===null||t===void 0?void 0:t.getData("text/plain");if(!r||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(r)||(/^www\./.test(r)&&(r="https://"+r),!Cr.isActiveAt(e.state,i.from,1)))return!1;let s=J(e.state),o=!1;return s.iterate({from:i.from,to:i.to,enter:l=>{(l.from>i.from||$Q.test(l.name))&&(o=!0)},leave:l=>{l.to{if(i.origin!==this.conf){const r=t.delta,s=[];let o=0;for(let l=0;l0&&e.transactions[0].annotation(Zr)===this.conf)return;const t=this.conf.ytext;t.doc.transact(()=>{let i=0;e.changes.iterChanges((r,s,o,l,a)=>{const h=a.sliceString(0,a.length,` -`);r!==s&&t.delete(r+i,s-r),h.length>0&&t.insert(r+i,h),i+=h.length-(s-r)})},this.conf)}destroy(){this._ytext.unobserve(this._observer)}}const CQ=Se.fromClass(TQ),ZQ=C.baseTheme({".cm-ySelection":{},".cm-yLineSelection":{padding:0,margin:"0px 2px 0px 4px"},".cm-ySelectionCaret":{position:"relative",borderLeft:"1px solid black",borderRight:"1px solid black",marginLeft:"-1px",marginRight:"-1px",boxSizing:"border-box",display:"inline"},".cm-ySelectionCaretDot":{borderRadius:"50%",position:"absolute",width:".4em",height:".4em",top:"-.2em",left:"-.2em",backgroundColor:"inherit",transition:"transform .3s ease-in-out",boxSizing:"border-box"},".cm-ySelectionCaret:hover > .cm-ySelectionCaretDot":{transformOrigin:"bottom center",transform:"scale(0)"},".cm-ySelectionInfo":{position:"absolute",top:"-1.05em",left:"-1px",fontSize:".75em",fontFamily:"serif",fontStyle:"normal",fontWeight:"normal",lineHeight:"normal",userSelect:"none",color:"white",paddingLeft:"2px",paddingRight:"2px",zIndex:101,transition:"opacity .3s ease-in-out",backgroundColor:"inherit",opacity:0,transitionDelay:"0s",whiteSpace:"nowrap"},".cm-ySelectionCaret:hover > .cm-ySelectionInfo":{opacity:1,transitionDelay:"0s"}}),XQ=Ie.define();class AQ extends at{constructor(e,t){super(),this.color=e,this.name=t}toDOM(){return Nr("span",[$n("class","cm-ySelectionCaret"),$n("style",`background-color: ${this.color}; border-color: ${this.color}`)],[wn("⁠"),Nr("div",[$n("class","cm-ySelectionCaretDot")]),wn("⁠"),Nr("div",[$n("class","cm-ySelectionInfo")],[wn(this.name)]),wn("⁠")])}eq(e){return e.color===this.color}compare(e){return e.color===this.color}updateDOM(){return!1}get estimatedHeight(){return-1}ignoreEvent(){return!0}}class RQ{constructor(e){this.conf=e.state.facet(qr),this._listener=({added:t,updated:i,removed:r},s,o)=>{t.concat(i).concat(r).findIndex(a=>a!==this.conf.awareness.doc.clientID)>=0&&e.dispatch({annotations:[XQ.of([])]})},this._awareness=this.conf.awareness,this._awareness.on("change",this._listener),this.decorations=E.of([])}destroy(){this._awareness.off("change",this._listener)}update(e){const t=this.conf.ytext,i=t.doc,r=this.conf.awareness,s=[],o=this.conf.awareness.getLocalState();if(o!=null){const l=e.view.hasFocus&&e.view.dom.ownerDocument.hasFocus(),a=l?e.state.selection.main:null,h=o.cursor==null?null:Ni(o.cursor.anchor),c=o.cursor==null?null:Ni(o.cursor.head);if(a!=null){const f=Xs(t,a.anchor),u=Xs(t,a.head);(o.cursor==null||!$l(h,f)||!$l(c,u))&&r.setLocalStateField("cursor",{anchor:f,head:u})}else o.cursor!=null&&l&&r.setLocalStateField("cursor",null)}r.getStates().forEach((l,a)=>{if(a===r.doc.clientID)return;const h=l.cursor;if(h==null||h.anchor==null||h.head==null)return;const c=As(h.anchor,i),f=As(h.head,i);if(c==null||f==null||c.type!==t||f.type!==t)return;const{color:u="#30bced",name:O="Anonymous"}=l.user||{},d=l.user&&l.user.colorLight||u+"33",p=MO(c.index,f.index),g=jO(c.index,f.index),S=e.view.state.doc.lineAt(p),b=e.view.state.doc.lineAt(g);if(S.number===b.number)s.push({from:p,to:g,value:M.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})});else{s.push({from:p,to:S.from+S.length,value:M.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})}),s.push({from:b.from,to:g,value:M.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})});for(let Q=S.number+1;Q0?-1:1,block:!1,widget:new AQ(u,O)})})}),this.decorations=M.set(s,!0)}}const MQ=Se.fromClass(RQ,{decorations:n=>n.decorations});class jQ{constructor(e){this.undoManager=e}addTrackedOrigin(e){this.undoManager.addTrackedOrigin(e)}removeTrackedOrigin(e){this.undoManager.removeTrackedOrigin(e)}undo(){return this.undoManager.undo()!=null}redo(){return this.undoManager.redo()!=null}}const Dr=Z.define({combine(n){return n[n.length-1]}});class LQ{constructor(e){this.view=e,this.conf=e.state.facet(Dr),this._undoManager=this.conf.undoManager,this.syncConf=e.state.facet(qr),this._beforeChangeSelection=null,this._onStackItemAdded=({stackItem:t,changedParentTypes:i})=>{i.has(this.syncConf.ytext)&&this._beforeChangeSelection&&!t.meta.has(this)&&t.meta.set(this,this._beforeChangeSelection)},this._onStackItemPopped=({stackItem:t})=>{const i=t.meta.get(this);if(i){const r=this.syncConf.fromYRange(i);e.dispatch(e.state.update({selection:r,effects:[C.scrollIntoView(r)]})),this._storeSelection()}},this._storeSelection=()=>{this._beforeChangeSelection=this.syncConf.toYRange(this.view.state.selection.main)},this._undoManager.on("stack-item-added",this._onStackItemAdded),this._undoManager.on("stack-item-popped",this._onStackItemPopped),this._undoManager.addTrackedOrigin(this.syncConf)}update(e){e.selectionSet&&(e.transactions.length===0||e.transactions[0].annotation(Zr)!==this.syncConf)&&this._storeSelection()}destroy(){this._undoManager.off("stack-item-added",this._onStackItemAdded),this._undoManager.off("stack-item-popped",this._onStackItemPopped),this._undoManager.removeTrackedOrigin(this.syncConf)}}const YQ=Se.fromClass(LQ),EQ=({state:n,dispatch:e})=>n.facet(Dr).undo()||!0,zQ=({state:n,dispatch:e})=>n.facet(Dr).redo()||!0,_Q=(n,e,{undoManager:t=new LO(n)}={})=>{const i=new vQ(n,e),r=[qr.of(i),CQ];return e&&r.push(ZQ,MQ),t!==!1&&r.push(Dr.of(new jQ(t)),YQ,C.domEventHandlers({beforeinput(s,o){return s.inputType==="historyUndo"?EQ(o):s.inputType==="historyRedo"?zQ(o):!1}})),r},wO=_e.define({create:n=>ir(n.doc.toString()),update:(n,e)=>e.docChanged?ir(e.newDoc.toString()):n});function Jt(n){return n.field(wO,!1)??ir(n.doc.toString())}const WQ=5e3;function VQ(n){const e=n.trim().split(/[\s@._-]+/).filter(Boolean);return e.length?(e[0][0]+(e[1]?.[0]??"")).toUpperCase():"?"}function BQ(n,e=20){const t=document.createElement("span"),i=Wh(n);return t.className="pavatar",t.textContent=VQ(n),t.style.setProperty("--ph",String(i)),t.style.width=t.style.height=e+"px",t}class qQ extends at{constructor(e,t,i){super(),this.name=e,this.folded=t,this.foldable=i}name;folded;foldable;eq(e){return e.name===this.name&&e.folded===this.folded&&e.foldable===this.foldable}toDOM(){const e=document.createElement("span");e.className="ms-head";const t=document.createElement("button");return t.type="button",t.className="ms-toggle",t.dataset.section=this.name,t.setAttribute("aria-label",(this.folded?"Expand ":"Collapse ")+this.name),t.setAttribute("aria-expanded",String(!this.folded)),t.disabled=!this.foldable,e.append(t,BQ(this.name)),e}ignoreEvent(){return!1}}class DQ extends at{constructor(e){super(),this.s=e}s;eq(e){return e.s.kind===this.s.kind&&e.s.who===this.s.who&&e.s.at===this.s.at}toDOM(){const e=document.createElement("span");e.className="ms-status ms-"+this.s.kind,e.dataset.status=this.s.kind;const t=this.s.at?new Date(this.s.at).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return e.textContent=this.s.kind==="typing"?`${this.s.who||"Someone"} is typing…`:this.s.kind==="updated"?`Updated ${t}`:this.s.kind==="empty"?"Not started":this.s.kind==="you"?"You":"",this.s.kind==="typing"&&this.s.who&&e.style.setProperty("--ph",String(Wh(this.s.who))),e}}function IQ(n){return n?n.remoteCursors():[]}function $O(n,e){let t=!1;return Um(n).between(e.headingEnd,e.headingEnd+1,i=>{i===e.headingEnd&&(t=!0)}),t}function Zo(n){return n.to>n.headingEnd+1}function NQ(n,e){const t=Jt(n.state).find(r=>r.name===e);if(!t||!Zo(t))return;const i={from:t.headingEnd,to:t.to};n.dispatch({effects:$O(n.state,t)?Qn.of(i):bn.of(i)})}function GQ(n){const e=Se.fromClass(class{constructor(i){this.view=i,this.decorations=this.build(),setTimeout(()=>{const s=Jt(i.state).filter(o=>Zo(o)&&!Ir(o.name,n.me)).map(o=>bn.of({from:o.headingEnd,to:o.to}));s.length&&i.dispatch({effects:s})}),this.tick=setInterval(()=>this.refresh(),2e3);const r=()=>setTimeout(()=>this.refresh());n.collab?.awareness.on("change",r),this.offAwareness=()=>n.collab?.awareness.off("change",r)}view;decorations=M.none;last=new Map;tick;offAwareness;refresh(){try{this.view.dispatch({})}catch{}}update(i){if(i.docChanged){const r=Jt(i.state);for(const s of i.transactions){if(!s.docChanged)continue;const o=!!s.annotation(Zr);s.changes.iterChangedRanges((l,a,h)=>{const c=r.find(f=>h>=f.from&&h<=f.to);c&&this.last.set(c.name,{at:Date.now(),remote:o})})}}this.decorations=this.build()}status(i,r){const s=r.find(l=>l.pos>=i.from&&l.pos<=i.to),o=this.last.get(i.name);return s&&o&&o.remote&&Date.now()-o.ati.decorations,eventHandlers:{mousedown(i,r){const s=i.target.closest?.(".ms-toggle");return s?.dataset.section?(i.preventDefault(),NQ(r,s.dataset.section),!0):!1}}}),t=W.transactionFilter.of(i=>{if(!i.docChanged||!i.annotation(ne.userEvent)||!n.offline())return i;const r=[];return i.changes.iterChangedRanges((s,o)=>r.push([s,o])),PO(Jt(i.startState),n.me,r)?i:(n.onBlocked?.(),[])});return[wO,wf({preparePlaceholder:(i,r)=>{const s=Jt(i).find(o=>o.headingEnd===r.from);return s?vO(s):""},placeholderDOM:(i,r,s)=>{const o=document.createElement("span");return o.className="ms-summary",o.textContent=s||"…",o.title="Expand",o.onclick=r,o}}),e,t]}const zh=n=>n.trim().split(/\s+/)[0];function Mt(n,e,t,i,r=i.length){n.dispatch({changes:{from:e,to:t,insert:i},selection:{anchor:e+r},userEvent:"input.complete"})}function UQ(n){return uS({override:[r=>{const s=r.matchBefore(/(?:^|\s)\/\w*$/);if(!s)return null;const o=r.state.doc.lineAt(r.pos),l=r.state.sliceDoc(o.from,s.from+(s.text.startsWith("/")?0:1));if(!/^\s*(?:[-*+]\s+(?:\[[ xX]\]\s+)?)?$/.test(l))return null;const a=s.from+(s.text.startsWith("/")?0:1),h=/[-*+]\s+$/.test(l),c=/\]\s+$/.test(l),f=[{label:"/action",displayLabel:"Action item",detail:"- [ ] with an owner",section:"Meeting",apply:(u,O,d,p)=>{const g=c?"":h?"[ ] ":"- [ ] ",S=` @${zh(n.me)}`;Mt(u,d,p,g+S,g.length)}},{label:"/mention",displayLabel:"Mention someone",detail:"@name",section:"Meeting",apply:(u,O,d,p)=>{Mt(u,d,p,"@"),qi(u)}},{label:"/link",displayLabel:"Link a file",detail:"[[ file from this project",section:"Meeting",apply:(u,O,d,p)=>{Mt(u,d,p,"[[]]",2),qi(u)}}];if(n.carryOver){const u=n.carryOver;f.push({label:"/carry",displayLabel:"Carry over from last meeting",detail:"open - [ ] items",section:"Meeting",apply:(O,d,p,g)=>{Mt(O,p,g,""),u().then(S=>{if(!S)return n.onNotice?.("No earlier meeting note in this folder.");if(!S.items.length)return n.onNotice?.(`No open items in ${S.from.split("/").pop()}.`);const b=O.state.selection.main.head,Q=O.state.doc.lineAt(b),w=/^\s*(?:[-*+]\s*(?:\[[ xX]\]\s*)?)?$/.test(Q.text),k=S.items.join(` +}`,{label:"class",detail:"definition",type:"keyword"}),ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Nb=tO.concat([ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Ah=new hf,iO=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function ji(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const Gb=["FunctionDeclaration"],Ub={FunctionDeclaration:ji("function"),ClassDeclaration:ji("class"),ClassExpression:()=>!0,EnumDeclaration:ji("constant"),TypeAliasDeclaration:ji("type"),NamespaceDeclaration:ji("namespace"),VariableDefinition(n,e){n.matchContext(Gb)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function nO(n,e){let t=Ah.get(e);if(t)return t;let i=[],r=!0;function s(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(D.IncludeAnonymous).iterate(o=>{if(r)r=!1;else if(o.name){let l=Ub[o.name];if(l&&l(o,s)||iO.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of nO(n,o.node))i.push(l);return!1}}),Ah.set(e,i),i}const Rh=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,rO=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Fb(n){let e=J(n.state).resolveInner(n.pos,-1);if(rO.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Rh.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let r=e;r;r=r.parent)iO.has(r.name)&&(i=i.concat(nO(n.state.doc,r)));return{options:i,from:t?e.from:n.pos,validFor:Rh}}const ht=mi.define({name:"javascript",parser:Ib.configure({props:[bn.add({IfStatement:Jn({except:/^\s*({|else\b)/}),TryStatement:Jn({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:Gm,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:Nm({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Jn({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),ki.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Sf,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),sO={test:n=>/^JSX/.test(n.name),facet:Ho({commentTokens:{block:{open:"{/*",close:"*/}"}}})},oO=ht.configure({dialect:"ts"},"typescript"),lO=ht.configure({dialect:"jsx",props:[Ko.add(n=>n.isTop?[sO]:void 0)]}),aO=ht.configure({dialect:"jsx ts",props:[Ko.add(n=>n.isTop?[sO]:void 0)]},"typescript");let hO=n=>({label:n,type:"keyword"});const cO="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(hO),Hb=cO.concat(["declare","implements","private","protected","public"].map(hO));function Kb(n={}){let e=n.jsx?n.typescript?aO:lO:n.typescript?oO:ht,t=n.typescript?Nb.concat(Hb):tO.concat(cO);return new sn(e,[ht.data.of({autocomplete:A0(rO,au(t))}),ht.data.of({autocomplete:Fb}),n.jsx?tQ:[]])}function Jb(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function Mh(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const eQ=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),tQ=C.inputHandler.of((n,e,t,i,r)=>{if((eQ?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!ht.isActiveAt(n.state,e,-1))return!1;let s=r(),{state:o}=s,l=o.changeByRange(a=>{var h;let{head:c}=a,f=J(o).resolveInner(c-1,-1),u;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(c-1,c)!=i||f.name=="JSXAttributeValue"&&f.to>c)){if(i==">"&&f.name=="JSXFragmentTag")return{range:a,changes:{from:c,insert:""}};if(i=="/"&&f.name=="JSXStartCloseTag"){let O=f.parent,d=O.parent;if(d&&O.from==c-2&&((u=Mh(o.doc,d.firstChild,c))||((h=d.firstChild)===null||h===void 0?void 0:h.name)=="JSXFragmentTag")){let p=`${u}>`;return{range:y.cursor(c+p.length,-1),changes:{from:c,insert:p}}}}else if(i==">"){let O=Jb(f);if(O&&O.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(c,c+2))&&(u=Mh(o.doc,O,c)))return{range:a,changes:{from:c,insert:``}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([s,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Li=["_blank","_self","_top","_parent"],Ps=["ascii","utf-8","utf-16","latin1","latin1"],vs=["get","post","put","delete"],Ts=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],ve=["true","false"],X={},iQ={a:{attrs:{href:null,ping:null,type:null,media:null,target:Li,hreflang:null}},abbr:X,address:X,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:X,aside:X,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:X,base:{attrs:{href:null,target:Li}},bdi:X,bdo:X,blockquote:{attrs:{cite:null}},body:X,br:X,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Ts,formmethod:vs,formnovalidate:["novalidate"],formtarget:Li,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:X,center:X,cite:X,code:X,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:X,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:X,div:X,dl:X,dt:X,em:X,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:X,figure:X,footer:X,form:{attrs:{action:null,name:null,"accept-charset":Ps,autocomplete:["on","off"],enctype:Ts,method:vs,novalidate:["novalidate"],target:Li}},h1:X,h2:X,h3:X,h4:X,h5:X,h6:X,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:X,hgroup:X,hr:X,html:{attrs:{manifest:null}},i:X,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Ts,formmethod:vs,formnovalidate:["novalidate"],formtarget:Li,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:X,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:X,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:X,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Ps,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:X,noscript:X,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:X,param:{attrs:{name:null,value:null}},pre:X,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:X,rt:X,ruby:X,samp:X,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Ps}},section:X,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:X,source:{attrs:{src:null,type:null,media:null}},span:X,strong:X,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:X,summary:X,sup:X,table:X,tbody:X,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:X,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:X,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:X,time:{attrs:{datetime:null}},title:X,tr:X,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:X,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:X},fO={accesskey:null,class:null,contenteditable:ve,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:ve,autocorrect:ve,autocapitalize:ve,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":ve,"aria-autocomplete":["inline","list","both","none"],"aria-busy":ve,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":ve,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":ve,"aria-hidden":ve,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":ve,"aria-multiselectable":ve,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":ve,"aria-relevant":null,"aria-required":ve,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},uO="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(n=>"on"+n);for(let n of uO)fO[n]=null;class fn{constructor(e,t){this.tags={...iQ,...e},this.globalAttrs={...fO,...t},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}fn.default=new fn;function It(n,e,t=n.length){if(!e)return"";let i=e.firstChild,r=i&&i.getChild("TagName");return r?n.sliceString(r.from,Math.min(r.to,t)):""}function yi(n,e=!1){for(;n;n=n.parent)if(n.name=="Element")if(e)e=!1;else return n;return null}function OO(n,e,t){let i=t.tags[It(n,yi(e))];return i?.children||t.allTags}function Ql(n,e){let t=[];for(let i=yi(e);i&&!i.type.isTop;i=yi(i.parent)){let r=It(n,i);if(r&&i.lastChild.name=="CloseTag")break;r&&t.indexOf(r)<0&&(e.name=="EndTag"||e.from>=i.firstChild.to)&&t.push(r)}return t}const dO=/^[:\-\.\w\u00b7-\uffff]*$/;function jh(n,e,t,i,r){let s=/\s*>/.test(n.sliceDoc(r,r+5))?"":">",o=yi(t,t.name=="StartTag"||t.name=="TagName");return{from:i,to:r,options:OO(n.doc,o,e).map(l=>({label:l,type:"type"})).concat(Ql(n.doc,t).map((l,a)=>({label:"/"+l,apply:"/"+l+s,type:"type",boost:99-a}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function Lh(n,e,t,i){let r=/\s*>/.test(n.sliceDoc(i,i+5))?"":">";return{from:t,to:i,options:Ql(n.doc,e).map((s,o)=>({label:s,apply:s+r,type:"type",boost:99-o})),validFor:dO}}function nQ(n,e,t,i){let r=[],s=0;for(let o of OO(n.doc,t,e))r.push({label:"<"+o,type:"type"});for(let o of Ql(n.doc,t))r.push({label:"",type:"type",boost:99-s++});return{from:i,to:i,options:r,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function rQ(n,e,t,i,r){let s=yi(t),o=s?e.tags[It(n.doc,s)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],a=o&&o.globalAttrs===!1?l:l.length?l.concat(e.globalAttrNames):e.globalAttrNames;return{from:i,to:r,options:a.map(h=>({label:h,type:"property"})),validFor:dO}}function sQ(n,e,t,i,r){var s;let o=(s=t.parent)===null||s===void 0?void 0:s.getChild("AttributeName"),l=[],a;if(o){let h=n.sliceDoc(o.from,o.to),c=e.globalAttrs[h];if(!c){let f=yi(t),u=f?e.tags[It(n.doc,f)]:null;c=u?.attrs&&u.attrs[h]}if(c){let f=n.sliceDoc(i,r).toLowerCase(),u='"',O='"';/^['"]/.test(f)?(a=f[0]=='"'?/^[^"]*$/:/^[^']*$/,u="",O=n.sliceDoc(r,r+1)==f[0]?"":f[0],f=f.slice(1),i++):a=/^[^\s<>='"]*$/;for(let d of c)l.push({label:d,apply:u+d+O,type:"constant"})}}return{from:i,to:r,options:l,validFor:a}}function pO(n,e){let{state:t,pos:i}=e,r=J(t).resolveInner(i,-1),s=r.resolve(i);for(let o=i,l;s==r&&(l=r.childBefore(o));){let a=l.lastChild;if(!a||!a.type.isError||a.frompO(i,r)}const aQ=ht.parser.configure({top:"SingleExpression"}),mO=[{tag:"script",attrs:n=>n.type=="text/typescript"||n.lang=="ts",parser:oO.parser},{tag:"script",attrs:n=>n.type=="text/babel"||n.type=="text/jsx",parser:lO.parser},{tag:"script",attrs:n=>n.type=="text/typescript-jsx",parser:aO.parser},{tag:"script",attrs(n){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(n.type)},parser:aQ},{tag:"script",attrs(n){return!n.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(n.type)},parser:ht.parser},{tag:"style",attrs(n){return(!n.lang||n.lang=="css")&&(!n.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(n.type))},parser:Cr.parser}],gO=[{name:"style",parser:Cr.parser.configure({top:"Styles"})}].concat(uO.map(n=>({name:n,parser:ht.parser}))),SO=mi.define({name:"html",parser:R1.configure({props:[bn.add({Element(n){let e=/^(\s*)(<\/)?/.exec(n.textAfter);return n.node.to<=n.pos+e[0].length?n.continue():n.lineIndent(n.node.from)+(e[2]?0:n.unit)},"OpenTag CloseTag SelfClosingTag"(n){return n.column(n.node.from)+n.unit},Document(n){if(n.pos+/\s*/.exec(n.textAfter)[0].lengthn.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:""}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),ir=SO.configure({wrap:Gu(mO,gO)});function hQ(n={}){let e="",t;n.matchClosingTags===!1&&(e="noMatch"),n.selfClosingTags===!0&&(e=(e?e+" ":"")+"selfClosing"),(n.nestedLanguages&&n.nestedLanguages.length||n.nestedAttributes&&n.nestedAttributes.length)&&(t=Gu((n.nestedLanguages||[]).concat(mO),(n.nestedAttributes||[]).concat(gO)));let i=t?SO.configure({wrap:t,dialect:e}):e?ir.configure({dialect:e}):ir;return new sn(i,[ir.data.of({autocomplete:lQ(n)}),n.autoCloseTags!==!1?fQ:[],Kb().support,pb().support])}const Yh=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" "));function cQ(n,e,t){for(var i;;){if(((i=e.lastChild)===null||i===void 0?void 0:i.name)!="CloseTag")return!1;let r=e.parent;if(!r||It(n,r)!=t)return!0;e=r}}const fQ=C.inputHandler.of((n,e,t,i,r)=>{if(n.composing||n.state.readOnly||e!=t||i!=">"&&i!="/"||!ir.isActiveAt(n.state,e,-1))return!1;let s=r(),{state:o}=s,l=o.changeByRange(a=>{var h;let c=o.doc.sliceString(a.from-1,a.to)==i,{head:f}=a,u=J(o).resolveInner(f,-1),O;if(c&&i==">"&&u.name=="EndTag"){let d=u.parent;if((O=It(o.doc,d.parent,f))&&!Yh.has(O)&&!cQ(o.doc,d.parent,O)){let p=f+(o.doc.sliceString(f,f+1)===">"?1:0),g=``;return{range:a,changes:{from:f,to:p,insert:g}}}}else if(c&&i=="/"&&u.name=="IncompleteCloseTag"){let d=u.parent;if(u.from==f-2&&((h=d.lastChild)===null||h===void 0?void 0:h.name)!="CloseTag"&&(O=It(o.doc,d,f))&&!Yh.has(O)){let p=f+(o.doc.sliceString(f,f+1)===">"?1:0),g=`${O}>`;return{range:y.cursor(f+g.length,-1),changes:{from:f,to:p,insert:g}}}}return{range:a}});return l.changes.empty?!1:(n.dispatch([s,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),bO=Ho({commentTokens:{block:{open:""}}}),QO=new R,yO=vS.configure({props:[ki.add(n=>!n.is("Block")||n.is("Document")||Zo(n)!=null||uQ(n)?void 0:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})),QO.add(Zo),bn.add({Document:()=>null}),_t.add({Document:bO})]});function Zo(n){let e=/^(?:ATX|Setext)Heading(\d)$/.exec(n.name);return e?+e[1]:void 0}function uQ(n){return n.name=="OrderedList"||n.name=="BulletList"}function OQ(n,e){let t=n;for(;;){let i=t.nextSibling,r;if(!i||(r=Zo(i.type))!=null&&r<=e)break;t=i}return t.to}const dQ=gf.of((n,e,t)=>{for(let i=J(n).resolveInner(t,-1);i&&!(i.fromt)return{from:t,to:s}}return null});function yl(n){return new Ee(bO,n,[],"markdown")}const pQ=yl(yO),mQ=yO.configure([ES,_S,zS,WS,{props:[ki.add({Table:(n,e)=>({from:e.doc.lineAt(n.from).to,to:n.to})})]}]),Zr=yl(mQ);function gQ(n,e){return t=>{if(t&&n){let i=null;if(t=/\S*/.exec(t)[0],typeof n=="function"?i=n(t):i=gr.matchLanguageName(n,t,!0),i instanceof gr)return i.support?i.support.language.parser:rn.getSkippingParser(i.load());if(i)return i.parser}return e?e.parser:null}}class Cs{constructor(e,t,i,r,s,o,l){this.node=e,this.from=t,this.to=i,this.spaceBefore=r,this.spaceAfter=s,this.type=o,this.item=l}blank(e,t=!0){let i=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(e!=null){for(;i.length0;r--)i+=" ";return i+(t?this.spaceAfter:"")}}marker(e,t){let i=this.node.name=="OrderedList"?String(+kO(this.item,e)[2]+t):"";return this.spaceBefore+i+this.type+this.spaceAfter}}function xO(n,e){let t=[],i=[];for(let r=n;r;r=r.parent){if(r.name=="FencedCode")return i;(r.name=="ListItem"||r.name=="Blockquote")&&t.push(r)}for(let r=t.length-1;r>=0;r--){let s=t[r],o,l=e.lineAt(s.from),a=s.from-l.from;if(s.name=="Blockquote"&&(o=/^ *>( ?)/.exec(l.text.slice(a))))i.push(new Cs(s,a,a+o[0].length,"",o[1],">",null));else if(s.name=="ListItem"&&s.parent.name=="OrderedList"&&(o=/^( *)\d+([.)])( *)/.exec(l.text.slice(a)))){let h=o[3],c=o[0].length;h.length>=4&&(h=h.slice(0,h.length-4),c-=4),i.push(new Cs(s.parent,a,a+c,o[1],h,o[2],s))}else if(s.name=="ListItem"&&s.parent.name=="BulletList"&&(o=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(a)))){let h=o[4],c=o[0].length;h.length>4&&(h=h.slice(0,h.length-4),c-=4);let f=o[2];o[3]&&(f+=o[3].replace(/[xX]/," ")),i.push(new Cs(s.parent,a,a+c,o[1],h,f,s))}}return i}function kO(n,e){return/^(\s*)(\d+)(?=[.)])/.exec(e.sliceString(n.from,n.from+10))}function Zs(n,e,t,i=0){for(let r=-1,s=n;;){if(s.name=="ListItem"){let l=kO(s,e),a=+l[2];if(r>=0){if(a!=r+1)return;t.push({from:s.from+l[1].length,to:s.from+l[0].length,insert:String(r+2+i)})}r=a}let o=s.nextSibling;if(!o)break;s=o}}function xl(n,e){let t=/^[ \t]*/.exec(n)[0].length;if(!t||e.facet(Sn)!=" ")return n;let i=bt(n,4,t),r="";for(let s=i;s>0;)s>=4?(r+=" ",s-=4):(r+=" ",s--);return r+n.slice(t)}const SQ=(n={})=>({state:e,dispatch:t})=>{let i=J(e),{doc:r}=e,s=null,o=e.changeByRange(l=>{if(!l.empty||!Zr.isActiveAt(e,l.from,-1)&&!Zr.isActiveAt(e,l.from,1))return s={range:l};let a=l.from,h=r.lineAt(a),c=xO(i.resolveInner(a,-1),r);for(;c.length&&c[c.length-1].from>a-h.from;)c.pop();if(!c.length)return s={range:l};let f=c[c.length-1];if(f.to-f.spaceAfter.length>a-h.from)return s={range:l};let u=a>=f.to-f.spaceAfter.length&&!/\S/.test(h.text.slice(f.to));if(f.item&&u){if(f.item.from]*$/.test(h.text.slice(0,f.to)))return s={range:l};let S=f.node.firstChild,b=f.node.getChild("ListItem","ListItem");if(S.to>=a||b&&b.to0&&!/[^\s>]/.test(r.lineAt(h.from-1).text)||n.nonTightLists===!1){let Q=c.length>1?c[c.length-2]:null,w,k="";Q&&Q.item?(w=h.from+Q.from,k=Q.marker(r,1)):w=h.from+(Q?Q.to:0);let v=[{from:w,to:a,insert:k}];return f.node.name=="OrderedList"&&Zs(f.item,r,v,-2),Q&&Q.node.name=="OrderedList"&&Zs(Q.item,r,v),{range:y.cursor(w+k.length),changes:v}}else{let Q=zh(c,e,h);return{range:y.cursor(a+Q.length+1),changes:{from:h.from,insert:Q+e.lineBreak}}}}if(f.node.name=="Blockquote"&&u&&h.from){let S=r.lineAt(h.from-1),b=/>\s*$/.exec(S.text);if(b&&b.index==f.from){let Q=e.changes([{from:S.from+b.index,to:S.to},{from:h.from+f.from,to:h.to}]);return{range:l.map(Q),changes:Q}}}let O=[];f.node.name=="OrderedList"&&Zs(f.item,r,O);let d=f.item&&f.item.from]*/.exec(h.text)[0].length>=f.to)for(let S=0,b=c.length-1;S<=b;S++)p+=S==b&&!d?c[S].marker(r,1):c[S].blank(Sh.from&&/\s/.test(h.text.charAt(g-h.from-1));)g--;return p=xl(p,e),QQ(f.node,e.doc)&&(p=zh(c,e,h)+e.lineBreak+p),O.push({from:g,to:a,insert:e.lineBreak+p}),{range:y.cursor(g+p.length+1),changes:O}});return s?!1:(t(e.update(o,{scrollIntoView:!0,userEvent:"input"})),!0)},bQ=SQ();function Eh(n){return n.name=="QuoteMark"||n.name=="ListMark"}function QQ(n,e){if(n.name!="OrderedList"&&n.name!="BulletList")return!1;let t=n.firstChild,i=n.getChild("ListItem","ListItem");if(!i)return!1;let r=e.lineAt(t.to),s=e.lineAt(i.from),o=/^[\s>]*$/.test(r.text);return r.number+(o?0:1){let t=J(n),i=null,r=n.changeByRange(s=>{let o=s.from,{doc:l}=n;if(s.empty&&Zr.isActiveAt(n,s.from)){let a=l.lineAt(o),h=xO(yQ(t,o),l);if(h.length){let c=h[h.length-1],f=c.to-c.spaceAfter.length+(c.spaceAfter?1:0);if(o-a.from>f&&!/\S/.test(a.text.slice(f,o-a.from)))return{range:y.cursor(a.from+f),changes:{from:a.from+f,to:o}};if(o-a.from==f&&(c.item&&a.from<=c.item.from||/^[\s>]*$/.test(a.text.slice(0,c.to)))){let u=a.from+c.from;if(c.item&&c.node.from{var t;let{main:i}=e.state.selection;if(i.empty)return!1;let r=(t=n.clipboardData)===null||t===void 0?void 0:t.getData("text/plain");if(!r||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(r)||(/^www\./.test(r)&&(r="https://"+r),!Zr.isActiveAt(e.state,i.from,1)))return!1;let s=J(e.state),o=!1;return s.iterate({from:i.from,to:i.to,enter:l=>{(l.from>i.from||vQ.test(l.name))&&(o=!0)},leave:l=>{l.to{if(i.origin!==this.conf){const r=t.delta,s=[];let o=0;for(let l=0;l0&&e.transactions[0].annotation(Xr)===this.conf)return;const t=this.conf.ytext;t.doc.transact(()=>{let i=0;e.changes.iterChanges((r,s,o,l,a)=>{const h=a.sliceString(0,a.length,` +`);r!==s&&t.delete(r+i,s-r),h.length>0&&t.insert(r+i,h),i+=h.length-(s-r)})},this.conf)}destroy(){this._ytext.unobserve(this._observer)}}const XQ=Se.fromClass(ZQ),AQ=C.baseTheme({".cm-ySelection":{},".cm-yLineSelection":{padding:0,margin:"0px 2px 0px 4px"},".cm-ySelectionCaret":{position:"relative",borderLeft:"1px solid black",borderRight:"1px solid black",marginLeft:"-1px",marginRight:"-1px",boxSizing:"border-box",display:"inline"},".cm-ySelectionCaretDot":{borderRadius:"50%",position:"absolute",width:".4em",height:".4em",top:"-.2em",left:"-.2em",backgroundColor:"inherit",transition:"transform .3s ease-in-out",boxSizing:"border-box"},".cm-ySelectionCaret:hover > .cm-ySelectionCaretDot":{transformOrigin:"bottom center",transform:"scale(0)"},".cm-ySelectionInfo":{position:"absolute",top:"-1.05em",left:"-1px",fontSize:".75em",fontFamily:"serif",fontStyle:"normal",fontWeight:"normal",lineHeight:"normal",userSelect:"none",color:"white",paddingLeft:"2px",paddingRight:"2px",zIndex:101,transition:"opacity .3s ease-in-out",backgroundColor:"inherit",opacity:0,transitionDelay:"0s",whiteSpace:"nowrap"},".cm-ySelectionCaret:hover > .cm-ySelectionInfo":{opacity:1,transitionDelay:"0s"}}),RQ=Ge.define();class MQ extends ct{constructor(e,t){super(),this.color=e,this.name=t}toDOM(){return Gr("span",[Pn("class","cm-ySelectionCaret"),Pn("style",`background-color: ${this.color}; border-color: ${this.color}`)],[$n("⁠"),Gr("div",[Pn("class","cm-ySelectionCaretDot")]),$n("⁠"),Gr("div",[Pn("class","cm-ySelectionInfo")],[$n(this.name)]),$n("⁠")])}eq(e){return e.color===this.color}compare(e){return e.color===this.color}updateDOM(){return!1}get estimatedHeight(){return-1}ignoreEvent(){return!0}}class jQ{constructor(e){this.conf=e.state.facet(Dr),this._listener=({added:t,updated:i,removed:r},s,o)=>{t.concat(i).concat(r).findIndex(a=>a!==this.conf.awareness.doc.clientID)>=0&&e.dispatch({annotations:[RQ.of([])]})},this._awareness=this.conf.awareness,this._awareness.on("change",this._listener),this.decorations=E.of([])}destroy(){this._awareness.off("change",this._listener)}update(e){const t=this.conf.ytext,i=t.doc,r=this.conf.awareness,s=[],o=this.conf.awareness.getLocalState();if(o!=null){const l=e.view.hasFocus&&e.view.dom.ownerDocument.hasFocus(),a=l?e.state.selection.main:null,h=o.cursor==null?null:Gi(o.cursor.anchor),c=o.cursor==null?null:Gi(o.cursor.head);if(a!=null){const f=As(t,a.anchor),u=As(t,a.head);(o.cursor==null||!Pl(h,f)||!Pl(c,u))&&r.setLocalStateField("cursor",{anchor:f,head:u})}else o.cursor!=null&&l&&r.setLocalStateField("cursor",null)}r.getStates().forEach((l,a)=>{if(a===r.doc.clientID)return;const h=l.cursor;if(h==null||h.anchor==null||h.head==null)return;const c=Rs(h.anchor,i),f=Rs(h.head,i);if(c==null||f==null||c.type!==t||f.type!==t)return;const{color:u="#30bced",name:O="Anonymous"}=l.user||{},d=l.user&&l.user.colorLight||u+"33",p=LO(c.index,f.index),g=YO(c.index,f.index),S=e.view.state.doc.lineAt(p),b=e.view.state.doc.lineAt(g);if(S.number===b.number)s.push({from:p,to:g,value:j.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})});else{s.push({from:p,to:S.from+S.length,value:j.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})}),s.push({from:b.from,to:g,value:j.mark({attributes:{style:`background-color: ${d}`},class:"cm-ySelection"})});for(let Q=S.number+1;Q0?-1:1,block:!1,widget:new MQ(u,O)})})}),this.decorations=j.set(s,!0)}}const LQ=Se.fromClass(jQ,{decorations:n=>n.decorations});class YQ{constructor(e){this.undoManager=e}addTrackedOrigin(e){this.undoManager.addTrackedOrigin(e)}removeTrackedOrigin(e){this.undoManager.removeTrackedOrigin(e)}undo(){return this.undoManager.undo()!=null}redo(){return this.undoManager.redo()!=null}}const Ir=Z.define({combine(n){return n[n.length-1]}});class EQ{constructor(e){this.view=e,this.conf=e.state.facet(Ir),this._undoManager=this.conf.undoManager,this.syncConf=e.state.facet(Dr),this._beforeChangeSelection=null,this._onStackItemAdded=({stackItem:t,changedParentTypes:i})=>{i.has(this.syncConf.ytext)&&this._beforeChangeSelection&&!t.meta.has(this)&&t.meta.set(this,this._beforeChangeSelection)},this._onStackItemPopped=({stackItem:t})=>{const i=t.meta.get(this);if(i){const r=this.syncConf.fromYRange(i);e.dispatch(e.state.update({selection:r,effects:[C.scrollIntoView(r)]})),this._storeSelection()}},this._storeSelection=()=>{this._beforeChangeSelection=this.syncConf.toYRange(this.view.state.selection.main)},this._undoManager.on("stack-item-added",this._onStackItemAdded),this._undoManager.on("stack-item-popped",this._onStackItemPopped),this._undoManager.addTrackedOrigin(this.syncConf)}update(e){e.selectionSet&&(e.transactions.length===0||e.transactions[0].annotation(Xr)!==this.syncConf)&&this._storeSelection()}destroy(){this._undoManager.off("stack-item-added",this._onStackItemAdded),this._undoManager.off("stack-item-popped",this._onStackItemPopped),this._undoManager.removeTrackedOrigin(this.syncConf)}}const zQ=Se.fromClass(EQ),_Q=({state:n,dispatch:e})=>n.facet(Ir).undo()||!0,WQ=({state:n,dispatch:e})=>n.facet(Ir).redo()||!0,VQ=(n,e,{undoManager:t=new EO(n)}={})=>{const i=new CQ(n,e),r=[Dr.of(i),XQ];return e&&r.push(AQ,LQ),t!==!1&&r.push(Ir.of(new YQ(t)),zQ,C.domEventHandlers({beforeinput(s,o){return s.inputType==="historyUndo"?_Q(o):s.inputType==="historyRedo"?WQ(o):!1}})),r},$O=We.define({create:n=>nr(n.doc.toString()),update:(n,e)=>e.docChanged?nr(e.newDoc.toString()):n});function Jt(n){return n.field($O,!1)??nr(n.doc.toString())}const BQ=5e3;function qQ(n){const e=n.trim().split(/[\s@._-]+/).filter(Boolean);return e.length?(e[0][0]+(e[1]?.[0]??"")).toUpperCase():"?"}function DQ(n,e=20){const t=document.createElement("span"),i=Vh(n);return t.className="pavatar",t.textContent=qQ(n),t.style.setProperty("--ph",String(i)),t.style.width=t.style.height=e+"px",t}class IQ extends ct{constructor(e,t,i){super(),this.name=e,this.folded=t,this.foldable=i}name;folded;foldable;eq(e){return e.name===this.name&&e.folded===this.folded&&e.foldable===this.foldable}toDOM(){const e=document.createElement("span");e.className="ms-head";const t=document.createElement("button");return t.type="button",t.className="ms-toggle",t.dataset.section=this.name,t.setAttribute("aria-label",(this.folded?"Expand ":"Collapse ")+this.name),t.setAttribute("aria-expanded",String(!this.folded)),t.disabled=!this.foldable,e.append(t,DQ(this.name)),e}ignoreEvent(){return!1}}class NQ extends ct{constructor(e){super(),this.s=e}s;eq(e){return e.s.kind===this.s.kind&&e.s.who===this.s.who&&e.s.at===this.s.at}toDOM(){const e=document.createElement("span");e.className="ms-status ms-"+this.s.kind,e.dataset.status=this.s.kind;const t=this.s.at?new Date(this.s.at).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";return e.textContent=this.s.kind==="typing"?`${this.s.who||"Someone"} is typing…`:this.s.kind==="updated"?`Updated ${t}`:this.s.kind==="empty"?"Not started":this.s.kind==="you"?"You":"",this.s.kind==="typing"&&this.s.who&&e.style.setProperty("--ph",String(Vh(this.s.who))),e}}function GQ(n){return n?n.remoteCursors():[]}function PO(n,e){let t=!1;return Hm(n).between(e.headingEnd,e.headingEnd+1,i=>{i===e.headingEnd&&(t=!0)}),t}function Xo(n){return n.to>n.headingEnd+1}function UQ(n,e){const t=Jt(n.state).find(r=>r.name===e);if(!t||!Xo(t))return;const i={from:t.headingEnd,to:t.to};n.dispatch({effects:PO(n.state,t)?yn.of(i):Qn.of(i)})}function FQ(n){const e=Se.fromClass(class{constructor(i){this.view=i,this.decorations=this.build(),setTimeout(()=>{const s=Jt(i.state).filter(o=>Xo(o)&&!Nr(o.name,n.me)).map(o=>Qn.of({from:o.headingEnd,to:o.to}));s.length&&i.dispatch({effects:s})}),this.tick=setInterval(()=>this.refresh(),2e3);const r=()=>setTimeout(()=>this.refresh());n.collab?.awareness.on("change",r),this.offAwareness=()=>n.collab?.awareness.off("change",r)}view;decorations=j.none;last=new Map;tick;offAwareness;refresh(){try{this.view.dispatch({})}catch{}}update(i){if(i.docChanged){const r=Jt(i.state);for(const s of i.transactions){if(!s.docChanged)continue;const o=!!s.annotation(Xr);s.changes.iterChangedRanges((l,a,h)=>{const c=r.find(f=>h>=f.from&&h<=f.to);c&&this.last.set(c.name,{at:Date.now(),remote:o})})}}this.decorations=this.build()}status(i,r){const s=r.find(l=>l.pos>=i.from&&l.pos<=i.to),o=this.last.get(i.name);return s&&o&&o.remote&&Date.now()-o.ati.decorations,eventHandlers:{mousedown(i,r){const s=i.target.closest?.(".ms-toggle");return s?.dataset.section?(i.preventDefault(),UQ(r,s.dataset.section),!0):!1}}}),t=W.transactionFilter.of(i=>{if(!i.docChanged||!i.annotation(ne.userEvent)||!n.offline())return i;const r=[];return i.changes.iterChangedRanges((s,o)=>r.push([s,o])),TO(Jt(i.startState),n.me,r)?i:(n.onBlocked?.(),[])});return[$O,$f({preparePlaceholder:(i,r)=>{const s=Jt(i).find(o=>o.headingEnd===r.from);return s?CO(s):""},placeholderDOM:(i,r,s)=>{const o=document.createElement("span");return o.className="ms-summary",o.textContent=s||"…",o.title="Expand",o.onclick=r,o}}),e,t]}const _h=n=>n.trim().split(/\s+/)[0];function Mt(n,e,t,i,r=i.length){n.dispatch({changes:{from:e,to:t,insert:i},selection:{anchor:e+r},userEvent:"input.complete"})}function HQ(n){return dS({override:[r=>{const s=r.matchBefore(/(?:^|\s)\/\w*$/);if(!s)return null;const o=r.state.doc.lineAt(r.pos),l=r.state.sliceDoc(o.from,s.from+(s.text.startsWith("/")?0:1));if(!/^\s*(?:[-*+]\s+(?:\[[ xX]\]\s+)?)?$/.test(l))return null;const a=s.from+(s.text.startsWith("/")?0:1),h=/[-*+]\s+$/.test(l),c=/\]\s+$/.test(l),f=[{label:"/action",displayLabel:"Action item",detail:"- [ ] with an owner",section:"Meeting",apply:(u,O,d,p)=>{const g=c?"":h?"[ ] ":"- [ ] ",S=` @${_h(n.me)}`;Mt(u,d,p,g+S,g.length)}},{label:"/mention",displayLabel:"Mention someone",detail:"@name",section:"Meeting",apply:(u,O,d,p)=>{Mt(u,d,p,"@"),Di(u)}},{label:"/link",displayLabel:"Link a file",detail:"[[ file from this project",section:"Meeting",apply:(u,O,d,p)=>{Mt(u,d,p,"[[]]",2),Di(u)}}];if(n.carryOver){const u=n.carryOver;f.push({label:"/carry",displayLabel:"Carry over from last meeting",detail:"open - [ ] items",section:"Meeting",apply:(O,d,p,g)=>{Mt(O,p,g,""),u().then(S=>{if(!S)return n.onNotice?.("No earlier meeting note in this folder.");if(!S.items.length)return n.onNotice?.(`No open items in ${S.from.split("/").pop()}.`);const b=O.state.selection.main.head,Q=O.state.doc.lineAt(b),w=/^\s*(?:[-*+]\s*(?:\[[ xX]\]\s*)?)?$/.test(Q.text),k=S.items.join(` `);w?Mt(O,Q.from,Q.to,k):Mt(O,b,b,` -`+k)})}})}return{from:a,options:f,filter:!0}},r=>{const s=r.matchBefore(/(?:^|[\s(])@[\w.-]*$/);if(!s)return null;const o=s.from+s.text.indexOf("@"),l=[...new Set(n.people().map(zh).filter(Boolean))];return{from:o,options:l.map(a=>({label:"@"+a,type:"variable",apply:"@"+a+" "}))}},r=>{const s=r.matchBefore(/\[\[[^\]\n]*$/);if(!s)return null;const o=r.state.sliceDoc(r.pos,r.pos+2);return{from:s.from+2,options:n.files().map(l=>{const a=(l.split("/").pop()??l).replace(/\.md$/i,"");return{label:a,detail:l.includes("/")?l.slice(0,l.lastIndexOf("/")):"",apply:(h,c,f,u)=>Mt(h,f,u+(o==="]]"?2:0),a+"]]")}})}}],activateOnTyping:!0,icons:!1})}function oy({apiBase:n,path:e,initial:t,onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,baseSha:c,me:f,mode:u="markdown",meeting:O=!1,files:d,onInfo:p,onPending:g,handle:S}){const b=oe.useRef(null),Q=oe.useRef(null),w=oe.useRef({onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,onInfo:p,onPending:g});w.current={onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,onInfo:p,onPending:g};const k=oe.useRef(d??[]);k.current=d??[];const v=oe.useRef(u);v.current=u;const T=oe.useRef(O);T.current=O;const L=oe.useRef("connecting"),I=oe.useRef(new fn),U=oe.useRef(t),Y=oe.useRef(t),A=oe.useRef(null),q=oe.useRef(null);oe.useEffect(()=>{if(t===Y.current)return;U.current=t;const H=A.current;w.current.onExternal?.(H&&q.current?H.merge(t,te.current):"blocked")},[t]);const N=oe.useRef(f);N.current=f;const te=oe.useRef(c);te.current=c;const[Ue,ht]=oe.useState(!1);return oe.useEffect(()=>{if(!b.current)return;let H=null;ht(!1);const Fe=N.current?.name??"",Gt=j=>{const ft=j.state.selection.main.head,vi=j.state.doc.lineAt(ft);w.current.onInfo?.({text:j.state.doc.toString(),line:vi.number,col:ft-vi.from+1,collab:H===j&&Qe?ye.collab:null})},Me=()=>T.current?GQ({me:Fe,collab:ye.collab,offline:()=>Qe&&L.current!=="live",onBlocked:()=>kl("Offline: other people's sections are read-only until you reconnect.")}):[],de=[I.current.of(_h(v.current)),Jp(),$g(),xQ(),sg(ag,{fallback:!0}),UQ({me:Fe,files:()=>k.current,people:()=>{const j=ir(H?.state.doc.toString()??"").map(ft=>ft.name);return ye.collab.awareness.getStates().forEach(ft=>{const vi=ft.user?.name;vi&&j.push(vi)}),j},carryOver:T.current?async()=>{const j=TO(e,k.current);if(!j)return null;const ft=await CO(ZO(n,j));return{from:j,items:ft.kind==="text"?XO(ft.text):[]}}:void 0,onNotice:j=>kl(j)}),pn.of([...Ou,...tg,...v0,...Mg,T0]),C.lineWrapping,C.updateListener.of(j=>{(j.docChanged||j.selectionSet||j.focusChanged)&&Gt(j.view)})];let Qe=!1;const ct=C.updateListener.of(j=>{j.docChanged&&(w.current.onStateChange?.("dirty"),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{ye.saveNow()},YO))}),Qt=()=>{H||!b.current||(H=new C({parent:b.current,state:W.create({doc:U.current,extensions:[...de,Me(),ct]})}),q.current=H,ht(!0),H.focus(),Gt(H))},Ut=()=>{H||!b.current||(H=new C({parent:b.current,state:W.create({doc:ye.collab.text.toString(),extensions:[...de,_Q(ye.collab.text,ye.collab.awareness),Me()]})}),Qe=!0,q.current=H,ht(!0),H.focus(),Gt(H))},ye=EO({apiBase:n,path:e,seed:U.current,baseSha:te.current,who:N.current?.name,me:N.current,onConflictCopy:j=>w.current.onConflictCopy?.(j),onShrinkRefused:j=>RO(e,j),onShrinkWithdrawn:AO,onReady:()=>Ut(),onSolo:()=>Qt(),onState:j=>w.current.onStateChange?.(j),onCollab:j=>{L.current=j,w.current.onCollab?.(j)},onPending:j=>w.current.onPending?.(j),onPeers:j=>w.current.onPeers?.(j),onSaved:j=>w.current.onSaved?.(j),onWriting:()=>w.current.onWriting?.(),soloText:()=>H?.state.doc.toString()??"",soloApply:j=>H?.dispatch({changes:j})});return A.current=ye,S&&(S.current=ye),()=>{Q.current&&clearTimeout(Q.current),A.current=null,S?.current===ye&&(S.current=null),q.current=null,ye.destroy(),H?.destroy()}},[n,e]),oe.useEffect(()=>{q.current?.dispatch({effects:I.current.reconfigure(_h(u))})},[u]),kn.jsxs(kn.Fragment,{children:[!Ue&&kn.jsx("pre",{className:"cm-preview cm-mode-"+u,"aria-busy":"true",children:t}),kn.jsx("div",{ref:b,id:"editor",className:"cm-host cm-mode-"+u,"data-mode":u})]})}function _h(n){return n==="markdown"?[dm()]:[C.contentAttributes.of({"data-write":""})]}export{oy as Editor}; +`+k)})}})}return{from:a,options:f,filter:!0}},r=>{const s=r.matchBefore(/(?:^|[\s(])@[\w.-]*$/);if(!s)return null;const o=s.from+s.text.indexOf("@"),l=[...new Set(n.people().map(_h).filter(Boolean))];return{from:o,options:l.map(a=>({label:"@"+a,type:"variable",apply:"@"+a+" "}))}},r=>{const s=r.matchBefore(/\[\[[^\]\n]*$/);if(!s)return null;const o=r.state.sliceDoc(r.pos,r.pos+2);return{from:s.from+2,options:n.files().map(l=>{const a=(l.split("/").pop()??l).replace(/\.md$/i,"");return{label:a,detail:l.includes("/")?l.slice(0,l.lastIndexOf("/")):"",apply:(h,c,f,u)=>Mt(h,f,u+(o==="]]"?2:0),a+"]]")}})}}],activateOnTyping:!0,icons:!1})}function ay({apiBase:n,path:e,initial:t,onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,baseSha:c,me:f,mode:u="markdown",meeting:O=!1,files:d,onInfo:p,onPending:g,handle:S}){const b=oe.useRef(null),Q=oe.useRef(null),w=oe.useRef({onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,onInfo:p,onPending:g});w.current={onSaved:i,onWriting:r,onStateChange:s,onCollab:o,onPeers:l,onExternal:a,onConflictCopy:h,onInfo:p,onPending:g};const k=oe.useRef(d??[]);k.current=d??[];const v=oe.useRef(u);v.current=u;const T=oe.useRef(O);T.current=O;const L=oe.useRef("connecting"),I=oe.useRef(new un),U=oe.useRef(t),Y=oe.useRef(t),A=oe.useRef(null),q=oe.useRef(null);oe.useEffect(()=>{if(t===Y.current)return;U.current=t;const G=A.current;w.current.onExternal?.(G&&q.current?G.merge(t,te.current):"blocked")},[t]);const N=oe.useRef(f);N.current=f;const te=oe.useRef(c);te.current=c;const[He,ft]=oe.useState(!1);return oe.useEffect(()=>{if(!b.current)return;let G=null;ft(!1);const Ke=N.current?.name??"",Gt=M=>{const je=M.state.selection.main.head,Ti=M.state.doc.lineAt(je);w.current.onInfo?.({text:M.state.doc.toString(),line:Ti.number,col:je-Ti.from+1,collab:G===M&&Qe?Me.collab:null})},Re=()=>T.current?FQ({me:Ke,collab:Me.collab,offline:()=>Qe&&L.current!=="live",onBlocked:()=>wl("Offline: other people's sections are read-only until you reconnect.")}):[],de=[I.current.of(Wh(v.current)),tm(),vg(),wQ(),lg(cg,{fallback:!0}),HQ({me:Ke,files:()=>k.current,people:()=>{const M=nr(G?.state.doc.toString()??"").map(je=>je.name);return Me.collab.awareness.getStates().forEach(je=>{const Ti=je.user?.name;Ti&&M.push(Ti)}),M},carryOver:T.current?async()=>{const M=ZO(e,k.current);if(!M)return null;const je=await XO(AO(n,M));return{from:M,items:je.kind==="text"?RO(je.text):[]}}:void 0,onNotice:M=>wl(M)}),mn.of([{key:"Mod-s",preventDefault:!0,run:()=>(Me.saveNow(),!0)},...du,...ng,...C0,...Lg,Z0]),C.lineWrapping,C.updateListener.of(M=>{(M.docChanged||M.selectionSet||M.focusChanged)&&Gt(M.view)})];let Qe=!1,qe=!1;const ut=U.current,Ut=C.updateListener.of(M=>{M.docChanged&&(w.current.onStateChange?.("dirty"),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{Me.saveNow()},zO))}),vi=(M=!1)=>{G||!b.current||(qe=M,G=new C({parent:b.current,state:W.create({doc:M?ut:U.current,extensions:[...de,Re(),Ut]})}),q.current=G,ft(!0),G.focus(),Gt(G))},vO=()=>{if(!b.current)return;let M=-1;if(G&&qe&&(Q.current&&clearTimeout(Q.current),M=G.state.selection.main.head,G.destroy(),G=null,qe=!1),G)return;const je=Me.collab.text.toString();G=new C({parent:b.current,state:W.create({doc:je,...M>=0?{selection:{anchor:Math.min(M,je.length)}}:{},extensions:[...de,VQ(Me.collab.text,Me.collab.awareness),Re()]})}),Qe=!0,q.current=G,ft(!0),G.focus(),Gt(G)},Me=_O({apiBase:n,path:e,seed:U.current,baseSha:te.current,who:N.current?.name,me:N.current,onConflictCopy:M=>w.current.onConflictCopy?.(M),onShrinkRefused:M=>jO(e,M),onShrinkWithdrawn:MO,onReady:()=>vO(),onSolo:()=>vi(),onStalled:()=>vi(!0),onState:M=>w.current.onStateChange?.(M),onCollab:M=>{L.current=M,w.current.onCollab?.(M)},onPending:M=>w.current.onPending?.(M),onPeers:M=>w.current.onPeers?.(M),onSaved:M=>w.current.onSaved?.(M),onWriting:()=>w.current.onWriting?.(),soloText:()=>G?G.state.doc.toString():ut,soloApply:M=>G?.dispatch({changes:M})});return A.current=Me,S&&(S.current=Me),()=>{Q.current&&clearTimeout(Q.current),A.current=null,S?.current===Me&&(S.current=null),q.current=null,Me.destroy(),G?.destroy()}},[n,e]),oe.useEffect(()=>{q.current?.dispatch({effects:I.current.reconfigure(Wh(u))})},[u]),wn.jsxs(wn.Fragment,{children:[!He&&wn.jsx("pre",{className:"cm-preview cm-mode-"+u,"aria-busy":"true",children:t}),wn.jsx("div",{ref:b,id:"editor",className:"cm-host cm-mode-"+u,"data-mode":u})]})}function Wh(n){return n==="markdown"?[mm()]:[C.contentAttributes.of({"data-write":""})]}export{ay as Editor}; diff --git a/internal/webapp/static/assets/VisualEdit-CwChUaNM.js b/internal/webapp/static/assets/VisualEdit-CwChUaNM.js new file mode 100644 index 00000000..4d16cebf --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-CwChUaNM.js @@ -0,0 +1 @@ +import{r as i,j as y,w as pe,a as he}from"./index-BD48v6-0.js";import{o as be,D as ye,c as T,a as C,m as ie,d as ce}from"./sharedfile-DXV-dXg-.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function Te(k){if(!globalThis.crypto?.subtle)return null;try{const E=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(k));return[...new Uint8Array(E)].map(g=>g.toString(16).padStart(2,"0")).join("")}catch{return null}}function je({apiBase:k,fileURL:E,path:g,initial:ae,me:P,onStateChange:H,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,le]=i.useState(null),[de,J]=i.useState(!1),[ue,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:H,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:H,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ae),L=i.useRef(P);L.current=P;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const fe=700;J(!1),K(!1);const xe=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),me=setTimeout(()=>K(!0),24e3),s=X.current=be({apiBase:k,path:g,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>he(g,e),onShrinkWithdrawn:pe,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const t=e.getText("body").toString(),r=s.collab.text.toString();if(x&&t===r)for(const[a,n]of d){const u=T(n.from,e),m=T(n.to,e);u&&m&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,m.index),span:n.span,orig:n.orig})}else d.clear(),x=!1,t!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new ye,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:t,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");t>e&&a.delete(e,t-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(h.some(n=>n.end>t.length||n.start>n.end)){h=null,p(n=>n+1);return}const r=await Te(t);if(r!==null?r!==$:D>=0&&t.length!==D){h=null,p(n=>n+1);return}d.clear();for(const n of h)d.set(Z(n),{from:C(e,n.start),to:C(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",D=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const t=e.data;if(!t||typeof t!="object")return;if(t.type==="bd-edit:clobbered"){le("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(t.type==="bd-edit:ready"){h=t.ranges,$=t.hash,D=t.len,await w();return}if(t.type!=="bd-edit:patch")return;const r=d.get(Z(t));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),ge=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),oe=ie(r.orig,N,t.html),se=oe.ok?oe.text:t.html;if(r.orig=t.html,N===se)return;o.transact(()=>{for(const f of ce(N,se))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},fe);return}const a=s.collab.doc,n=T(r.from,a),u=T(r.to,a);if(!n||!u||n.index>u.index)return;const m=s.collab.text,te=u.index-n.index;if(n.index===0&&u.index===m.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:m.length}),d.clear(),x=!1,p(c=>c+1);return}const M=m.toString().slice(n.index,u.index),ne=ie(r.orig,M,t.html),re=ne.ok?ne.text:t.html;r.orig=t.html,M!==re&&s.collab.applySplices(ce(M,re).map(c=>({...c,index:c.index+n.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(xe),clearTimeout(me),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[k,g,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),ue&&!de&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:E+(E.includes("?")?"&":"?")+"edit=1",title:g},Q)]})}export{je as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-DpNpdB4J.js b/internal/webapp/static/assets/VisualEdit-DpNpdB4J.js deleted file mode 100644 index c1a86db6..00000000 --- a/internal/webapp/static/assets/VisualEdit-DpNpdB4J.js +++ /dev/null @@ -1 +0,0 @@ -import{r,j as d,w as ee,a as te}from"./index-Bnuge9vv.js";import{o as ne,c as O,a as Q}from"./sharedfile-nk3qnjVG.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function re(m){if(!globalThis.crypto?.subtle)return null;try{const h=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(m));return[...new Uint8Array(h)].map(i=>i.toString(16).padStart(2,"0")).join("")}catch{return null}}function le({apiBase:m,fileURL:h,path:i,initial:U,me:k,onStateChange:E,onCollab:A,onPeers:F,onConflictCopy:P,baseSha:x,onSaved:W,onWriting:C,onRendered:H}){const y=r.useRef(null),[L,X]=r.useState(null),[Y,N]=r.useState(!1),[Z,M]=r.useState(!1),G=r.useRef(0),[I,g]=r.useState(0),o=r.useRef({onStateChange:E,onCollab:A,onPeers:F,onSaved:W,onWriting:C,onRendered:H,onConflictCopy:P});o.current={onStateChange:E,onCollab:A,onPeers:F,onSaved:W,onWriting:C,onRendered:H,onConflictCopy:P};const v=r.useRef(U),R=r.useRef(k);R.current=k;const V=r.useRef(x);V.current=x;const q=r.useRef(null);return r.useEffect(()=>{q.current?.rebase(x)},[x]),r.useEffect(()=>{let l=null,S=!1;N(!1),M(!1);const _=setTimeout(()=>{!w&&G.current<1&&(G.current++,g(e=>e+1))},11e3),$=setTimeout(()=>M(!0),24e3),s=q.current=ne({apiBase:m,path:i,seed:v.current,baseSha:V.current,who:R.current?.name,me:R.current,onConflictCopy:e=>o.current.onConflictCopy?.(e),onShrinkRefused:e=>te(i,e),onShrinkWithdrawn:ee,onReady:()=>{S=!0,p()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,v.current),S=!0,p()},onState:e=>o.current.onStateChange?.(e),onCollab:e=>o.current.onCollab?.(e),onPeers:e=>o.current.onPeers?.(e),onSaved:e=>o.current.onSaved?.(e),onWriting:()=>o.current.onWriting?.(),soloText:()=>v.current}),b=new Map,z=e=>e.start+","+e.end,p=async()=>{if(w||!l||!S)return;const e=s.collab.text.toString();if(!e)return;if(l.some(t=>t.end>e.length||t.start>t.end)){l=null,g(t=>t+1);return}const n=await re(e);if(n!==null?n!==D:T>=0&&e.length!==T){l=null,g(t=>t+1);return}b.clear();for(const t of l)b.set(z(t),{from:Q(s.collab.text,t.start),to:Q(s.collab.text,t.end),span:t.end-t.start});w=!0,N(!0),o.current.onRendered?.()};let D="",T=-1,w=!1;const J=async e=>{if(!y.current||e.source!==y.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){X("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){l=n.ranges,D=n.hash,T=n.len,await p();return}if(n.type!=="bd-edit:patch")return;const a=b.get(z(n));if(!a)return;const t=s.collab.doc,c=O(a.from,t),f=O(a.to,t);if(!c||!f||c.index>f.index)return;const u=s.collab.text,j=f.index-c.index;if(c.index===0&&f.index===u.length&&a.spana.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:j,stamped:a.span,docLength:u.length}),b.clear(),w=!1,g(B=>B+1);return}u.toString().slice(c.index,f.index)!==n.html&&t.transact(()=>{u.delete(c.index,j),u.insert(c.index,n.html)})},K=()=>{p()};return s.collab.text.observe(K),window.addEventListener("message",J),()=>{clearTimeout(_),clearTimeout($),s.collab.text.unobserve(K),setTimeout(()=>{window.removeEventListener("message",J),s.destroy()},300)}},[m,i,I]),d.jsxs(d.Fragment,{children:[L&&d.jsx("div",{id:"edit-clobbered",className:"banner",children:L}),Z&&!Y&&d.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",d.jsx("b",{children:"Edit source"}),"."]}),d.jsx("iframe",{ref:y,className:"htmlview",sandbox:"allow-scripts",src:h+(h.includes("?")?"&":"?")+"edit=1",title:i},I)]})}export{le as VisualEdit}; diff --git a/internal/webapp/static/assets/index-BD48v6-0.js b/internal/webapp/static/assets/index-BD48v6-0.js new file mode 100644 index 00000000..bf253fcf --- /dev/null +++ b/internal/webapp/static/assets/index-BD48v6-0.js @@ -0,0 +1,131 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CUvVSG63.js","assets/sharedfile-DXV-dXg-.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CwChUaNM.js"])))=>i.map(i=>d[i]); +import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const u of o.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,o){var u=null;if(o!==void 0&&(u=""+o),i.key!==void 0&&(u=""+i.key),"key"in i){o={};for(var f in i)f!=="key"&&(o[f]=i[f])}else o=i;return i=o.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:o}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var l=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1p||F[d]!==ne[p]){var ce=` +`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function lt(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function hn(s){try{var a="",c=null;do a+=lt(s,c),c=s,s=s.return;while(s);return a}catch(d){return` +Error generating stack: `+d.message+` +`+d.stack}}var Nt=Object.prototype.hasOwnProperty,Ct=e.unstable_scheduleCallback,mn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function vt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function yt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function _t(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function wt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),wt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return wt(J,G,Vc(te),ue);if(te.$$typeof===R)return wt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=wt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var wt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(wt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(wt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Et===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Et.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[sn]=s,a[kn]=c}catch(v){pt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[sn]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kwt&&(C=wt,wt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,wt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>wt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(_t(s,2),Js(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),_t(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(_t(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return Ct(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||vt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:o,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||o&&!o(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(o))return!1}else if(!Vl(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const o=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,o)=>{e=i,t=o});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const o=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{o(()=>{f(...h)})},schedule:o,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),o=()=>i.status!=="pending",u=S=>{if(!o()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{o()||(r?.(),i.resolve(S))},w=S=>{o()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(o()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,o()||e.onContinue?.()}),j=()=>{if(o())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(o())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&o.length){const j=i==="backward",S=j?YS:Ap,E={pages:o,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??o.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,o=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===o?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const o=new Set(i??this.#p);return this.options.throwOnError&&o.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&o.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:o,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:o&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,u)=>{this.#a({type:"failed",failureCount:o,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const o=await this.#s.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#a({type:"success",data:o}),o}catch(o){try{await this.#n.config.onError?.(o,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(o,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,o,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:o}),o}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(o){Promise.reject(o)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(o){Promise.reject(o)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(o){Promise.reject(o)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(o){Promise.reject(o)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let o=this.get(i);return o||(o=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(r.queryHash)?.state.data,u=aM(t,o);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,n);return n.throwOnError||(o=o.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),o=fn(),u=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=o.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!o.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(o,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1){const o=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return o.status===401&&!i&&Bd(),o.ok||await ko(o),qd("PUT",e),await o.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return o.ok||await ko(o),await o.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const o=yw(i,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let i=0;i{let{children:i,...o}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(o,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...f)=>{const h=o(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,o)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(h,{...f,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>l.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(o,u){const f=b.createContext(u);f.displayName=o+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return l.jsx(S.Provider,{value:E,children:x})};m.displayName=o+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${o}\``)}return[m,y]}const i=()=>{const o=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||o;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(o)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return l.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=o(f,_),T=Kt(E,R.collectionRef);return l.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=o(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),l.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=o(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else o(y)},[f,e,o,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),o=b.useRef(t);return uT(()=>{o.current=t},[t]),b.useEffect(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),o=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:o}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),o=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(o.current=u.current??Rl(r.current),u.current=void 0):o.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=o.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(o.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const o=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{o?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),l.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),l.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...o].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,o,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=o=>{o.target&&!r.current&&cj(ST,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,o):i.dispatchEvent(o)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(o),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return l.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,o]=b.useState(!1);ir(()=>o(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(l.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,o=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` + .`.concat(FT,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(f,"px ").concat(r,`; + } + body[`).concat(yo,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(i,`px; + padding-top: `).concat(o,`px; + padding-right: `).concat(u,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(f,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(f,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(sd,` { + right: `).concat(f,"px ").concat(r,`; + } + + .`).concat(rd,` { + margin-right: `).concat(f,"px ").concat(r,`; + } + + .`).concat(sd," .").concat(sd,` { + right: 0 `).concat(r,`; + } + + .`).concat(rd," .").concat(rd,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(yo,`] { + `).concat(IT,": ").concat(f,`px; + } +`)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var o=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(o,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var o=yj(e,r),u=o[1],f=o[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var o=dO(e,window.getComputedStyle(t).direction),u=o*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-o*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},pO=0,oo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],o=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==o)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(o),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==o}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(o,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var o=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(o.get(w)||0)+1;lo.set(w,S),o.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=o.get(g)-1;lo.set(g,w),o.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:o,caller:Yd});return l.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),o=Kt(t,i.triggerRef);return l.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:o,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=qs(Kg,t);return l.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=qs(xd,e.__scopeDialog);return o.modal?l.jsx(fr,{present:r||o.open,children:l.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),o=_T(),u=Kt(t,o);return l.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:l.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=qs(Co,e.__scopeDialog);return l.jsx(fr,{present:r||o.open,children:o.modal?l.jsx(NO,{...i,ref:t}):l.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const o=r.current;if(o)return bj(o)},[]),l.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,o=>{const u=o.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&o.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return l.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=o.target;n.triggerRef.current?.contains(u)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,...u}=e,f=qs(Co,n);return dj(),l.jsx(l.Fragment,{children:l.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:l.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return l.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return l.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return l.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let u,f;if("borderBoxSize"in o){const h=o.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),o=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let o=LO(Ea(e),n==="start",r);return i&&(o=o.map(u=>u+"-"+i),t&&(o=o.concat(o.map(Fp)))),o}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const o=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=o==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:o,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(E)))==null||n?E:E.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(f.floating)),T=await(o.isElement==null?void 0:o.isElement(R))&&await(o.getScale==null?void 0:o.getScale(R))||{x:1,y:1},A=Sd(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:o,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=o.reference[j]+o.reference[x]-w[x]-o.floating[j],A=w[x]-o.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||o.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&o.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=o.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...o,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...o,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=o&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:o+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await o.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:o,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:o},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:o}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(o.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(o.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(o){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),o=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==o||bd(r)!==u;return f&&(n=o,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Lj(t);let u=(o?bd(n.width):n.width)/r,f=(o?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(o,n,r)?$j(o):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(o&&r){const w=Xn(o),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&o)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!o)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!o?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(o+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),o=Br(e),u=i.visualViewport;let f=o.clientWidth,h=o.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(o)<=0){const w=o.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(o.clientWidth-x.clientWidth-S),_=getComputedStyle(o).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=xo(e),u=e.clientWidth*o.x,f=e.clientHeight*o.y,h=i*o.x,m=r*o.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const o=ur(e).position==="fixed";let u=o?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:o?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:o.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||o?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),o&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,o):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),o&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},o={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:o})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const o=i[r];if(!(o==="_owner"&&e.$$typeof)&&!jd(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:o,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=o||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...o}=e;return l.jsx(ot.svg,{...o,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:l.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[o,u]=b.useState(void 0);return l.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=qj(Gj,n),u=b.useRef(null),f=o.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=o.placementState&&iv(o.placementState),w=g?.[0],x=g?.[1];return r?null:l.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:o="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(o!=="center"?"-"+o:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ht}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),l.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:l.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:l.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,o=IA(Yj,r),u=PA[o.placedSide];return l.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:l.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>l.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:l.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:l.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:o,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(o),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),l.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:l.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:u,...f}=e,h=us(),m=o||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),l.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:l.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(o),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),l.jsx(Xj,{...f,children:l.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:l.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return l.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=Si(lv,t);return l.jsx(mD,{scope:t,forceMount:n,children:l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return l.jsx(Gl.Provider,{scope:e.__scopeMenu,children:l.jsx(fr,{present:r||o.open,children:l.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?l.jsx(gD,{...i,ref:t}):l.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const o=r.current;if(o)return bj(o)},[]),l.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return l.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return l.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:l.jsx(be,{...$,children:l.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(o,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:l.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:l.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:l.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,o),m=b.useRef(!1),y=()=>{const g=o.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return l.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[o.children]),l.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:l.jsx(rD,{asChild:!0,...f,focusable:!r,children:l.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return l.jsx(wC,{scope:e.__scopeMenu,checked:n,children:l.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=Vr(r);return l.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:o,children:l.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),o=n===i.value;return l.jsx(wC,{scope:e.__scopeMenu,checked:o,children:l.jsx(rf,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":hv(o),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=CD(fv,n);return l.jsx(fr,{present:r||_d(o.checked)||o.checked===!0,children:l.jsx(ot.span,{...i,ref:t,"data-state":hv(o.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return l.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),o=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=o,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return l.jsx(ov,{asChild:!0,...m,children:l.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{o.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(o.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];o.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(w),w.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||o.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...o}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return l.jsx(Gl.Provider,{scope:e.__scopeMenu,children:l.jsx(fr,{present:r||u.open,children:l.jsx(Gl.Slot,{scope:e.__scopeMenu,children:l.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...o,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let u=RD(e,Math.max(o,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,u=t.length-1;or!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:o,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return l.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:l.jsx(MC,{...y,dir:o,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,o=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{o.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),o.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),l.jsxs(l.Fragment,{children:[l.jsx(TC,{...u,virtualRef:m}),l.jsx(ot.span,{"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),o.open&&o.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return l.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),o=Pn(n),u=b.useRef(!1);return l.jsx(AC,{...o,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:o??!1,onChange:u,caller:of});return l.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:l.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=e_(n_,n),u=Un(n),f=Kt(t,o.triggerRef);return l.jsx(TC,{asChild:!0,...u,children:l.jsx(ot.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(o.onOpenToggle(),o.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&o.onOpenToggle(),h.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return l.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),o=Un(n),u=b.useRef(!1);return l.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>l.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,o=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return l.jsx(ot.div,{"data-orientation":o,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),l.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:o})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),o?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),l.jsx(Xj,{...m,children:l.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),o=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),l.jsx(Wj,{asChild:!0,...u,children:l.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=oc(pv,t);return l.jsx(Gz,{scope:t,forceMount:n,children:l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,u=oc(_o,e.__scopeTooltip);return l.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?l.jsx(w_,{side:i,...o,ref:t}):l.jsx(Zz,{side:i,...o,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),o=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),l.jsx(w_,{...e,ref:o})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),l.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:l.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[l.jsx(Xz,{children:r}),l.jsx(Yz,{scope:n,isInside:!0,children:l.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:l.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,i,o)){case o:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,u=t.length-1;or!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const o=t[t.length-1],u=t[t.length-2];if((o.x-u.x)*(i.y-u.y)>=(o.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const o=n[n.length-1],u=n[n.length-2];if((o.x-u.x)*(i.y-u.y)>=(o.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],o=n.nextPart.get(i);if(o){const m=N_(e,t+1,o);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let o=0;o{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),o=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(o,u)=>{n[o]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(o){let u=n[o];if(u!==void 0)return u;if((u=r[o])!==void 0)return i(o,u),u},set(o,u){o in n?n[o]=u:i(o,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const o=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(o,x,w,j)};if(t){const i=t+Gw,o=r;r=u=>u.startsWith(i)?o(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=o=>n({className:o,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let o=0;o0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:o(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,o;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,o=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return o=u,(...h)=>o(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),o=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ht=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[o,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return l.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return l.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return l.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return l.jsx(o4,{children:l.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,l.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:o,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!o&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(o)?o:[o]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},o)=>b.createElement(f3,{ref:o,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const o=document.getElementById("main");o&&(n&&t?o.setAttribute("inert",""):o.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,o=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-o),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,o=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!o)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+o);od(f),np(f)};return l.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?l.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return l.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return l.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[l.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),l.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),l.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return l.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return l.jsxs(l.Fragment,{children:[l.jsx("div",{id:"sb-backdrop",onClick:ds}),l.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??l.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,l.jsx(iL,{}),l.jsx("div",{id:"rail",children:e.rail??l.jsx(oE,{})})]}),l.jsxs("main",{id:"main",children:[e.topbar,e.exit,l.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return l.jsxs(l.Fragment,{children:[e??l.jsx("span",{className:"rail-mark",children:l.jsx(Sv,{size:20})}),l.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return l.jsxs(uf,{delayDuration:100,children:[l.jsx(df,{asChild:!0,children:l.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[l.jsx(ge,{name:e.icon}),e.badge?l.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),l.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&l.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return l.jsxs("header",{id:"vault",children:[l.jsx("span",{id:"vault-badge",children:l.jsx(Sv,{size:22})}),l.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:o=>{n&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())},children:t}),i&&l.jsx("span",{id:"vault-beta",children:"Beta"}),r&&l.jsx("div",{className:"vault-actions",children:l.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:l.jsx(ge,{name:"power"})})})]})}function ci(e){return l.jsxs("header",{id:"topbar",children:[l.jsxs(uf,{delayDuration:150,children:[l.jsx(df,{asChild:!0,children:l.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:l.jsx(ge,{name:"sidebar"})})}),l.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",l.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,l.jsx("span",{id:"crumb",children:e.crumb}),l.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,o=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===o),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),u?this.toasts=this.toasts.map(h=>h.id===o?(this.publish({...h,...t,id:o,title:r}),{...h,...t,id:o,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:o}),o},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let o=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))o=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){o=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){o=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){o=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){o=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{o&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,o,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ht,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),lt=ye.useRef(g.duration||Y||Jw),hn=ye.useRef(null),Nt=ye.useRef(null),Ct=_===0,mn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,vt,yt)=>yt>=hs?ze:ze+vt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{lt.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=Nt.current;if(ze){const vt=ze.getBoundingClientRect().height;return Fe(vt),j(yt=>[{toastId:g.id,height:vt,position:g.position},...yt]),()=>j(yt=>yt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=Nt.current,vt=ze.style.height;ze.style.height="auto";const yt=ze.getBoundingClientRect().height;ze.style.height=vt,Fe(yt),j(Vt=>Vt.find(_t=>_t.toastId===g.id)?Vt.map(_t=>_t.toastId===g.id?{..._t,height:yt}:_t):[{toastId:g.id,height:yt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(vt=>vt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},lt.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var vt;return ye.createElement("div",{className:tr($?.loader,g==null||(vt=g.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":mn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":Ct,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(hn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,vt,yt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=Nt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((vt=Nt.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_t=new Date().getTime()-((yt=hn.current)==null?void 0:yt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/_t;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var nn,Nn;(nn=Nt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(Nn=Nt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var vt,yt,Vt;if(!Q.current||!An||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const _t=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(_t)>1)&&K(Math.abs(En)>Math.abs(_t)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&_t<0||nn.includes("bottom")&&_t>0)Nn.y=_t;else{const Jn=_t*gr(_t);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(yt=Nt.current)==null||yt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=Nt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(o=g.classNames)==null?void 0:o.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const o=i===1,u=o?"--mobile-offset":"--offset",f=o?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:o="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([o].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,o]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return l.jsx(zL,{theme:t,className:"toaster group",icons:{success:l.jsx(B3,{className:"size-4"}),info:l.jsx(I5,{className:"size-4"}),warning:l.jsx(tE,{className:"size-4"}),error:l.jsx(g6,{className:"size-4"}),loading:l.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return l.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:o}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=o?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...o,...f}[S]):{...o,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const o=r?YM:"button";return l.jsx(o,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return l.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return l.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return l.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return l.jsxs(BL,{"data-slot":"dialog-portal",children:[l.jsx(GL,{}),l.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&l.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[l.jsx(nE,{}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return l.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return l.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(o=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:o}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return l.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:l.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?l.jsx(YL,{m:e}):l.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[o,u]=b.useState(e.value),f=e.match===void 0||o.trim()===e.match,h=()=>{const m=o;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return l.jsxs(l.Fragment,{children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.title})}),l.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),l.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:o,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&l.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),l.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return l.jsxs(l.Fragment,{children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.title})}),l.jsx("div",{className:"modal-msg",children:e.message}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),l.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,o=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{o(e.keep)};return l.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:l.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[l.jsxs("div",{className:"sd-head",children:[l.jsx("span",{className:"sd-icon","aria-hidden":"true",children:l.jsx(ge,{name:"shield"})}),l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),l.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),l.jsxs("div",{className:"sd-compare",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Saved version"}),l.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Your editor"}),l.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),l.jsxs("div",{className:"modal-actions sd-actions",children:[l.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),l.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{o(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",o=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),o&&(u.connect=o),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),o=i.path.indexOf("/"),u=o===-1?i.path:i.path.slice(0,o);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=o===-1?"":i.path.slice(o+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const o=vE(e),u=o&&i?"edit/"+o:o,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(o=>{n.push(o);const u=t(o);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return o=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(o);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=o.getValue())!=null?u:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,o],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(o,n,t,e)},{}),o}function h$(e,t,n,r){var i,o;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(o=f.id)!=null?o:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(o),u},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(o,e)}),o}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var o,u;const f=(o=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?o:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(i!=null&&i.includes(o.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const o=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,o,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const o=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,o,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,o,u,f,h,m;return[...(i=(o=t[0])==null?void 0:o.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,o;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(o=h[0])==null?void 0:o.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,o,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const o=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(o))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const o=e.getValue(t);return o>=r&&o<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(o>u){const f=o;o=u,u=f}return[o,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),o=r?.find(y=>y.id===e.id),u=Sa(n,o?o.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(o){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var o;return(o=Sa(t,i))==null?void 0:o.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const o=i.getValue(e);return r+(typeof o=="number"?o:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(r=o)&&(r=o)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(o=>{const u=o.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let o=i.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((o,u)=>o-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(u=>u.id===o)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let o=[];if(!(t!=null&&t.length))o=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&o.push(f.splice(m,1)[0])}o=[...o,...f]}return k$(o,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var o,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((o=i?.left)!=null?o:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,o,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((o=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,o=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return o?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const o=[...r??[],...i??[]];return n.filter(u=>!o.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(u=>u.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(u=>u.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,o;return!!((i=r.left)!=null&&i.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(o=>!i.includes(o.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=o??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,o)=>i+o.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,o)=>i+o.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var o;n+=(o=i.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return o=>{if(!r||!i||(o.persist==null||o.persist(),ip(o)&&o.touches&&o.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(o)?Math.round(o.touches[0].clientX):o.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(o)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,o)=>({...i,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,o;e.setExpanded(r?{}:(i=(o=e.initialState)==null?void 0:o.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const u=o.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const o=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!o,!o&&n)return{...u,[e.id]:!0};if(o&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=o=>Sa(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let o=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,u)),{...i,pageIndex:o}})},e.resetPageIndex=r=>{var i,o;e.setPageIndex(r?eg:(i=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,o;e.setPageSize(r?tg:(i=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const o=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/o);return{...i,pageIndex:f,pageSize:o}})},e.setPageCount=r=>e.setPagination(i=>{var o;let u=Sa(r,(o=e.options.pageCount)!=null?o:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((o,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const o=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...o]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,o=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return o?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const o=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=o?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,o;return!!((i=r.top)!=null&&i.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(o=>!i.has(o.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):i.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(o=>{ng(i,o.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(o=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return o;const f={...o};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var o;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=u.subRows)!=null&&o.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},o=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:o(h.subRows)}),y)return h}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,o=!1;return e.subRows.forEach(u=>{if(!(o&&!i)&&(u.getCanSelect()&&(Dv(u,t)?o=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?o=!0:(f==="some"&&(o=!0),i=!1)}}),i?"all":o?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),o=r.shift(),u=parseInt(i,10),f=parseInt(o,10),h=[u,f].sort();if(isNaN(h[0])){if(i>o)return 1;if(o>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const o=i?.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return Tl.datetime;if(typeof o=="string"&&(r=!0,o.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=o?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(o||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const o=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const o=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(o,w):{...o,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...o,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,o,u){o===void 0&&(o=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],o=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};o.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(o=>$v.includes(o)))return n;const i=r.reduce((o,u)=>bn(o)?void 0:o[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",St=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),o=i.length,u=o-1;for(;++r{const i={};for(const o in e)Object.defineProperty(i,o,{get:()=>{const u=o;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),Re(n,o))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const o=n.get(e);if(o&&o.has(t))return!0;if(o)o.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const o=Re(e,i);if(o){const{_f:u,...f}=o;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return St(i,DE,t[n]),St(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,o)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(o?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,o=n[i];return r&&delete r[o],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const o of e)o.next&&o.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(o=>o!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],o=t[r];if(i&&Pt(i)&&o){const u=IE(i,o);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=o)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],o=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(o))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],o),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const o=e[i],u=r&&r[i];UE(o)&&(!Array.isArray(o)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(o,Array.isArray(o)?[]:{},u):ai(o,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(o,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const o of e){const u=Re(t,o);u&&St(i,o,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const o=i.join("."),u=Re(t,o),f=Re(e,o);if(u&&!Array.isArray(u)&&n!==o)return{name:n};if(f&&f.type)return{name:o,error:f};if(f&&f.root&&f.root.type)return{name:`${o}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...o}=e,u=Object.keys(o);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?St(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,o,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&St(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&St(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&St(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else St(o,z,Q)},H=(z,Q)=>{St(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=o,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(o,z)),Se=Re(o,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?St(o,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(o,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,o,void 0,r):Ee?Gt(n.dirtyFields,z):St(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(St(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?St(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(o,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):St(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:o,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&ht(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?ht(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,o,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):St(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&<(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&St(o,z,Q),!sr(u.mount?o:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?o:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?o:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&St(o,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?o:Bt(o)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(o,z),rt=sr(Ee,_e);if(rt||St(o,z,_e),Se)E.array.next({name:z,values:fe?o:Bt(o)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?o:Bt(o);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(o):z;if(!sr(o,X)){o={...o,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:o}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(o,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(St(o,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const yt=h[X];yt&&yt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),vt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(o)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),vt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:yt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(yt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(yt)}else A([X],!0),Se=(await v1(me,f.disabled,o,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?o:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;St(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...o};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),lt=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(o,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(o)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},hn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},Nt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return St(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?hn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;St(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},Ct=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),mn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(o);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),Ct(),setTimeout(Ct);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),St(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,o,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(o,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?St(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(o=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)St(o,_e,Re(xe,_e))}else o=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&o?ai(i,o,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(o):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:Nt,unregister:lt,getFieldState:Te,handleSubmit:Ut,setError:ht,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:Ct,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:hn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:mn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return o},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:Nt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,o,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:lt,setError:ht,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,o]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>o({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return o(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,o(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),o=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));St(u,"root",o),St(n,r,u)}else St(n,r,o)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function jt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const o=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,o)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,o)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const o=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(o,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return Ci(this,"shape",o),o}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,o={...i};if(n)for(const u in n){if(!(u in o))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)o[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",o),o}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,o=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...o,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...o,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...o,...u.path]);else{const f=[...o,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const o=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},o);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,o,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const o=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},o);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,o,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new wo;return o.issues.length?{success:!1,error:new(e??Kv)(o.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:o.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:o.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,o=i.length;if(o===t.length)return;const u=Gv(i),f=o>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` +`).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),o=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of o)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,i.join(` +`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},o=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>o(y,u,f)):o(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}jt(e,"~standard",()=>({validate:i=>{try{const o=F8(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,o]=r;if(!o)throw new Error;const u=Number(o);if(`${u}`!==o)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return o.length?Promise.all(o).then(()=>n):n}});function Od(e,t,n,r,i,o){const u=n in r;if(e.issues.length){if(i&&o&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,o){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));jt(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,o=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return o?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` + if (${T}.issues.length) { + if (${A} in input) { + payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${A}, ...iss.path] : [${A}] + }))); + } + } + + if (${T}.value === undefined) { + if (${A} in input) { + newResult[${A}] = undefined; + } + } else { + newResult[${A}] = ${T}.value; + } + + `):L?x.write(` + if (${T}.issues.length) { + payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${A}, ...iss.path] : [${A}] + }))); + } + + if (${T}.value === undefined) { + if (${A} in input) { + newResult[${A}] = undefined; + } + } else { + newResult[${A}] = ${T}.value; + } + + `):x.write(` + const ${T}_present = ${A} in input; + if (${T}.issues.length) { + payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${A}, ...iss.path] : [${A}] + }))); + } + if (!${T}_present && !${T}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${A}] + }); + } + + if (${T}_present) { + if (${T}.value === undefined) { + newResult[${A}] = undefined; + } else { + newResult[${A}] = ${T}.value; + } + } + + `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let o;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(o||(o=i(t.shape)),w=o(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!vo(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),jt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),jt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),jt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),o=!0;else{if(h.issues.length===0)return h;u.push(h)}}return o?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,o=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||u instanceof Promise?Promise.all([o,u]).then(([h,m])=>T1(n,h,m)):T1(n,o,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};for(const o of r){const u=dg(e[o],t[o]);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};i[o]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(o.length&&i&&e.issues.push({...i,keys:o}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(u=>O1(u,i)):O1(o,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.innerType._zod.optin),jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>A1(o,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>D1(o,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>yi(o,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>t.in._zod.values),jt(e._zod,"optin",()=>t.in._zod.optin),jt(e._zod,"optout",()=>t.out._zod.optout),jt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(u=>Qu(u,t.in,r)):Qu(o,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Qu(o,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),jt(e._zod,"propValues",()=>t.innerType._zod.propValues),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"optin",()=>t.innerType?._zod?.optin),jt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(o=>L1(o,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(Wl(o))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},o=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){o(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){o(u);continue}}if(e.metadataRegistry.get(u[0])?.id){o(u);continue}if(f.cycle){o(u);continue}if(f.count>1&&e.reused==="ref"){o(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},u=o2({...i??{},target:o,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:o,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,o=KE(i.entries);o.every(u=>typeof u=="number")&&(n.type="number"),o.every(u=>typeof u=="string")&&(n.type="string"),n.enum=o},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(o.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const u=o.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=o.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=jn(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,o=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,o?"oneOf":"anyOf",h]}));o?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,o=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(o)?o.allOf:[o],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,o=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?o?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:o};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,o,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,o){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return o.shouldUseNativeValidation&&cg({},o),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,o){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return o.shouldUseNativeValidation&&cg({},o),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const o in n){const u=n[o];Object.defineProperty(r,o,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,o)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),jt(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,o)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const o={};for(const u of r)if(n.has(u))o[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:o})},e.exclude=(r,i)=>{const o={...t.entries};for(const u of r)if(n.has(u))delete o[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:o})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(Wl(o,n.value,t));else{const u=o;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return l.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:l.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return l.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return l.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return l.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return l.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return l.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?l.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:l.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):l.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return l.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:l.jsxs(Q9,{className:"admin-table",children:[l.jsx(X9,{children:e.getHeaderGroups().map(n=>l.jsx(K1,{children:n.headers.map(r=>l.jsx(eU,{header:r},r.id))},n.id))}),l.jsx(W9,{children:e.getRowModel().rows.map(n=>l.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>l.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:o=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>l.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>l.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>l.jsxs("span",{className:"share-acts",children:[l.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:l.jsx(ge,{name:"copy"})}),r&&l.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return o?l.jsx("div",{className:"admin-list",children:l.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?l.jsx("div",{className:"admin-list",children:l.jsx("div",{className:"admin-empty",children:i})}):l.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",o=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return l.jsxs("div",{className:"admin",children:[l.jsx("h1",{id:"org-title",children:e.name}),!i&&l.jsx("p",{className:"role-chip-row",children:l.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&l.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&l.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),o()}catch(j){ke(j.message,!0)}}),children:[l.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),l.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),l.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&l.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),l.jsx("h3",{children:"Members"}),l.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:o}),l.jsx("h3",{children:"Projects"}),l.jsxs("div",{className:"admin-list",children:[w.length===0&&l.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>l.jsx("div",{className:"admin-item",children:l.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"admin-h",children:[l.jsx("h3",{children:"Invite links"}),l.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),l.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&l.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>l.jsxs("div",{className:"admin-item",children:[l.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),l.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),l.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),l.jsx("h3",{children:"Public share links"}),l.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),l.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),l.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},o=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"admin-h",children:[l.jsx("h3",{children:"Apps"}),l.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),l.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),l.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&l.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>l.jsxs("div",{children:[l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",title:u.name,children:u.name}),l.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&l.jsxs(l.Fragment,{children:[l.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>o((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),l.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>l.jsxs("div",{className:"admin-item",children:[l.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),l.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),l.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,o]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return l.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?l.jsx("span",{className:"ai-tag role-static",children:y.role}):l.jsxs("span",{className:"role-cell",children:[l.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[l.jsx("option",{value:"owner",children:"owner"}),l.jsx("option",{value:"member",children:"member"})]}),l.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:o,getCoreRowModel:ME(),getSortedRowModel:TE()});return l.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const o=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return l.jsxs("div",{className:"admin",children:[l.jsx("h1",{children:"Signup & access"}),l.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),l.jsx("h3",{children:"New-account vetting"}),l.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[l.jsxs("div",{className:"admin-list",children:[l.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),l.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),l.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),l.jsx("h3",{children:"Who can sign up"}),l.jsxs("div",{className:"admin-list",children:[l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Allowed email domains"}),l.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Self-signup"}),l.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Hub admins"}),l.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),l.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),l.jsx("h3",{children:"Pending signups"}),l.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&l.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),l.jsx(Ie,{variant:"primary",onClick:()=>o(u.id,"approve",u.email),children:"Approve"}),l.jsx("button",{className:"ai-del",onClick:()=>o(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return l.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[l.jsxs("span",{className:"ai-main",children:[l.jsx("div",{className:"tg-label",children:e}),l.jsx("div",{className:"tg-desc",children:t})]}),l.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return l.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return l.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return l.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return l.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return l.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return l.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Connections are unavailable"}),l.jsx("p",{children:n.error.message})]});const o=n.data?.grants??[];return l.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[l.jsx("h2",{children:"Connected agents"}),l.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",l.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),o.length===0?l.jsx(Es,{children:l.jsxs(Ns,{children:[l.jsx(ks,{children:"No agents connected"}),l.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",l.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):o.map(u=>l.jsxs(Es,{className:"mcp-grant",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:u.client_name||"Unnamed client"}),l.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),l.jsxs(Ps,{children:[l.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>l.jsx("span",{className:"ps-chip",children:i(f)},f))}),l.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return l.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return l.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return l.jsx(Rz,{children:l.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return l.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return l.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return l.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[l.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:l.jsx(zz,{children:l.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return l.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return l.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return l.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,o]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=o.human||0,r.agent+=o.agent||0,r.share+=o.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-eo.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let o=r.cx+r.r+4,u="start";o+i.length*NU>t.right&&(o=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:o,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],o=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(o.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:o}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const o=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:o,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==o),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),o=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:o}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const o=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return l.jsxs("nav",{id:"projects","aria-label":"Projects",children:[l.jsx($2,{projects:e,current:o,menu:n,account:r,onNew:i,trigger:l.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${o?.name??"none"}`,title:o?.name,children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:o?mc(o.name):void 0,children:l.jsx(ui,{name:o?.icon})}),l.jsx("span",{className:"proj-name",children:o?o.name:e.length?"Select a project":"No projects yet"}),l.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&l.jsx(F2,{}),n&&l.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>l.jsx("li",{children:l.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[l.jsx(ge,{name:m}),l.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&l.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:o,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return l.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[l.jsx(Wv,{asChild:!0,children:o}),l.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[l.jsx("div",{className:"sb-menu-projects",children:e.map(_=>l.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),ds()},children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:l.jsx(ui,{name:_.icon})}),l.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&l.jsx(ge,{name:"check"})]},_.id))}),l.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[l.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:l.jsx(ge,{name:"plus"})}),l.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&l.jsx(mg,{}),n&&t&&l.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[l.jsx(ge,{name:"gear"}),l.jsx("span",{className:"label",children:"Project settings"})]}),w&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[l.jsx(ge,{name:"building"}),l.jsx("span",{className:"label",children:"Organization settings"}),l.jsx("span",{className:"meta",children:w.name}),E&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[l.jsx(ge,{name:"card"}),l.jsx("span",{className:"label",children:"Billing"}),l.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&l.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[l.jsx(ge,{name:"shield"}),l.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&l.jsx("span",{className:"meta",children:r.admin.pending})]}),l.jsx(mg,{}),r&&l.jsx(dU,{className:"sb-menu-label",children:r.me.email}),l.jsxs("div",{className:"sb-theme",children:[l.jsx("span",{className:"label",children:"Theme"}),l.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>l.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:l.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[l.jsx(ge,{name:"plug"}),l.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?l.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[l.jsx(ge,{name:"power"}),l.jsx("span",{className:"label",children:"Log out"})]}):l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"signout",href:"/auth/logout",children:[l.jsx(ge,{name:"power"}),l.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:o}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),o&&u.push("synced "+ho(o));const f=l.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?l.jsx("span",{className:"sync-dot","aria-hidden":"true"}):l.jsx(ge,{name:"laptop"}),l.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?l.jsx("div",{className:"sb-foot",children:l.jsxs(uf,{delayDuration:300,children:[l.jsx(df,{asChild:!0,children:f}),l.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):l.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return l.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[l.jsx(ge,{name:"search"}),l.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?l.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):l.jsxs(uf,{delayDuration:150,children:[l.jsx(df,{asChild:!0,children:l.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),l.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",l.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return l.jsx(l.Fragment,{children:L2.map(([r,i,o])=>l.jsx(jv,{id:"rail-"+r,icon:o,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return l.jsx($2,{...e,side:"right",trigger:l.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:l.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return l.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:l.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return l.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[l.jsx(HU,{}),l.jsx("span",{children:"Star on GitHub"}),l.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return l.jsxs("footer",{id:"accountbar",children:[l.jsx(qU,{}),l.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[l.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),l.jsxs("span",{className:"acct",children:[l.jsx("b",{children:"Sign in…"}),l.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return l.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return l.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Billing is unavailable"}),l.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return l.jsxs("div",{className:"project-settings",id:"billing-view",children:[l.jsxs("h2",{children:["Billing",l.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),l.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx("div",{className:"usage-bar",children:l.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?l.jsx("div",{className:"plan-grid",children:n.plans.map(r=>l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:r.name}),l.jsx(lr,{children:r.blurb})]}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsxs("p",{className:"plan-price",children:[r.price,l.jsx("small",{children:" / user / month"})]}),l.jsxs("form",{method:"post",action:n.checkout_url,children:[l.jsx("input",{type:"hidden",name:"plan",value:r.id}),l.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):l.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Manage subscription"}),l.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx("form",{method:"post",action:n.portal_url,children:l.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return l.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return l.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),o=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{o.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=o.watch("icon"),f=o.watch("description"),h=o.handleSubmit(async m=>{const y=o.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),o.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return l.jsxs("div",{className:"project-settings",children:[l.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&l.jsx("span",{className:"ps-chip",children:"Read-only"})]}),l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"General"}),l.jsx(lr,{children:"Name, description and icon for this project."})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsxs("form",{className:"ps-form",onSubmit:h,children:[l.jsxs("div",{className:"ps-field",children:[l.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),l.jsxs("div",{className:"ps-icon-row",children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:l.jsx(ui,{name:u})}),l.jsxs(Xv,{children:[l.jsx(Wv,{asChild:!0,children:l.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),l.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[l.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>o.setValue("icon","",{shouldDirty:!0}),children:l.jsx(ui,{})}),Object.keys(Yp).map(m=>l.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>o.setValue("icon",m,{shouldDirty:!0}),children:l.jsx(ui,{name:m})},m))]})]})]})]}),l.jsxs("div",{className:"ps-field",children:[l.jsx(pp,{htmlFor:"ps-name",children:"Name"}),l.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!o.formState.errors.name,"aria-describedby":o.formState.errors.name?"ps-name-err":void 0,...o.register("name")}),o.formState.errors.name&&l.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:o.formState.errors.name.message})]}),l.jsxs("div",{className:"ps-field",children:[l.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",l.jsx("span",{className:"ps-opt",children:"(optional)"})]}),l.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!o.formState.errors.description,"aria-describedby":o.formState.errors.description?"ps-desc-err":void 0,...o.register("description")}),l.jsxs("div",{className:"ps-meta",children:[o.formState.errors.description?l.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:o.formState.errors.description.message}):l.jsx("span",{}),l.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&l.jsxs(l.Fragment,{children:[l.jsx(Fr,{}),l.jsx("div",{className:"ps-actions",children:l.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!o.formState.isDirty||o.formState.isSubmitting,children:"Save changes"})})]})]})})]}),l.jsx(XU,{project:e}),l.jsx(JU,{project:e,org:t}),l.jsxs(Es,{id:"ps-devices",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Devices"}),l.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),l.jsx(Ps,{children:l.jsx(Ie,{asChild:!0,variant:"outline",children:l.jsx("a",{...In(cn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&l.jsx(QU,{project:e,onChanged:r}),l.jsxs(Es,{children:[l.jsx(Ns,{children:l.jsx(ks,{children:"About"})}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsxs("dl",{className:"ps-facts",children:[l.jsx("dt",{children:"Project id"}),l.jsx("dd",{children:l.jsx("code",{children:e.id})}),t&&l.jsxs(l.Fragment,{children:[l.jsx("dt",{children:"Workspace"}),l.jsx("dd",{children:t.name})]}),e.created&&l.jsxs(l.Fragment,{children:[l.jsx("dt",{children:"Created"}),l.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),l.jsxs("p",{className:"ps-note ps-export",children:[l.jsx("strong",{children:"Take your files elsewhere."})," Run ",l.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",l.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",l.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&l.jsxs(Es,{className:"ps-danger",children:[l.jsx(Ns,{children:l.jsx(ks,{children:"Danger zone"})}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),l.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return l.jsxs(Es,{id:"ps-data",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Data"}),l.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),l.jsx(Ps,{children:l.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Public links"}),l.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(o=>o.opens!==void 0)&&l.jsxs(l.Fragment,{children:[" ",v2]})]})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),o=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return l.jsxs(Es,{className:"ps-people",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"People"}),l.jsx(lr,{children:"Who can see and change this project."})]}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[t?.role==="owner"&&l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Not in ",t.name," yet?"]}),l.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),l.jsx("select",{"aria-label":"Default access for workspace members",disabled:!o,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>l.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&l.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),l.jsxs("div",{className:"ps-people-head",children:[l.jsx("h4",{children:"Exceptions"}),o&&l.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?l.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):l.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return l.jsxs("div",{className:"admin-item",children:[l.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&l.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?l.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):l.jsxs("span",{className:"role-cell",children:[l.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!o,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>l.jsx("option",{value:S.value,children:S.label},S.value))}),o&&l.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,o=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} +to set up ${o} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive +bdrive init --server `+n+" --project "+e.id;return l.jsxs("div",{className:"guide",children:[l.jsxs("h1",{className:"in-title gd-head",children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:l.jsx(ui,{name:e.icon})}),e.name]}),e.description&&l.jsx("p",{className:"in-desc",children:e.description}),l.jsxs("div",{className:"gd-body",children:[l.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&l.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),l.jsx(Jl,{code:r}),l.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),l.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),l.jsxs("details",{className:"gd-manual",children:[l.jsx("summary",{children:"What exactly happens"}),l.jsxs("ul",{className:"gd-desc gd-list",children:[l.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),l.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),l.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),l.jsxs("details",{className:"gd-manual",children:[l.jsx("summary",{children:"Or run it yourself"}),l.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),l.jsx(Jl,{code:i}),l.jsx("p",{className:"gd-desc",children:l.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return l.jsxs("pre",{className:"gd-code",children:[l.jsx("code",{children:e}),l.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return l.jsxs("div",{className:"onboard",children:[l.jsx("h1",{children:"Welcome to BearDrive"}),l.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&l.jsxs("div",{className:"ob-card ob-start",children:[l.jsx("h3",{children:"Start a project"}),l.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),l.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),l.jsxs("div",{className:"ob-card ob-agent",children:[l.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),l.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),l.jsx(Jl,{code:kf(window.location.origin)}),l.jsx("p",{className:"ob-alt",children:l.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return l.jsxs("div",{className:"onboard setup-welcome",children:[l.jsx("h1",{children:"Welcome to BearDrive"}),l.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),l.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),l.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return l.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[l.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),l.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",l.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>l.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&l.jsx("div",{className:"setup-dim",children:"├── …"}),l.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",l.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),l.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[o,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:o});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,o,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return l.jsxs("div",{className:"setup-connect",children:[l.jsxs("header",{children:[l.jsxs("h2",{children:["Add a shared folder to your project",!N&&l.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),l.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",l.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&l.jsxs("ul",{className:"setup-why",children:[l.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),l.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),l.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),l.jsxs("div",{className:"setup-body",children:[l.jsxs("div",{className:"setup-form",children:[l.jsxs("label",{className:"setup-field",children:[l.jsx("span",{children:"Your project folder"}),l.jsxs("div",{className:"setup-root",children:[l.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),l.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),l.jsxs("label",{className:"setup-field",children:[l.jsx("span",{children:"Shared folder name"}),l.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),l.jsxs("label",{className:"setup-toggle",children:[l.jsx("input",{type:"checkbox",id:"setup-hooks",checked:o,onChange:T=>u(T.target.checked)}),l.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&l.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&l.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&l.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&l.jsxs("div",{className:"setup-warn",children:[l.jsx("p",{children:f.warning}),f.helper&&l.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",l.jsx("code",{children:f.helper})," ",l.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),l.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),l.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",l.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),l.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const o=["creating","connecting","syncing","done"],u=Math.max(0,o.indexOf(n.phase));return l.jsxs("div",{className:"setup-syncing",children:[l.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),l.jsx("div",{className:"setup-bar",children:l.jsx("div",{style:{width:`${(u+1)/o.length*100}%`}})}),l.jsxs("ul",{className:"setup-log",children:[l.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),l.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),l.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?l.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):l.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[o,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return l.jsxs("div",{className:"setup-done",children:[l.jsxs("h2",{children:[f,"/ is live"]}),l.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&l.jsx("p",{className:"setup-err",children:e.error}),l.jsxs("div",{className:"setup-cards",children:[l.jsxs("div",{className:"setup-card",children:[l.jsx("h3",{children:"Open the dashboard"}),l.jsx("p",{children:"Browse files, history, and who reads what."}),l.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),l.jsxs("div",{className:"setup-card setup-card-lead",children:[l.jsx("h3",{children:"Tell your agent"}),l.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),l.jsx(Jl,{code:h}),l.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),l.jsxs("div",{className:"setup-card",children:[l.jsx("h3",{children:"Invite teammates"}),l.jsx("p",{children:"A link that signs them up straight into this project."}),l.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),o&&l.jsx("p",{className:"setup-err",id:"setup-invite-err",children:o})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),l.jsxs("div",{className:"setup",children:[e==="welcome"&&l.jsx(nV,{onStart:n}),e==="connect"&&l.jsx(rV,{onStarted:o=>gt("/setup/syncing?name="+encodeURIComponent(o))}),e==="syncing"&&l.jsx(aV,{onDone:o=>{i(o),gt("/setup/done")}}),e==="done"&&l.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,o]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return l.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:l.jsxs(cc,{className:"modal",showCloseButton:!1,children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:"New project"})}),l.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),l.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{o(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&l.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&l.jsxs("fieldset",{className:"start-points",children:[l.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>l.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[l.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),l.jsxs("span",{className:"sp-text",children:[l.jsxs("span",{className:"sp-title",children:[x.title,j===0&&l.jsx("span",{className:"sp-rec",children:"Recommended"})]}),l.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),l.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,o)=>i<3&&dV(o),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:o,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||o?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const o=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},o))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},o))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),o=b.useRef(t);return o.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:o.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:o.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const o=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` +`).filter(f=>f.trim()).join(` +`),t.push(i),i=null)};for(const u of e.split(` +`)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(o(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return o(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(` +`).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=cy(e),n=[];let r=0;return e.split(` +`).forEach((i,o)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:o+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` +`)}function BB(e){return e.split(` +`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),o=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||o==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(o))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;no.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,o])=>i>=r.headingEnd&&o<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return l.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,o=n.length-r.length;return l.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>l.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),o>0&&l.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",o]}),i>0&&l.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,o,u){if(typeof o=="string"){const f=o.charCodeAt(0);if(f>=48&&f<=57){const h=+o;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(i),o=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let o=0;o{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const o=e.options.useScrollendEvent&&MV;let u=0;const f=o?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),o&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),o&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),o=n.itemSizeCache.get(i);if(o!==void 0)return o}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,o;(o=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||o.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(o=>{const u=()=>{const f=o.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var o;return(o=r())==null?void 0:o.observe(i,{box:"border-box"})},unobserve:i=>{var o;return(o=r())==null?void 0:o.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(o[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=o.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(o.getItemKey(0)!==S||o.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=o.followOnAppend===!0?"auto":o.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||o.getItemKey(x-1)!==E)&&(h=T)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,u)=>{if(u&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===o?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",u,Id),o.addEventListener("touchend",f,Id),this.unsubs.push(()=>{o.removeEventListener("touchstart",u),o.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[o,u,f,h]=i;o!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,o,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,o)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,o,u)=>o===null||u===null?[]:n({startIndex:o,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-o),f=Math.min(this.options.count-1,i+o);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),o=this.elementsCache.get(i);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,o;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let o=0,u=n.length;othis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,o=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,o?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+o?"end":"start"),r==="center"?n+=(i-o)/2:r==="end"&&(n-=o);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),o=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=o+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[u,f]=o,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,u=this._flatMeasurements;u!=null?i=u[o*2]+u[o*2+1]:i=((n=r[o])==null?void 0:n.end)??0}else{const o=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&o.some(f=>f===null);){const f=r[u];o[f.lane]===null&&(o[f.lane]=f.end),u--}i=Math.max(...o.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,o=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,o=n(i);if(or)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,o=e[i*2];if(on)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&i!==null){const m=$V(i,o,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(o,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],o=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const u=m=>{const y=o.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=o.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=o.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return l.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return l.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return l.jsx(rz,{children:l.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return l.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return l.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return l.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,o,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+o,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+o||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",o=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-o.length))+o}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const o=e.toLowerCase();if(o.length===e.length)return{text:o,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let o=0;o65535?2:1);for(;u65535?2:1}const f=e.slice(o,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:o}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:o},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+o-1]}function aH(e,t,n,r){const i=e.length,o=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*o),m=new Float64Array(i*o);for(let w=0;w0&&(N=Math.max(m[_-o-1]+Pl[f[n+E]],h[_-o-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=o-1;w>=0;w--)for(;x>=0;x--){const j=w*o+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-o-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*o-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const o=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let o=n;for(let u=0;u=o)return!0;if(o=t.indexOf(e[u],o)+1,o===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,o=-1;for(let u=0;ui&&(i=f,o=u)}return o<0?-1/0:(r&&_g(e.drops[o].text,e.drops[o].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,o=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!o){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),o=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!o?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const o=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return o!==u?o0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,o=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],o):n.push([i,o])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const o={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:o,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,o=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{o.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;o.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:o=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>o===w||o.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),o=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:o.list,folderCount:i.total,fileCount:o.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const o=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&o.push(e.slice(u,m)),o.push(l.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[l.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",l.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&l.jsxs(i,{onSelect:()=>n.newFile(f),children:[l.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&l.jsxs(i,{onSelect:()=>n.togglePin(e),children:[l.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),l.jsx(o,{}),l.jsxs(i,{onSelect:()=>n.copyPath(e),children:[l.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&l.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[l.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&l.jsx(o,{}),n.history&&l.jsxs(i,{onSelect:()=>n.history(e),children:[l.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&l.jsxs(i,{onSelect:()=>n.insights(e),children:[l.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&l.jsxs(l.Fragment,{children:[l.jsx(o,{}),l.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[l.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:o,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>l.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return l.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:l.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return l.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return l.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsx("span",{className:"chev",children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"system"})}),l.jsx("span",{className:"label",children:"System files"}),l.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&o){r(W.path);return}m.open(W.path),W.dir||ds()};return l.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[l.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[l.jsx(VV,{asChild:!0,children:l.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),l.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),l.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&l.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&l.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&l.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:l.jsx(ge,{name:"lock"})}),l.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&l.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:l.jsx(ge,{name:"plus"})}),l.jsx(Wv,{asChild:!0,children:l.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:l.jsx(ge,{name:"dots"})})})]})]})}),l.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),l.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,o]=b.useState(!1);b.useEffect(()=>o(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>l.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:E.dir?"folder":"doc"})}),l.jsxs("span",{className:"fhit-text",children:[l.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),l.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&l.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return l.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&l.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&l.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&l.jsxs("button",{className:"fmore",onClick:()=>o(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&l.jsx("div",{className:"fempty",children:"No file or folder names match"}),l.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"search"})}),l.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),l.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:o,onUnpin:u}=e;return t.length?l.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[l.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return l.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&o(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),o(f))},children:[l.jsx(ge,{name:"star"}),l.jsx("span",{className:"label",children:h}),m>0&&l.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&l.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),l.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:l.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-sep"}),t.map(i=>{const o=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return l.jsx(jv,{icon:"doc",label:o,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return l.jsx("span",{className:"crumbs",title:e,children:n.map((i,o)=>{r=r?r+"/"+i:i;const u=r,f=o===n.length-1,h=o>0&&!f;return l.jsxs("span",{className:"crumb",children:[o>0&&l.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?l.jsx("span",{className:"crumb-last",children:i}):l.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,o=e?.until?Ng(e.until):null;return i&&(r.since=i),o&&(r.until=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const o of["q","user","actor","device"])e?.[o]&&n.set(o,e[o]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` +`);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:o[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=o[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,o=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return l.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[l.jsxs("div",{className:"fv-chips",children:[n&&l.jsxs("span",{className:"fv-chip accent",children:[l.jsx(ge,{name:"shield"})," ",n]}),r&&l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),l.jsxs("div",{className:"fv-meta",children:[o&&l.jsxs("span",{className:"meta-stale",title:o,children:[l.jsx("span",{"aria-hidden":"true",children:"⚠ "}),o]}),f&&l.jsxs("span",{className:"fv-who",title:f,children:[l.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&l.jsxs("span",{children:[l.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&l.jsxs("span",{className:"fv-when",children:[l.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&l.jsxs("span",{className:"fv-reads",title:Ur,children:[l.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,o=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(o),y=r?Vs(r):0;if(!o.length&&!n?.length&&!y)return null;const g=l.jsxs(l.Fragment,{children:[o.length>0&&l.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[l.jsx("p",{className:"fv-sec-h",children:"On this page"}),l.jsx("ul",{children:o.map(w=>l.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:l.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&l.jsx(PH,{heat:r,insightsHref:i}),n?.length?l.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[l.jsx("p",{className:"fv-sec-h",children:"Properties"}),l.jsx("dl",{children:n.map(w=>l.jsxs("div",{children:[l.jsx("dt",{children:w.key}),l.jsx("dd",{children:w.code?l.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?l.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:l.jsx("div",{className:"fv-rail-in",children:g})}):l.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[l.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),l.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return l.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[l.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&l.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),l.jsxs("div",{className:"fv-big",title:Ur,children:[n,l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),l.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>l.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),l.jsx("div",{className:"fv-legend",children:r.map(i=>l.jsxs("span",{children:[l.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&l.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const o=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(o))};return o(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],o="",u=!1,f=0;const h=()=>{i.push(o),o="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,o=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=l.jsxs(l.Fragment,{children:[i&&m.length>0&&l.jsx(ZH,{...e,secs:m}),l.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[l.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&l.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?l.jsxs("p",{className:"er-empty",children:["None yet. Type ",l.jsx("kbd",{children:"/"})," and pick Action item, or write ",l.jsx("code",{children:"- [ ] … @owner"}),"."]}):l.jsx("ul",{className:"er-list",children:h.map(g=>l.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[l.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),l.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",l.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&l.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return o?l.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:l.jsx("div",{className:"fv-rail-in",children:y})}):l.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[l.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),l.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return l.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[l.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),l.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:l.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),l.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),o=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return l.jsxs("li",{children:[l.jsx(G2,{name:r.name}),l.jsx("span",{className:"er-name",children:r.name}),l.jsx("span",{className:"er-state "+(o?"typing":r.body?"done":"none"),children:i&&u?"You · editing":o?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[o,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return l.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[l.jsx("h4",{children:"Recent versions"}),l.jsxs("ul",{className:"er-vlist",children:[l.jsxs("li",{className:"now",children:[l.jsx("i",{className:"er-dot live","aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",children:"Now"}),l.jsx("span",{className:"er-vwho",children:"Live"}),l.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return l.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[l.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),l.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),l.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&l.jsx("button",{type:"button",className:"er-restore",disabled:!!o,title:"Restore this version as a new version",onClick:()=>{y(g)},children:o===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),l.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CUvVSG63.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CwChUaNM.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,o]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&o(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{o(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,o=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?l.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?l.jsx(s7,{...e}):oi.test(n)?l.jsx(a7,{...e}):Lr.test(n)?l.jsx(WH,{...e,fileURL:o}):id.test(n)?l.jsx("iframe",{className:"pdfview",src:o,title:n,onLoad:e.onRendered}):P_.test(n)?l.jsx(o7,{src:o,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?l.jsx(vS,{...e,fileURL:o,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?l.jsx(vS,{...e,fileURL:o}):l.jsx(JH,{...e,fileURL:o})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,o=V2(t,n,e.fileURL,r),u=o.url,f=b.useRef(o.fresh);f.current=o.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?l.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:o}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&o?.()},[u,o]),f?l.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?l.jsx("pre",{className:"plain",children:u.text},n):l.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"name",children:n.split("/").pop()}),l.jsx("p",{children:e.children}),l.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:o}=e;b.useEffect(()=>o?.(),[o]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:l.jsx(ge,{name:"link"})}),l.jsx("div",{className:"name",children:t.split("/").pop()}),l.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),l.jsxs("p",{children:["Target:"," ",f?l.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:l.jsx("code",{children:n})}):l.jsx("code",{children:n}),!f&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),l.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,o=Eo(t,n),u=V2(t,n,o).url,f=ly(o,["text",o],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[o]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(o)}),()=>{Fe=!1}},[w,o]);const x=y===o?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(o),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",o]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",o]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,o]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(l.jsxs(l.Fragment,{children:[l.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[l.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&l.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>l.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&l.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?l.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?l.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):l.jsxs(l.Fragment,{children:[h&&l.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&l.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&l.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[l.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&l.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>l.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[l.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&l.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?l.jsxs("div",{className:"empty",children:["Could not load the editor."," ",l.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?l.jsx("div",{className:"empty",children:"Loading editor…"}):l.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?l.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:l.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):l.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&l.jsx(r7,{...e}),!i&&l.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[l.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),l.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[l.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&l.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?l.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):l.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:o}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?l.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,o)}):l.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:o,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return l.jsx(Tf,{version:i,err:g});if(!y)return l.jsx(uN,{});const _=i?null:o&&o[y.path]||null,N=l.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return l.jsxs(l.Fragment,{children:[l.jsx(i7,{findings:y.findings}),!t&&N,l.jsx(FH,{doc:y,heat:_}),l.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return l.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[l.jsxs("div",{className:"fskel-main",children:[l.jsx("span",{className:"fskel-title"}),l.jsxs("span",{className:"fskel-meta",children:[l.jsx("span",{style:{width:120}}),l.jsx("span",{style:{width:90}}),l.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>l.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),l.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[l.jsx("span",{style:{width:"40%"}}),l.jsx("span",{style:{width:"80%"}}),l.jsx("span",{style:{width:"65%"}}),l.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?l.jsxs("div",{className:"sbadge",role:"status",children:[l.jsx("span",{className:"sb-icon",children:l.jsx(ge,{name:"shield"})}),l.jsxs("div",{className:"sb-text",children:[l.jsx("b",{children:GH(e)}),l.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(o,decodeURIComponent(i))))}function py(e,t,n,r,i){const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(o,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?l.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):l.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return l.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:o}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&o?.()},[u,o]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?l.jsx(Tf,{version:n,err:f}):u==null?null:h?l.jsx(l7,{csv:h},t):l.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((o,u)=>Math.max(o,u.length),0),i=Array.from({length:r},(o,u)=>u);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"csvbox",children:l.jsxs("table",{className:"csvview",children:[l.jsx("thead",{children:l.jsx("tr",{children:i.map(o=>l.jsx("th",{children:t[o]??""},o))})}),l.jsx("tbody",{children:n.map((o,u)=>l.jsx("tr",{children:i.map(f=>l.jsx("td",{children:o[f]??""},f))},u))})]})}),e.truncated>0&&l.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return l.jsxs("span",{className:"dv-dl",children:[l.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),l.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),o=tc(e,r,!0),u=i.data?.kind==="text"&&o.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&o.data?.kind==="text"?kg(i.data.text,o.data.text):null,[i.data,o.data]);if(i.error||o.error)return l.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!o.data)return l.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||o.data.kind==="too-large";return l.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",l.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return l.jsxs("div",{className:"dv",children:[l.jsxs("div",{className:"dv-head",children:[l.jsxs("span",{className:"dv-stat",children:[l.jsxs("span",{className:"dv-add",children:["+",m]})," ",l.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&l.jsx("span",{className:"dv-same",children:"No line changes"})]}),l.jsx("div",{className:"dv-body",children:h.map((g,w)=>l.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[l.jsx("span",{className:"dv-n",children:g.an??""}),l.jsx("span",{className:"dv-n",children:g.bn??""}),l.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),l.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),o=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||o.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,o.data.text):kg("",o.data.text),[i.data,o.data,t])}function d7({add:e,del:t}){return l.jsxs("span",{className:"hstat",children:[e>0&&l.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&l.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:o,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return l.jsxs("div",{className:"dtabs",children:[l.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>l.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),l.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?l.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):l.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&l.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:o,projectId:u,onOpenFile:f}),h==="full"&&y&&l.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:o}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?l.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?l.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?l.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,o)}):l.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):l.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?l.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?l.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):l.jsx("div",{className:"dv",children:l.jsx("div",{className:"dv-body",children:n.data.text.split(` +`).map((r,i)=>l.jsxs("div",{className:"dv-line dv-ctx",children:[l.jsx("span",{className:"dv-n",children:i+1}),l.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):l.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return l.jsx(l.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?l.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:o,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!o&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!o?.busy&&o.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return l.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[l.jsxs("div",{className:"hline",children:[l.jsx("span",{className:"hkind",children:g7[N]||N}),m&&l.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),l.jsx("span",{className:"hpath",children:e.path}),q&&l.jsx(d7,{add:q.add,del:q.del}),l.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),l.jsxs("div",{className:"hmeta",children:[l.jsx("span",{className:"hwho",title:R,children:yv(e)}),l.jsx("span",{className:"hdev",children:T}),l.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&l.jsx("span",{className:"hgone",children:"can be restored"}),V&&l.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&l.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&l.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&l.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),o.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&l.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:l.jsx(fN,{text:e.note})}),(M||Y)&&l.jsxs("div",{className:"hactions",children:[M&&(r.prev?l.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):l.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"clock"}),"Open this version"]}),l.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[l.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,o=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=o.filter(g=>g.dir).length,f=o.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||o.some(g=>hd(n,g.path,!!g.dir));return l.jsxs("div",{className:"dirlist",children:[l.jsxs("h1",{className:"dl-title",children:[l.jsx("span",{className:"dl-title-icon",children:l.jsx(ge,{name:"folder"})}),l.jsx("span",{children:t.name})]}),l.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&l.jsx("p",{className:"dl-heatnote",children:Ur}),o.length===0?l.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):l.jsx("div",{className:"dl-items",children:o.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return l.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:g.dir?"folder":"doc"})}),l.jsx("span",{className:"dl-name",children:g.name}),S&&l.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&l.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&l.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&l.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),l.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&l.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:l.jsxs("div",{className:"dl-history",children:[l.jsx("h3",{className:"dl-h3",children:"Recent changes"}),l.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>l.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),l.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:o,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return l.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:l.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:B})}),l.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Everyone in ",g," can"]}),l.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&l.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&l.jsxs("p",{className:"ps-note",children:["A folder set to ",l.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",l.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&l.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&l.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),l.jsx("span",{className:"ai-main",title:P.email,children:P.email}),l.jsx("span",{className:"role-cell",children:l.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>l.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&l.jsxs("div",{className:"admin-item sd-add",children:[l.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),l.jsxs("span",{className:"role-cell",children:[l.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"ps-row",children:_?l.jsxs("span",{children:["Access comes from the rule on ",l.jsx("b",{children:_.prefix})," — you can"," ",l.jsx("b",{children:_.me})," here."]}):l.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&l.jsxs(l.Fragment,{children:[" — the project default is ",l.jsx("b",{children:m.default})]}),"."]})}),_&&l.jsx("p",{className:"ps-row",children:l.jsxs(Ie,{variant:"subtle",onClick:()=>o(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),l.jsx("h4",{className:"sd-head",children:"Public link"}),n?l.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsx("span",{children:l.jsx(ge,{name:T?"globe":"lock"})}),l.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[l.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),l.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sd-warn",children:l.jsx("b",{children:"This file may contain credentials"})}),l.jsx("p",{className:"ps-note",children:BH(W)}),l.jsxs("p",{className:"ps-row",children:[l.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),l.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"modal-url",children:T.url}),l.jsxs("div",{className:"modal-expiry",children:[l.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),l.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:l.jsxs("div",{className:"share-banner",role:"status",children:[l.jsxs("div",{className:"sb-head",children:[l.jsx(ge,{name:"share"}),l.jsx("b",{children:"Publicly shared"}),l.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),l.jsxs("p",{className:"sb-note",children:[l.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&l.jsxs(l.Fragment,{children:[" ",v2]})]}),e.map(r=>l.jsxs("div",{className:"sb-link",children:[l.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),l.jsx("span",{className:"sb-meta",children:g2(r,!1)}),l.jsxs("span",{className:"sb-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&l.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,o)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==o);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,o,u,f)=>{const h=await Sn(e+"comments",{path:i,body:o,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,o,u="")=>{const f=await Sn(e+"comments/"+i,{action:o,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;mo&&(i=u,o=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),o=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return o<0?null:[i[o],i[o+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const o=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=o.nextNode();u;u=o.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[o]=0)return e.starts[r]+n;const o=t.ownerDocument.createRange();o.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),o=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=o)return null;const f=(n||i.all.slice(o,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,o,u)};return r&&(h.line=i.all.slice(0,o).split(` +`).length),h}function N7(e,t,n,r){const i=e;let o=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([o,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([o,u]=[f.startContainer,f.startOffset])}if(!o)return null;for(const[f,h]of r)try{if(h.isPointInRange(o,u)&&!(h.endContainer===o&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:o,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(o),[o]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return l.jsxs(l.Fragment,{children:[e.children,l.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>l.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[l.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&l.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[l.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&l.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[l.jsx(vN,{a:j.anchor}),l.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),l.jsxs("div",{className:"cm-row",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),l.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:o,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),o(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return l.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[l.jsxs("header",{className:"cm-head",children:[l.jsx("b",{children:"Comments"}),l.jsxs("div",{className:"cm-tabs",role:"tablist",children:[l.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&l.jsxs("span",{children:[" · ",j.length]})]}),l.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&l.jsxs("span",{children:[" · ",S.length]})]})]}),l.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:l.jsx(ge,{name:"x"})})]}),f&&l.jsx("div",{className:"cm-pickbar",children:l.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[l.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),l.jsxs("div",{className:"cm-list",children:[R.length===0&&l.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>l.jsx(M7,{t:U,active:U.id===i,onFocus:()=>o(U.id===i?null:U.id),onJump:()=>{o(null),requestAnimationFrame(()=>o(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),l.jsxs("footer",{className:"cm-foot",children:[l.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),l.jsxs("div",{className:"cm-row",children:[l.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",l.jsx("code",{children:"bdrive comments"})]}),l.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:o,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await o.act(t.id,S,h),m("")});return l.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[l.jsxs("div",{className:"cm-card-top",onClick:r,children:[l.jsx("span",{className:"cm-n",children:t.n}),l.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&l.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>l.jsxs("div",{className:"cm-msg",children:[l.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),l.jsxs("div",{className:"cm-msg-main",children:[l.jsxs("div",{className:"cm-who",children:[l.jsx("b",{children:S.name||S.author||"someone"})," ",l.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),l.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&l.jsxs("div",{className:"cm-queued",children:[l.jsx(ge,{name:"sparkle"}),l.jsxs("span",{children:["Queued for next agent sweep · ",l.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&l.jsxs("div",{className:"cm-resolved",children:[l.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),l.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),l.jsxs("div",{className:"cm-row",children:[u&&l.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await o.remove(t.id)})},children:l.jsx(ge,{name:"trash"})}),l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&l.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[l.jsx(ge,{name:"jump"})," Jump to text"]}),l.jsx("span",{className:"cm-spacer"}),h.trim()&&l.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?l.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):l.jsxs("div",{className:"cm-anchor",children:[e.quote&&l.jsxs("div",{className:"cm-quote",children:[e.prefix&&l.jsx("span",{className:"cm-ctx",children:e.prefix}),l.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&l.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&l.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,o,u){if(o===t.length)return i===e.length?_S:$7;var f=`${i},${o}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(o),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,o+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(o)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),o=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=o.current.get(D))==null?void 0:I.value)&&(o.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{o.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{o.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=o.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=o.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),o=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,o,[e.value,e.children,o],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=o.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(o,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...o}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...o,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),o=ka(u=>!u.search);return!n&&!o?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,o=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||o.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,o=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&o.current){let m=u.current,y=o.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(o,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:o,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:o},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...o}=e;return b.createElement(ot.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),o=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());o.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return l.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[l.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),l.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return l.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return l.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return l.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"picon",children:l.jsx(ge,{name:e.icon})}),l.jsxs("span",{className:"ptext",children:[l.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&l.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&l.jsx("span",{className:"ploc",children:n})]}),!r&&l.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[o,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=o.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(o,m,{limit:oq}).hits,[o,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return l.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:l.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[l.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),l.jsxs(sq,{shouldFilter:!1,loop:!0,children:[l.jsxs("div",{id:"palette-inputwrap",children:[l.jsx(ge,{name:"search"}),l.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:o,onValueChange:u})]}),l.jsx(aq,{children:h?y.length===0?l.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return l.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:l.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>l.jsx(iq,{heading:x,children:j.map(S=>l.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:l.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),l.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=o=>(o.session?"s\0"+o.session:"n\0"+o.note)+"\0"+(o.device?.id??""),n=new Map;e.forEach((o,u)=>{if(!o.note&&!o.session)return;const f=n.get(t(o));if(f){f.entries.push(o),f.idx.push(u);return}n.set(t(o),{note:o.note??"",session:o.session,entries:[o],idx:[u]})});const r=[],i=new Set;return e.forEach((o,u)=>{const f=o.note||o.session?n.get(t(o)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const o of e)r++,n.add(o.path),xi(o)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=o=>o.seq?(o.device?.id??"")+"\0"+o.seq:o.time+"\0"+o.path+"\0"+o.kind+"\0"+(o.device?.id??""),r=new Set,i=[];for(const o of[...e,...t]){const u=n(o);r.has(u)||(r.add(u),i.push(o))}return i.sort((o,u)=>Date.parse(u.time)-Date.parse(o.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let o=n.get(i);o||(o={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,o)),!o.agent&&xi(r)&&(o.agent=Mf(r.note)),t&&r.user===t&&(o.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const o of e){const u=t[o.path],f=ay(o.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:o.path,reads:h,days:f})}return i.sort((o,u)=>u.reads-o.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=o=>{let u=o.dir?0:Date.parse(o.time||"")||0;for(const f of o.children||[])u=Math.max(u,r(f));return u},i=[];for(const o of e.children||[]){if(!o.dir)continue;const u=hd(t,o.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(o);i.push({name:o.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((o,u)=>u.reads-o.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,o=t.id,u=Eq(o),f=sy(o),h=RN(o),[m,y]=b.useState(""),g=T2(o),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return l.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return l.jsx("div",{className:"home home-empty",children:l.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,o),H=cn("history",o,"",m?{actor:m}:void 0);return l.jsxs("div",{className:"home",children:[l.jsxs("header",{className:"home-head",children:[l.jsx("h1",{className:"home-greet",children:gq(i?.name)}),l.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&l.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[l.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),l.jsx("div",{className:"home-cards",children:R.map(U=>l.jsxs("a",{className:"home-card",...In(L(U.path)),children:[l.jsxs("span",{className:"hc-name",children:[l.jsx(ge,{name:"doc"}),Vd(U.path)]}),l.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),l.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),l.jsxs("div",{className:"home-grid",children:[l.jsxs("div",{className:"home-main",children:[l.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[l.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&l.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?l.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):l.jsx("ul",{className:"home-list",children:T.map(U=>l.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),l.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Recent activity"}),l.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>l.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?l.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?l.jsx("p",{className:"home-none",children:"No changes yet."}):l.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return l.jsxs("li",{className:"home-fe",children:[l.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:l.jsx(ge,{name:Y?"sparkle":"users"})}),l.jsxs("div",{className:"fe-body",children:[l.jsxs("div",{children:[l.jsx("b",{className:"fe-who",children:ae})," ",l.jsx("span",{className:"fe-what",children:le})]}),W?l.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?l.jsx("span",{className:"fe-path del",children:Z.path}):l.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&l.jsx("span",{className:"fe-dev",children:Z.device.name})]}),l.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):l.jsx("p",{className:"home-none",children:"Loading…"})]})]}),l.jsxs("aside",{className:"home-side",children:[l.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[l.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?l.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):l.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&l.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),l.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[l.jsxs("h2",{className:"home-h",children:[l.jsx(ge,{name:"terminal"}),"Connect another device"]}),l.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),l.jsx(Jl,{code:kf(window.location.origin,{project:t})}),l.jsx("a",{className:"home-more",...In(cn("install",o)),children:"Full setup guide →"})]}),A.length>0&&l.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Where reads go"}),l.jsx("a",{className:"home-more",...In(cn("dashboard",o)),children:"Insights →"})]}),l.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>l.jsxs("li",{className:"fresh-"+U.fresh,children:[l.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[l.jsx("span",{children:U.name}),l.jsx("span",{className:"hb-n",children:U.reads})]}),l.jsx("span",{className:"hb-track",children:l.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),l.jsxs("div",{className:"home-legend",children:[l.jsx("span",{className:"fresh-fresh",children:"fresh"}),l.jsx("span",{className:"fresh-aging",children:"aging"}),l.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&l.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:l.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,o,u;return e.kind==="conflict"?(n="alert",u="conflict",r=l.jsxs(l.Fragment,{children:["Sync conflict on ",l.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,o="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=l.jsxs(l.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",l.jsx("b",{children:Vd(e.path)})]}),i=e.path,o="Reply"):(n="clock",u="stale",r=l.jsxs(l.Fragment,{children:[l.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,o="Review"),l.jsxs("li",{className:"home-attn-row "+u,children:[l.jsx("span",{className:"ha-icon","aria-hidden":"true",children:l.jsx(ge,{name:n})}),l.jsxs("div",{className:"ha-text",children:[l.jsx("span",{className:"ha-title",children:r}),l.jsx("span",{className:"ha-sub",children:i})]}),l.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:o})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?l.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?l.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` +`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,o]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return l.jsxs("div",{className:"insights",children:[l.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsxs("div",{className:"dl-empty in-blank",children:[l.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),l.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&l.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?l.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return l.jsxs("div",{className:"insights",children:[l.jsxs("div",{className:"in-top",children:[l.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>l.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&l.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),l.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),l.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),l.jsx(Pq,{pts:S,th:i,setTh:o,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),l.jsxs("div",{className:"in-split",children:[l.jsxs("section",{className:"in-sec in-sec-map",children:[l.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),l.jsxs("section",{className:"in-sec in-sec-hot",children:[l.jsx("h2",{className:"in-h2",children:"Hot path"}),l.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),l.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),l.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&l.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return l.jsxs("section",{className:"in-sec","data-sec":e.id,children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&l.jsx("p",{className:"in-sub",children:e.sub})]}),l.jsxs("div",{className:"in-sec-tools",children:[e.aside,l.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?l.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],o=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:o("human"),agent:o("agent"),share:o("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return l.jsxs("div",{className:"in-kpis",children:[l.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[l.jsx("div",{className:"in-kpi-l",children:"Reads"}),l.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),l.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?l.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),l.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>l.jsxs("span",{"data-kind":x,children:[l.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[l.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),l.jsxs("div",{className:"in-kpi-v",children:[m,"% ",l.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),l.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:l.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[l.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),l.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&l.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),l.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[l.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),l.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&l.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),l.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const o=Math.round(Number(r));return Number.isFinite(o)&&o>=1?o:i};return l.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[l.jsxs("label",{children:["Stale after"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),l.jsx("span",{"aria-hidden":!0,children:"·"}),l.jsxs("label",{children:["hot ≥"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return l.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?l.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,o)=>Number(o.empty)-Number(i.empty)||o.reads*Math.max(1,o.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return l.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:"Fix these first"}),l.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),l.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?l.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):l.jsxs("table",{className:"in-fix-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads · 30d"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Why it's here"}),l.jsx("th",{children:l.jsx("span",{className:"sr-only",children:"Action"})})]})}),l.jsx("tbody",{children:n.map(i=>{const o=i.path.lastIndexOf("/");return l.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[l.jsxs("td",{className:"in-fx-file",children:[l.jsx(AN,{p:i}),l.jsxs("span",{className:"in-fx-name",children:[l.jsx("span",{children:i.path.slice(o+1)}),o>0&&l.jsx("small",{children:i.path.slice(0,o+1)})]})]}),l.jsxs("td",{className:"in-fx-reads",children:[l.jsx("span",{className:"in-fx-track",children:l.jsx(Fq,{p:i,max:r,lens:e.lens})}),l.jsx("span",{className:"in-fx-n",children:i.reads})]}),l.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),l.jsx("td",{className:"in-fx-why",children:Lq(i)}),l.jsx("td",{className:"in-fx-act",children:i.empty?l.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):l.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&l.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const o=e.reduce((m,y)=>m+y.value,0);if(!o||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/o*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),o=n.get(i);o?o.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const o=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:o.reduce((u,f)=>u+f.reads,0),days:qq((o.length?o:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,o)=>i+o[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=o===null?e:e.filter(_=>DN(_.path,f)===o),w=o===null?Bq(e,f):Gq(g,o||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=l.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[l.jsx("button",{className:o===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),o!==null&&l.jsxs(l.Fragment,{children:[l.jsx("span",{"aria-hidden":!0,children:"›"}),l.jsx("span",{className:"cur",children:o||"(root)"}),o&&i(o)&&l.jsx("button",{className:"in-tm-open",onClick:()=>r(o),children:"Open folder"})]}),o===null&&l.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:o===null?"Folder":"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Files"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Flag"})]})}),l.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>l.jsxs("tr",{children:[l.jsx("td",{children:_.label}),l.jsx("td",{children:_.reads}),l.jsx("td",{children:_.files.length}),l.jsx("td",{children:vc(_.days)}),l.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return l.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,l.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":o===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return l.jsxs("g",{children:[l.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:l.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&l.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&l.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),l.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return l.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",l.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((o,u)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",o]},o))}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),l.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const o=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return o.some(u=>u.top.length)?l.jsx(l.Fragment,{children:o.map(({k:u,total:f,top:h})=>l.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):l.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsxs("th",{children:[Dg[t]," reads"]}),l.jsx("th",{children:"Last change"})]})}),l.jsx("tbody",{children:n.map(o=>l.jsxs("tr",{children:[l.jsx("td",{children:o.path}),l.jsx("td",{children:o[t]}),l.jsx("td",{children:o.orphan?"deleted":vc(o.days)})]},o.path))})]});return l.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:l.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:l.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[l.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&l.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(o=>{const u=()=>o.orphan?e.onOpenHistory(o.path):e.onOpenFile(o.path),f={danger:o[t]>=e.th.hot&&o.danger,empty:o.empty};return l.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(o),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[l.jsxs("span",{className:"in-hp-line",children:[l.jsxs("span",{className:"in-hp-name"+(o.danger||o.empty?" danger":""),children:[l.jsx(AN,{p:{danger:o.danger||f.danger,empty:o.empty}}),o.path]}),o.orphan&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),l.jsx("span",{className:"in-hp-count",children:o[t]})]}),l.jsx("span",{className:"in-hp-bar",children:l.jsx("span",{className:"in-hp-"+t,style:{width:(o[t]/r*100).toFixed(1)+"%"}})})]},o.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const o={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>o.l+m+N/f*(960-o.l-o.r-2*m),g=N=>340-o.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-o.t-o.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-o.r,top:o.t+8,bottom:340-o.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Days since change"}),l.jsx("th",{children:"Verdict"})]})}),l.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>l.jsxs("tr",{children:[l.jsx("td",{children:N.path}),l.jsx("td",{children:N.reads}),l.jsx("td",{children:Math.round(N.days)}),l.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return l.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:l.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[l.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[l.jsx("rect",{x:y(t.stale),y:o.t,width:Math.max(0,960-o.r-y(t.stale)),height:Math.max(0,g(t.hot)-o.t),className:"in-danger-zone"}),S.map(N=>l.jsxs("text",{x:y(N),y:340-o.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>l.jsx("text",{x:o.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),l.jsx("line",{x1:y(t.stale),y1:o.t,x2:y(t.stale),y2:340-o.b,className:"in-threshold","data-th":"stale"}),l.jsx("line",{x1:o.l,y1:g(t.hot),x2:960-o.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),l.jsx("line",{x1:o.l,y1:340-o.b,x2:960-o.r,y2:340-o.b,className:"in-axis"}),l.jsx("line",{x1:o.l,y1:o.t,x2:o.l,y2:340-o.b,className:"in-axis"}),l.jsx("text",{x:960-o.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),l.jsx("text",{x:12,y:(o.t+340-o.b)/2,className:"in-label",transform:`rotate(-90 12 ${(o.t+340-o.b)/2})`,children:"reads / 30d (log) →"}),l.jsx("text",{x:y(t.stale)+6,y:o.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),l.jsxs("text",{x:y(t.stale)+92,y:o.t+14,className:"in-quad-count",children:["· ",x]}),l.jsx("text",{x:o.l+6,y:o.t+14,className:"in-quad",children:"hot + fresh"}),l.jsx("text",{x:960-o.r-6,y:340-o.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),l.jsx("text",{x:o.l+6,y:340-o.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>l.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:l.jsx("title",{children:Af(N)})},N.path)),j.map(N=>l.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),l.jsxs("p",{className:"in-legend",children:[l.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",l.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",l.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((o,u)=>o+u.total,0);if(!r)return n;if(e.length>=3){const o=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(o/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(o=>o.total=2){const o=t[t.length-1];n.push({icon:"archive",head:`${o.name||"(root)"}${o.name?"/":""} is the least-read folder by agents`,body:`${Hs(o.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return l.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,o=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(o,r),f=t==="human"||t==="share",h=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Device"}),r.map(y=>l.jsx("th",{children:y.name||"(root)"},y.name)),l.jsx("th",{children:"Total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("td",{children:y.name}),r.map(g=>l.jsx("td",{children:i(y.d,g.name)},g.name)),l.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=l.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return l.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&l.jsxs("div",{className:"in-cov",children:[l.jsxs("div",{className:"in-matrix-wrap",children:[l.jsxs("table",{className:"in-matrix",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{}),r.map(y=>l.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),l.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return l.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),l.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),l.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&l.jsxs("aside",{className:"in-takeaways",children:[l.jsx("h3",{children:"What this tells you"}),u.map(y=>l.jsxs("div",{className:"in-takeaway",children:[l.jsx(sB,{name:y.icon}),l.jsxs("div",{children:[l.jsx("b",{children:y.head}),l.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,o=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&o({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return l.jsxs("div",{className:"hfilters",children:[l.jsxs("label",{className:"hf-search",children:[l.jsx(ge,{name:"search"}),l.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>l.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>o({actor:N}),children:R},R))}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"laptop"}),l.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;o({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[l.jsx("option",{value:"",children:"All devices"}),j.length>0&&l.jsx("optgroup",{label:"Devices",children:j.map(N=>l.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&l.jsx("optgroup",{label:"People",children:x.map(N=>l.jsx("option",{value:"u:"+N,children:N},N))})]})]}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"clock"}),l.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&o({range:void 0});return}y(!1),o({range:R,since:void 0,until:void 0})},children:[l.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>l.jsx("option",{value:N,children:R},N)),l.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&l.jsxs("span",{className:"hf-dates",children:[l.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>o({since:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-dash",children:"–"}),l.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>o({until:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&l.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const o={...e};for(const u of i)delete o[u];return o},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:o,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&o?.()},[S,o]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&l.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&l.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return l.jsx("div",{className:"activity",children:l.jsxs("div",{className:"history",children:[le,be,E||A?l.jsx(mB,{onRetry:U,timedOut:!E}):_&&l.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return l.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[l.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?l.jsxs("div",{className:"empty hempty",children:[l.jsx("span",{className:"hempty-icon",children:l.jsx(ge,{name:"search"})}),l.jsx("b",{children:"No changes match these filters."}),l.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>l.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,l.jsx(ge,{name:"x"})]},ve))}),l.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),l.jsxs("span",{className:"hempty-actions",children:[l.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&l.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):l.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?l.jsxs("div",{className:"hday",children:[l.jsx("b",{children:dy(Ze)}),l.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?l.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):l.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&l.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?l.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&l.jsx(dB,{})]})}function dB(){return l.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[l.jsx(ge,{name:"hist"}),l.jsx("b",{children:"Select a change"}),l.jsx("span",{children:"Its diff, rendered view and full file appear here."}),l.jsxs("span",{className:"ap-keys",children:[l.jsx("kbd",{children:"J"})," ",l.jsx("kbd",{children:"K"})," move · ",l.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return l.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[l.jsx("div",{className:"hday",children:l.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>l.jsxs("div",{className:"hskel-row",children:[l.jsx("span",{className:"hskel-dot"}),l.jsxs("span",{className:"hskel-lines",children:[l.jsx("span",{style:{width:e+"%"}}),l.jsx("span",{style:{width:e/2+"%"}})]}),l.jsx("span",{className:"hskel-time"})]},t)),l.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return l.jsxs("div",{className:"empty hempty herror",role:"alert",children:[l.jsx("span",{className:"hempty-icon herror-icon",children:l.jsx(ge,{name:"alert"})}),l.jsx("b",{children:"Couldn't load activity"}),l.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),l.jsx("span",{className:"hempty-actions",children:l.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[l.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let o="";try{o=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(o?"&tz="+encodeURIComponent(o):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return l.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return l.jsxs("div",{className:"hsum",children:[l.jsxs("div",{className:"hsum-head",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),l.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",l.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),l.jsxs("div",{className:"hsum-legend",children:[l.jsx("span",{className:"agent",children:"Agents"}),l.jsx("span",{className:"human",children:"People"})]})]}),l.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return l.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[l.jsxs("div",{className:"hsum-stack",children:[l.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),l.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),l.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",o=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return l.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[l.jsxs("div",{className:"ap-head",children:[l.jsx(ge,{name:"doc"}),l.jsx("span",{className:"ap-name",children:o}),l.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:l.jsx(ge,{name:"chev"})}),l.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:l.jsx(ge,{name:"chevd"})}),l.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:l.jsx(ge,{name:"x"})})]}),l.jsx("div",{className:"ap-path",children:t.path}),l.jsxs("div",{className:"ap-who",children:[l.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),l.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&l.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[l.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&l.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[l.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&l.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[l.jsx(ge,{name:"link"}),"Copy link"]})]}),l.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),l.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:o,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return l.jsxs("div",{className:"hrun"+(w?" open":""),children:[l.jsxs("div",{className:"hrun-head",children:[l.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:l.jsx(ge,{name:w?"chevd":"chev"})}),l.jsx("span",{className:"havatar agent","aria-hidden":"true",children:l.jsx(ge,{name:"terminal"})}),l.jsxs("span",{className:"hrun-title",children:[l.jsxs("span",{className:"hrun-what",children:[l.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),l.jsxs("span",{className:"hrun-sub",children:[l.jsx("span",{className:"hrun-note",children:l.jsx(fN,{text:e.note})}),l.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),l.jsx("span",{className:"hrun-time",children:H}),m&&l.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[l.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&l.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>l.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:o(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&l.jsxs("div",{className:"hrun-reads",children:[l.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>l.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[l.jsx("span",{className:"hkind",children:"read"}),l.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&l.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=o=>o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),o=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-o}function SB(e){const t=e.width??bB,n=i=>o=>{if(o.button!==0)return;o.preventDefault();const u=o.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=o.clientX;let g=null;u.setPointerCapture(o.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>o=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(o.key!==u&&o.key!==f)return;o.preventDefault();const h=$S(o.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(o.key===u?LS:-LS),h))};return l.jsx(l.Fragment,{children:["left","right"].map(i=>l.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=o?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"clock"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),l.jsx("span",{children:"This is not the current file."})]}),l.jsxs("div",{className:"vb-actions",children:[l.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),l.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"alert"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),l.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?l.jsxs(l.Fragment,{children:["The other version lives at ",l.jsx("code",{children:t.original})]}):l.jsx(l.Fragment,{children:"The other version kept the original name."})]})]}),n&&l.jsx("div",{className:"vb-actions",children:l.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:o}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!o),w=!i||!!o,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!o&&!!t.reads?.enabled),{data:E}=hE(i&&o?o?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!o&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&o&&Z&&!L&&pq(o.id,M)},[i,o,Z,M,L]),b.useEffect(()=>{(!i||o)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,o,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,o?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,o?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,o?.id,Ne)),ds()},[o?.id]),re=b.useCallback(ie=>gt(cn("history",o?.id,ie)),[o?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!o&&(Z||U)&&Fn(o.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!o&&Fn(Ut(M)??o.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,o?.id,L,!0,r.editing))},[M,o?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,o?.id,L,!1,r.editing),{replace:!0})},[M,o?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(o?.id,i&&!!o),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",o?.id]})},[f,o?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&o?pr?.mounts.find(ie=>ie.project===o.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!o,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!o&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!o&&Fn(o?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",l.jsxs(l.Fragment,{children:[l.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),l.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>l.jsxs("div",{className:"undo-row",children:[l.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&l.jsx("span",{className:"undo-after",children:"changed after this run"}),l.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&l.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&l.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&l.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&o){const Le=o.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:o.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&o&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!o||Le.id!==o.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,o,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?o?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?o?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!o&&t.upload.enabled&&Fn(o.perm,"write"),Io=b.useCallback(ie=>!!o&&Fn(Ut(ie?ie+"/":"")??o.perm,"write"),[o,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,o?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,o?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&o&&Fn(o.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&o?ie=>re(ie):void 0,insights:i&&o?ie=>gt(cn("dashboard",o.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,o,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=l.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:o?cn("install",o.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=l.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:o?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,o?.id,Ne),onFilters:ie=>gt(cn("history",o?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?l.jsx(uN,{}):l.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=l.jsxs("div",{className:"notfound",children:[l.jsx("h1",{children:"Couldn't find that"}),l.jsxs("p",{children:[l.jsx("code",{children:M})," isn't in this project right now."]}),l.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),l.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=l.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!o,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=l.jsxs(l.Fragment,{children:[L&&l.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&l.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=l.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:o?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?l.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=l.jsx(Nq,{project:o,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=l.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"link"})}),l.jsxs("div",{className:"vb-text",children:[l.jsxs("b",{children:["Moved from ",le.from]}),l.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?l.jsxs(l.Fragment,{children:[l.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&l.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||o?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?o.name:null,Cc=l.jsx(ci,{nav:t.desktop?l.jsxs("span",{id:"nav-btns",children:[l.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:l.jsx(ge,{name:"chevl"})}),l.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:l.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:l.jsxs(l.Fragment,{children:[l.jsx(jV,{people:x,path:M}),Vn&&l.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[l.jsx(ge,{name:"comment"})," ",l.jsx("span",{className:"lbl",children:"Comments"}),z>0&&l.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&l.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[l.jsx(ge,{name:"hist"})," ",l.jsx("span",{className:"lbl",children:"History"})]}),An&&l.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,o?.id,L,r.full,!0));return}const ie=Ln(M,o?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&l.jsx(ge,{name:"pencil"})," ",l.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&l.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&l.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[l.jsx(ge,{name:"link"})," ",l.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&l.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:l.jsx(ge,{name:"expand"})}),Kr&&l.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&l.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&l.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:l.jsx(ge,{name:"dots"})}),Te&&l.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&l.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&l.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&l.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&l.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&l.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!o&&l.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",o?.id,M))},children:"Insights"})]})]})});return l.jsxs(l.Fragment,{children:[l.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:l.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,l.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:l.jsxs(l.Fragment,{children:[!i&&l.jsx(F2,{}),Sc.trim()?l.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):l.jsxs(l.Fragment,{children:[rn&&l.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&l.jsxs("div",{className:"sb-section files-head",children:[l.jsx("span",{children:"Files"}),l.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:l.jsx(ge,{name:"sort"})}),Fa&&l.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:l.jsx(ge,{name:"fileplus"})})]}),l.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?l.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[l.jsx(ge,{name:"shrink"}),l.jsx("span",{className:"lbl",children:"Exit"}),l.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:l.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&l.jsx(b7,{shares:En,canRevoke:!!o&&Fn(o.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&l.jsx(SB,{width:rt,onChange:kt})]})}),je&&o&&l.jsx(x7,{project:o,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,o.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&l.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(o?.perm,"admin")}),l.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?l.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return l.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=l.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?l.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return l.jsx(ri,{to:"/setup"});if(!M)return l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=o?.kind==="hub"?{crumb:"Signup & access",body:l.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Organization not found"}),l.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:l.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?l.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Project not found"}),l.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?l.jsx(lU,{projects:g}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No agent access on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?l.jsx(GU,{url:e.billing.url}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No billing on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:l.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:l.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return l.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return l.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:o?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return l.jsxs(l.Fragment,{children:[l.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:l.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-mark",children:l.jsx(Sv,{size:20})}),l.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:l.jsx(PU,{pid:M.id,menu:P}),orgBar:l.jsxs(l.Fragment,{children:[l.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!o&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),l.jsx(li,{vault:l.jsx(mf,{name:"BearDrive",beta:!0}),topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?l.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):l.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:l.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return l.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?l.jsx(kB,{config:e}):l.jsx(MB,{config:e}):l.jsx(li,{vault:l.jsx(mf,{name:"…",showSignout:!1}),topbar:l.jsx(ci,{}),children:l.jsx("div",{className:"empty",children:"Loading…"})}),l.jsx(VL,{}),l.jsx(ZL,{}),l.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},o=e.path;if(!o||e.view||e.version||e.editing||!t(o))return[...r,i];const u=encodeURIComponent(o);return[...r,{queryKey:["render",n,o,""],url:n+"render?path="+u},i,{queryKey:["comments",n,o],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?l.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[l.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),l.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),l.jsx("p",{className:"mb-4",children:l.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),l.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(l.jsx(b.StrictMode,{children:l.jsx(LB,{children:l.jsx(NM,{client:$N,children:l.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,l as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/index-Bnuge9vv.js b/internal/webapp/static/assets/index-Bnuge9vv.js deleted file mode 100644 index b098924d..00000000 --- a/internal/webapp/static/assets/index-Bnuge9vv.js +++ /dev/null @@ -1,131 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-m3pwH2dA.js","assets/sharedfile-nk3qnjVG.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DpNpdB4J.js"])))=>i.map(i=>d[i]); -import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as IR,r as PR,L as UR,D as VR}from"./mermaid-DQuCJ8Gi.js";function HR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},El={};var Xb;function qR(){if(Xb)return El;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return El.Fragment=t,El.jsx=n,El.jsxs=n,El}var Wb;function BR(){return Wb||(Wb=1,$m.exports=qR()),$m.exports}var o=BR(),Fm={exports:{}},Be={};var Jb;function GR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),b=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=b&&O[b]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var _e=0;_e>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,b=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,b=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,b=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return b},e.unstable_next=function($){switch(b){case 1:case 2:case 3:var q=3;break;default:q=b}var V=b;b=q;try{return $()}finally{b=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=b;b=$;try{return q()}finally{b=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=b;return function(){var V=b;b=q;try{return $.apply(this,arguments)}finally{b=V}}}})(Um)),Um}var nw;function ZR(){return nw||(nw=1,Pm.exports=KR()),Pm.exports}var Vm={exports:{}},On={};var sw;function YR(){if(sw)return On;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=YR(),Vm.exports}var aw;function QR(){if(aw)return Nl;aw=1;var e=ZR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function _e(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Ae(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),Sl._currentValue=V)}var Ze,dt;function st(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",dt=-1)":-1p||F[d]!==ne[p]){var ce=` -`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Pe=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?st(c):""}function Ut(s,a){switch(s.tag){case 26:case 27:case 5:return st(s.type);case 16:return st("Lazy");case 13:return s.child!==a&&a!==null?st("Suspense Fallback"):st("Suspense");case 19:return st("SuspenseList");case 0:case 15:return _t(s.type,!1);case 11:return _t(s.type.render,!1);case 1:return _t(s.type,!0);case 31:return st("Activity");default:return""}}function En(s){try{var a="",c=null;do a+=Ut(s,c),c=s,s=s.return;while(s);return a}catch(d){return` -Error generating stack: `+d.message+` -`+d.stack}}var rt=Object.prototype.hasOwnProperty,sn=e.unstable_scheduleCallback,Hs=e.unstable_cancelCallback,At=e.unstable_shouldYield,Dt=e.unstable_requestPaint,$t=e.unstable_now,hr=e.unstable_getCurrentPriorityLevel,Ms=e.unstable_ImmediatePriority,ds=e.unstable_UserBlockingPriority,Ts=e.unstable_NormalPriority,qs=e.unstable_LowPriority,dn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Te,Ce=Math.log,Se=Math.LN2;function Te(s){return s>>>=0,s===0?32:31-(Ce(s)/Se|0)|0}var it=256,Ct=262144,Kt=4194304;function Et(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Et(d):(C&=k,C!==0?p=Et(C):c||(c=k&~s,c!==0&&(p=Et(c))))):(k=d&~v,k!==0?p=Et(k):C!==0?p=Et(C):c||(c=d&~s,c!==0&&(p=Et(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function ft(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function St(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function zt(){var s=Kt;return Kt<<=1,(Kt&62914560)===0&&(Kt=4194304),s}function zn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Nt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function Nn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Qr=/[\n"\\]/g;function Mn(s){return s.replace(Qr,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Ri(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Ln(a)):s.value!==""+Ln(a)&&(s.value=""+Ln(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Xr(s,C,Ln(a)):c!=null?Xr(s,C,Ln(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Ln(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Fo(s);return}c=c!=null?""+Ln(c):"",a=a!=null?""+Ln(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Fo(s)}function Xr(s,a,c){a==="number"&&Pa(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Ks(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(pr)try{var Po={};Object.defineProperty(Po,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Po,Po),window.removeEventListener("test",Po,Po)}catch{$f=!1}var Wr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Wr?Wr.value:Wr.textContent,v=p.length;for(s=0;s=Ho),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return ok.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Oi=!1;function ck(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function uk(s,a){if(Oi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Wr=null,Oi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Pa(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Pa(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var yk=pr&&"documentMode"in document&&11>=document.documentMode,Ai=null,Kf=null,Ko=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ai==null||Ai!==Pa(d)||(d=Ai,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Ko&&Go(Ko,d)||(Ko=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ke?(et=De,De=null):et=De.sibling;var ct=se(J,De,te[Ke],ue);if(ct===null){De===null&&(De=et);break}s&&De&&ct.alternate===null&&a(J,De),G=v(ct,G,Ke),lt===null?ze=ct:lt.sibling=ct,lt=ct,De=et}if(Ke===te.length)return c(J,De),at&&vr(J,Ke),ze;if(De===null){for(;KeKe?(et=De,De=null):et=De.sibling;var ba=se(J,De,ct.value,ue);if(ba===null){De===null&&(De=et);break}s&&De&&ba.alternate===null&&a(J,De),G=v(ba,G,Ke),lt===null?ze=ba:lt.sibling=ba,lt=ba,De=et}if(ct.done)return c(J,De),at&&vr(J,Ke),ze;if(De===null){for(;!ct.done;Ke++,ct=te.next())ct=fe(J,ct.value,ue),ct!==null&&(G=v(ct,G,Ke),lt===null?ze=ct:lt.sibling=ct,lt=ct);return at&&vr(J,Ke),ze}for(De=d(De);!ct.done;Ke++,ct=te.next())ct=oe(De,J,Ke,ct.value,ue),ct!==null&&(s&&ct.alternate!==null&&De.delete(ct.key===null?Ke:ct.key),G=v(ct,G,Ke),lt===null?ze=ct:lt.sibling=ct,lt=ct);return s&&De.forEach(function(FR){return a(J,FR)}),at&&vr(J,Ke),ze}function yt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var ze=te.key;G!==null;){if(G.key===ze){if(ze=te.type,ze===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===ze||typeof ze=="object"&&ze!==null&&ze.$$typeof===H&&Wa(ze)===G.type){c(J,G.sibling),ue=p(G,te.props),Jo(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ka(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),Jo(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for(ze=te.key;G!==null;){if(G.key===ze)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Wa(te),yt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if(ze=Q(te),typeof ze!="function")throw Error(r(150));return te=ze.call(te),Ie(J,G,te,ue)}if(typeof te.then=="function")return yt(J,G,Vc(te),ue);if(te.$$typeof===R)return yt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Wo=0;var ze=yt(J,G,te,ue);return qi=null,ze}catch(De){if(De===Hi||De===Pc)throw De;var lt=ts(29,De,null,J.mode);return lt.lanes=ue,lt.return=J,lt}}}var ei=d0(!0),f0=d0(!1),sa=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ra(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function aa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ut&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function el(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,kn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function tl(){if(gh){var s=Vi;if(s!==null)throw s}}function nl(s,a,c,d){gh=!1;var p=s.updateQueue;sa=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(Je&se)===se:(d&se)===se){se!==0&&se===Ui&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Ie=k;se=a;var yt=c;switch(Ie.tag){case 1:if(Oe=Ie.payload,typeof Oe=="function"){fe=Oe.call(yt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ie.payload,se=typeof Oe=="function"?Oe.call(yt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:sa=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ua|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=Nk(F,d);al(s,a,ce,is(s))}else al(s,a,d,is(s))}catch(fe){al(s,a,{then:function(){},status:"rejected",reason:fe},is())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Ak(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Ak:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),al(s,a.next.queue,{},is())}function Dh(){return yn(Sl)}function Z0(){return Ht().memoizedState}function Y0(){return Ht().memoizedState}function Dk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=is();s=ra(c);var d=aa(a,s,c);d!==null&&(Yn(d,a,c),el(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function zk(s,a,c){var d=is();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=is();al(s,a,c,d)}function al(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,es(k,C))return Ac(s,a,p,0),jt===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Gi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,kn(s,c)}}var il={readContext:yn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};il.useEffectEvent=Ft;var J0={readContext:yn,use:Yc,useCallback:function(s,a){return $n().memoizedState=[s,a===void 0?null:a],s},useContext:yn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=$n();a=a===void 0?null:a;var d=s();if(ti){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=$n();if(c!==void 0){var p=c(a);if(ti){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=zk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=$n();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=$n();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),$n().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=$n();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),jt===null)throw Error(r(349));(Je&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Zi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=$n(),a=jt.identifierPrefix;if(at){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[rn]=a,v[fn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(bn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&jr(a)}}return Rt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&jr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ii(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=vn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[rn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||ta(a,!0)}else s=xu(s).createTextNode(d),s[rn]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ii(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[rn]=a}else Za(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(ss(a),a):(ss(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ii(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[rn]=a}else Za(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(ss(a),a):(ss(a),null)}return ss(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Rt(a),null);case 4:return _e(),s===null&&vm(a.stateNode.containerInfo),Rt(a),null;case 10:return xr(a.type),Rt(a),null;case 19:if(D(Vt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)ll(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,ll(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Vt,Vt.current&1|2),at&&vr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&$t()>cu&&(a.flags|=128,p=!0,ll(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),ll(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Rt(a),null}else 2*$t()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,ll(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=$t(),s.sibling=null,c=Vt.current,B(Vt,p?c&1|2:c&1),at&&vr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return ss(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Xa),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),xr(Qt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Pk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return xr(Qt),_e(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Ae(a),null;case 31:if(a.memoizedState!==null){if(ss(a),a.alternate===null)throw Error(r(340));Za()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(ss(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Za()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Vt),null;case 4:return _e(),null;case 10:return xr(a.type),null;case 22:case 23:return ss(a),yh(),s!==null&&D(Xa),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return xr(Qt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:xr(Qt),_e();break;case 26:case 27:case 5:Ae(a);break;case 4:_e();break;case 31:a.memoizedState!==null&&ss(a);break;case 13:ss(a);break;case 19:D(Vt);break;case 10:xr(a.type);break;case 22:case 23:ss(a),yh(),s!==null&&D(Xa);break;case 24:xr(Qt)}}function cl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function la(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=ni(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function ul(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;lR(d,s.type,c,a),d[fn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&pa(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&pa(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Tn));else if(d!==4&&(d===27&&pa(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&pa(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);bn(a,d,c),a[rn]=s,a[fn]=c}catch(v){pt(s,s.return,v)}}var Cr=!1,Jt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Uk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),bn(v,d,c),v[rn]=s,Zt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kyt&&(C=yt,yt=Ie,Ie=C);var J=Iy(k,Ie),G=Iy(k,yt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Ie>yt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=fa,C=Rr;if(on=0,Ji=fa=null,Rr=0,(ut&6)!==0)throw Error(r(331));var k=ut;if(ut|=4,Px(v.current),$x(v,v.current,C,c),ut=k,gl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=gs(c,a),a=Ih(s.stateNode,a,2),s=aa(s,a,2),s!==null&&(Nt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(da===null||!da.has(d))){s=gs(c,s),c=ox(2),d=aa(a,c,2),d!==null&&(lx(c,d,a,s),Nt(d,2),Ws(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new qk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Yk.bind(null,s,a,c),a.then(s,s))}function Yk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,jt===s&&(Je&c)===c&&(It===4||It===3&&(Je&62914560)===Je&&300>$t()-lu?(ut&2)===0&&eo(s,0):sm|=c,Wi===Je&&(Wi=0)),Ws(s)}function ob(s,a){a===0&&(a=zt()),s=Ga(s,a),s!==null&&(Nt(s,a),Ws(s))}function Qk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Xk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Wk(s,a){return sn(s,a)}var pu=null,no=null,dm=!1,gu=!1,fm=!1,ma=0;function Ws(s){s!==no&&s.next===null&&(no===null?pu=no=s:no=no.next=s),gu=!0,dm||(dm=!0,eR())}function gl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=Je,v=Le(d,d===jt?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||ft(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function Jk(){lb()}function lb(){gu=dm=!1;var s=0;ma!==0&&uR()&&(s=ma);for(var a=$t(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(no=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||gl(s),ma!==0&&(ma=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=so;if(d&&typeof a=="string"&&a){var p=Mn(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),bn(a,"link",s),Zt(a),d.head.appendChild(a)))}}function xR(s){Mr.D(s),Tb("dns-prefetch",s,null)}function bR(s,a){Mr.C(s,a),Tb("preconnect",s,a)}function wR(s,a,c){Mr.L(s,a,c);var d=so;if(d&&s&&a){var p='link[rel="preload"][as="'+Mn(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+Mn(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+Mn(c.imageSizes)+'"]')):p+='[href="'+Mn(s)+'"]';var v=p;switch(a){case"style":v=ro(s);break;case"script":v=ao(s)}Ss.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),Ss.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(bl(v))||a==="script"&&d.querySelector(wl(v))||(a=d.createElement("link"),bn(a,"link",s),Zt(a),d.head.appendChild(a)))}}function SR(s,a){Mr.m(s,a);var c=so;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+Mn(d)+'"][href="'+Mn(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=ao(s)}if(!Ss.has(v)&&(s=g({rel:"modulepreload",href:s},a),Ss.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(wl(v)))return}d=c.createElement("link"),bn(d,"link",s),Zt(d),c.head.appendChild(d)}}}function jR(s,a,c){Mr.S(s,a,c);var d=so;if(d&&s){var p=Gs(d).hoistableStyles,v=ro(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(bl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=Ss.get(v))&&km(s,c);var F=C=d.createElement("link");Zt(F),bn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function CR(s,a){Mr.X(s,a);var c=so;if(c&&s){var d=Gs(c).hoistableScripts,p=ao(s),v=d.get(p);v||(v=c.querySelector(wl(p)),v||(s=g({src:s,async:!0},a),(a=Ss.get(p))&&Rm(s,a),v=c.createElement("script"),Zt(v),bn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function _R(s,a){Mr.M(s,a);var c=so;if(c&&s){var d=Gs(c).hoistableScripts,p=ao(s),v=d.get(p);v||(v=c.querySelector(wl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=Ss.get(p))&&Rm(s,a),v=c.createElement("script"),Zt(v),bn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=ro(c.href),c=Gs(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=ro(c.href);var v=Gs(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(bl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),Ss.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},Ss.set(s,c),v||ER(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=ao(c),c=Gs(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function ro(s){return'href="'+Mn(s)+'"'}function bl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function ER(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),bn(a,"link",c),Zt(a),s.head.appendChild(a))}function ao(s){return'[src="'+Mn(s)+'"]'}function wl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+Mn(c.href)+'"]');if(d)return a.instance=d,Zt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Zt(d),bn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=ro(c.href);var v=s.querySelector(bl(p));if(v)return a.state.loading|=4,a.instance=v,Zt(v),v;d=Ab(c),(p=Ss.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Zt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),bn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=ao(c.src),(p=s.querySelector(wl(v)))?(a.instance=p,Zt(p),p):(d=c,(p=Ss.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Zt(p),bn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function NR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function kR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=ro(d.href),v=a.querySelector(bl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Zt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=Ss.get(p))&&km(d,p),v=v.createElement("link"),Zt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),bn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function RR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(MR,s),Cu=null,ju.call(s))}function MR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=QR(),Im.exports}var WR=XR(),Ro=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},JR=class extends Ro{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new JR,eM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},tM=class{#e=eM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ci=new tM;function nM(e){setTimeout(e,0)}var sM=typeof window>"u"||"Deno"in globalThis;function In(){}function rM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ea(e,t){return typeof e=="function"?e(t):e}function os(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Ul(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(pi(t.options.mutationKey)!==pi(l))return!1}else if(!Ul(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||pi)(e)}function pi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Ul(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Ul(e[n],t[n])):!1}var aM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ci.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function oM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function lM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function cM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Vl=(()=>{let e=()=>sM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var uM=nM;function dM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=uM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=dM(),fM=class extends Ro{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new fM;function hM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);b(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},b=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Vl.isServer()?0:3),R=e.retryDelay??hM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?b(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ci.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Vl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ci.clearTimeout(this.#e),this.#e=void 0)}};function mM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{cM(j,()=>t.signal,()=>y=!0)},b=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await b(N),{maxPages:T}=t.options,A=E?lM:oM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function pM(e,t){return t?Ap(e,t)!=null:!1}function gM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var vM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(In).catch(In):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>os(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ea(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?mM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends Ro{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof os(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||os(this.options.enabled,this.#t)!==os(t.enabled,this.#t)||Ea(this.options.staleTime,this.#t)!==Ea(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||os(this.options.enabled,this.#t)!==os(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return xM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(In)),t}#g(){this.#b();const e=Ea(this.options.staleTime,this.#t);if(Vl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ci.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Vl.isServer()||os(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ci.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ci.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ci.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,b;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;b=y.data;let E=!1;if(t.placeholderData!==void 0&&b===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",b=Mp(i?.data,H,t),g=!0)}if(t.select&&b!==void 0&&!E)if(i&&b===l?.data&&t.select===this.#u)b=this.#l;else try{this.#u=t.select,b=t.select(b),b=Mp(i?.data,b,t),this.#l=b,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,b=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=b!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:b,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:os(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function yM(e,t){return os(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&os(t.retryOnMount,e)===!1)}function hw(e,t){return yM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(os(t.enabled,e)!==!1&&Ea(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||os(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return os(t.enabled,e)!==!1&&e.isStaleByTime(Ea(t.staleTime,e))}function xM(e,t){return!gd(e.getCurrentResult(),t)}var bM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",b=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:pM(t,n.data),hasPreviousPage:gM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:b,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!b}}},wM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var SM=class extends Ro{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new wM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch(In))))}};function Au(e){return e.options.scope?.id}var jM=class extends Ro{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&pi(n.mutationKey)!==pi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},CM=class extends Ro{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new vM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},_M=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new CM,this.#t=e.mutationCache||new SM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ea(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=rM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(In).catch(In)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(In)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(In)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ea(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(In).catch(In)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(In).catch(In)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(pi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Ul(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(pi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Ul(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=w.createContext(void 0),mn=e=>{const t=w.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},EM=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=w.createContext(!1),NM=()=>w.useContext(ej);ej.Provider;function kM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var RM=w.createContext(kM()),MM=()=>w.useContext(RM),TM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},OM=e=>{w.useEffect(()=>{e.clearReset()},[e])},AM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),DM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},zM=(e,t)=>e.isLoading&&e.isFetching&&!t,LM=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=NM(),i=MM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,DM(u),TM(u,i,f),OM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=w.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),b=!r&&h;if(w.useSyncExternalStore(w.useCallback(x=>{const j=b?y.subscribe(un.batchCalls(x)):In;return y.updateResult(),j},[y,b]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),w.useEffect(()=>{y.setOptions(u)},[u,y]),LM(u,g))throw pw(u,y,i);if(AM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Vl.isServer()&&zM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(In).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function tt(e,t){return tj(e,XS)}function $M(e,t){const n=mn(),[r]=w.useState(()=>new jM(n,e));w.useEffect(()=>{r.setOptions(e)},[r,e]);const i=w.useSyncExternalStore(w.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=w.useCallback((u,f)=>{r.mutate(u,f).catch(In)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function FM(e,t){return tj(e,bM)}let gw=!1;function IM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const PM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=PM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",UM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function tc(e){const t=await e.text();throw new Vg(e.status,VM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await tc(t),t.json()}async function HM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await tc(t),t}async function en(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await tc(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Cn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await tc(n),qd("POST",e),n.json()}async function qM(e,t,n,r=!1){const i=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{}},body:t});return i.status===401&&Bd(),i.ok||await tc(i),qd("PUT",e),await i.json().catch(()=>({}))}let zp=null;function BM(){zp??=Qe("/api/config")}function GM(){return tt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return IM(t),t},staleTime:1/0})}var nc=VS();const KM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Co(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),w.Children.forEach(i,b=>{if(JM(b)){f=!0;const x=b;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=QM(x,j),h.push(u?.props?.children)}else h.push(b)}),u?u=w.cloneElement(u,void 0,h):!f&&w.Children.count(i)===1&&w.isValidElement(i)&&(u=i);const m=u?WM(u):void 0,y=Gt(r,m);if(!u){if(i||i===0)throw new Error(f?sT(e):nT(e));return i}const g=XM(l,u.props??{});return u.type!==w.Fragment&&(g.ref=r?y:m),w.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var ZM=_o("Slot"),sj=Symbol.for("radix.slottable");function YM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=sj,t}var QM=(e,t)=>{if("child"in e.props){const n=e.props.child;return w.isValidElement(n)?w.cloneElement(n,void 0,e.props.children(n.props.children)):null}return w.isValidElement(t)?t:null};function XM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function WM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function JM(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===sj}var eT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===eT&&"_payload"in e&&tT(e._payload)}function tT(e){return typeof e=="object"&&e!==null&&"then"in e}var nT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,sT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],rT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=rT.reduce((e,t)=>{const n=_o(`Primitive.${t}`),r=w.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function rj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var aT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),iT="VisuallyHidden",aj=w.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...aT,...e.style}}));aj.displayName=iT;var oT=aj;function Ta(e,t=[]){let n=[];function r(l,u){const f=w.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:b,children:x,...j}=g,S=b?.[e]?.[h]||f,E=w.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,b,x={}){const{optional:j=!1}=x,S=b?.[e]?.[h]||f,E=w.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>w.createContext(u));return function(f){const h=f?.[e]||l;return w.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,lT(i,...t)]}function lT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function ij(e){const t=e+"CollectionProvider",[n,r]=Ta(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=w.useRef(null),R=w.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=_o(f),m=w.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Gt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",b=_o(y),x=w.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=w.useRef(null),A=Gt(E,T),M=l(y,_);return w.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(b,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return w.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?w.useLayoutEffect:()=>{},cT=Hd[" useInsertionEffect ".trim().toString()]||ar;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=uT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=w.useRef(e!==void 0);w.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=w.useCallback(y=>{if(f){const g=dT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function uT({defaultProp:e,onChange:t}){const[n,r]=w.useState(e),i=w.useRef(n),l=w.useRef(t);return cT(()=>{l.current=t},[t]),w.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function dT(e){return typeof e=="function"}function fT(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=hT(t),i=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),l=mT(r.ref,pT(i));return typeof n=="function"||r.isPresent?w.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function hT(e){const[t,n]=w.useState(),r=w.useRef(null),i=w.useRef(e),l=w.useRef("none"),u=w.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=fT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{h==="mounted"?(l.current=u.current??kl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=kl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,b=j=>{const E=kl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=kl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",b),t.addEventListener("animationend",b),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",b),t.removeEventListener("animationend",b)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:w.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=kl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function mT(...e){const t=w.useRef(e);return t.current=e,w.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),vT=0;function ls(e){const[t,n]=w.useState(gT());return ar(()=>{n(r=>r??String(vT++))},[e]),t?`radix-${t}`:""}var yT=w.createContext(void 0);function oj(e){const t=w.useContext(yT);return e||t||"ltr"}function Fr(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>((...n)=>t.current?.(...n)),[])}var xT="DismissableLayer",Lp="dismissableLayer.update",bT="dismissableLayer.pointerDownOutside",wT="dismissableLayer.focusOutside",ww,Hg=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=w.useContext(Hg),[g,b]=w.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=w.useState({}),S=Gt(t,b),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=w.useRef(!1),L=ET(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:w.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=NT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Fr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return w.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),w.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),w.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),w.useEffect(()=>{const X=()=>j({});return document.addEventListener(Lp,X),()=>document.removeEventListener(Lp,X)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=xT;var ST="DismissableLayerBranch",jT=w.forwardRef((e,t)=>{const n=w.useContext(Hg),r=w.useRef(null),i=Gt(t,r);return w.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});jT.displayName=ST;function CT(){const e=w.useContext(Hg),[t,n]=w.useState(null);return w.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var _T=()=>!0;function ET(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=_T}=t,f=Fr(e),h=w.useRef(!1),m=w.useRef(!1),y=w.useRef(new Map),g=w.useRef(()=>{});return w.useEffect(()=>{function b(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();b(),M||lj(bT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),b(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),b();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function NT(e,t=globalThis?.document){const n=Fr(e),r=w.useRef(!1);return w.useEffect(()=>{const i=l=>{l.target&&!r.current&&lj(wT,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function lj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?rj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},kT="FocusScope",qg=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=w.useState(null),m=Fr(i),y=Fr(l),g=w.useRef(null),b=Gt(t,h),x=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:ja(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||ja(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&ja(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),w.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(RT(DT(cj(f)),{select:!0}),document.activeElement===S&&ja(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||ja(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=w.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=MT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&ja(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&ja(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:b,onKeyDown:j})});qg.displayName=kT;function RT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ja(r,{select:t}),document.activeElement!==n)return}function MT(e){const t=cj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function cj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):TT(r,{upTo:t})))return r}function TT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function OT(e){return e instanceof HTMLInputElement&&"select"in e}function ja(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&OT(e)&&t&&e.select()}}var _w=AT();function AT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function DT(e){return e.filter(t=>t.tagName!=="A")}var zT="Portal",Kd=w.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=w.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=zT;var zu=0,oo=null;function uj(){w.useEffect(()=>{oo||(oo={start:Nw(),end:Nw()});const{start:e,end:t}=oo;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(oo?.start.remove(),oo?.end.remove(),oo=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return WT;var t=JT(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},tO=mj(),bo="data-scroll-locked",nO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` - .`.concat($T,` { - overflow: hidden `).concat(r,`; - padding-right: `).concat(f,"px ").concat(r,`; - } - body[`).concat(bo,`] { - overflow: hidden `).concat(r,`; - overscroll-behavior: contain; - `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` - padding-left: `.concat(i,`px; - padding-top: `).concat(l,`px; - padding-right: `).concat(u,`px; - margin-left:0; - margin-top:0; - margin-right: `).concat(f,"px ").concat(r,`; - `),n==="padding"&&"padding-right: ".concat(f,"px ").concat(r,";")].filter(Boolean).join(""),` - } - - .`).concat(sd,` { - right: `).concat(f,"px ").concat(r,`; - } - - .`).concat(rd,` { - margin-right: `).concat(f,"px ").concat(r,`; - } - - .`).concat(sd," .").concat(sd,` { - right: 0 `).concat(r,`; - } - - .`).concat(rd," .").concat(rd,` { - margin-right: 0 `).concat(r,`; - } - - body[`).concat(bo,`] { - `).concat(FT,": ").concat(f,`px; - } -`)},Rw=function(){var e=parseInt(document.body.getAttribute(bo)||"0",10);return isFinite(e)?e:0},sO=function(){w.useEffect(function(){return document.body.setAttribute(bo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(bo):document.body.setAttribute(bo,e.toString())}},[])},rO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;sO();var l=w.useMemo(function(){return eO(i)},[i]);return w.createElement(tO,{styles:nO(l,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var lo=$p?{passive:!1}:!1,aO=function(e){return e.tagName==="TEXTAREA"},pj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!aO(e)&&n[t]==="visible")},iO=function(e){return pj(e,"overflowY")},oO=function(e){return pj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=gj(e,r);if(i){var l=vj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},lO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},cO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},gj=function(e,t){return e==="v"?iO(t):oO(t)},vj=function(e,t){return e==="v"?lO(t):cO(t)},uO=function(e,t){return e==="h"&&t==="rtl"?-1:1},dO=function(e,t,n,r,i){var l=uO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,b=0;do{if(!f)break;var x=vj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&gj(e,f)&&(g+=_,b+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(b)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},fO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},hO=function(e){return` - .block-interactivity-`.concat(e,` {pointer-events: none;} - .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},mO=0,co=[];function pO(e){var t=w.useRef([]),n=w.useRef([0,0]),r=w.useRef(),i=w.useState(mO++)[0],l=w.useState(mj)[0],u=w.useRef(e);w.useEffect(function(){u.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=LT([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=w.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return dO(Q,E,S,Q==="h"?R:T)},[]),h=w.useCallback(function(S){var E=S;if(!(!co.length||co[co.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&fO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=w.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:gO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=w.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=w.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),b=w.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);w.useEffect(function(){return co.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:b}),document.addEventListener("wheel",h,lo),document.addEventListener("touchmove",h,lo),document.addEventListener("touchstart",y,lo),function(){co=co.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,lo),document.removeEventListener("touchmove",h,lo),document.removeEventListener("touchstart",y,lo)}},[]);var x=e.removeScrollBar,j=e.inert;return w.createElement(w.Fragment,null,j?w.createElement(l,{styles:hO(i)}):null,x?w.createElement(rO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function gO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const vO=BT(hj,pO);var Bg=w.forwardRef(function(e,t){return w.createElement(Zd,sr({},e,{ref:t,sideCar:vO}))});Bg.classNames=Zd.classNames;var yO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},uo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,yj=function(e){return e&&(e.host||yj(e.parentNode))},xO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=yj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},bO=function(e,t,n,r){var i=xO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(b){if(f.has(b))y(b);else try{var x=b.getAttribute(r),j=x!==null&&x!=="false",S=(uo.get(b)||0)+1,E=(l.get(b)||0)+1;uo.set(b,S),l.set(b,E),u.push(b),S===1&&j&&Fu.set(b,!0),E===1&&b.setAttribute(n,"true"),j||b.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",b,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var b=uo.get(g)-1,x=l.get(g)-1;uo.set(g,b),l.set(g,x),b||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(uo=new WeakMap,uo=new WeakMap,Fu=new WeakMap,Iu={})}},xj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=yO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),bO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[bj]=Ta(Yd),[wO,Vs]=bj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=w.useRef(null),h=w.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(wO,{scope:t,triggerRef:f,contentRef:h,contentId:ls(),titleId:ls(),descriptionId:ls(),open:m,onOpenChange:y,onOpenToggle:w.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var wj="DialogTrigger",SO=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(wj,n),l=Gt(t,i.triggerRef);return o.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});SO.displayName=wj;var Kg="DialogPortal",[jO,Sj]=bj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Kg,t);return o.jsx(jO,{scope:t,forceMount:n,children:w.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=w.forwardRef((e,t)=>{const n=Sj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(xd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(_O,{...i,ref:t})}):null});Yg.displayName=xd;var CO=_o("DialogOverlay.RemoveScroll"),_O=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(xd,n),l=CT(),u=Gt(t,l);return o.jsx(Bg,{as:CO,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Eo="DialogContent",Qg=w.forwardRef((e,t)=>{const n=Sj(Eo,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(Eo,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(EO,{...i,ref:t}):o.jsx(NO,{...i,ref:t})})});Qg.displayName=Eo;var EO=w.forwardRef((e,t)=>{const n=Vs(Eo,e.__scopeDialog),r=w.useRef(null),i=Gt(t,n.contentRef,r);return w.useEffect(()=>{const l=r.current;if(l)return xj(l)},[]),o.jsx(jj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),NO=w.forwardRef((e,t)=>{const n=Vs(Eo,e.__scopeDialog),r=w.useRef(!1),i=w.useRef(!1);return o.jsx(jj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),jj=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(Eo,n);return uj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),Cj="DialogTitle",_j=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Cj,n);return o.jsx(ot.h2,{id:i.titleId,...r,ref:t})});_j.displayName=Cj;var Ej="DialogDescription",Nj=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Ej,n);return o.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});Nj.displayName=Ej;var kj="DialogClose",Rj=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(kj,n);return o.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Rj.displayName=kj;function Xg(e){return e?"open":"closed"}function kO(e){const[t,n]=w.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const RO=["top","right","bottom","left"],Na=Math.min,zr=Math.max,bd=Math.round,Pu=Math.floor,Lr=e=>({x:e,y:e}),MO={left:"right",right:"left",bottom:"top",top:"bottom"};function Mj(e,t,n){return zr(e,Na(t,n))}function Ir(e,t){return typeof e=="function"?e(t):e}function ka(e){return e.split("-")[0]}function Mo(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(rr(e))}function TO(e,t,n){n===void 0&&(n=!1);const r=Mo(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function OO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],AO=["top","bottom"],DO=["bottom","top"];function zO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?AO:DO;default:return[]}}function LO(e,t,n,r){const i=Mo(e);let l=zO(ka(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=ka(e);return MO[t]+e.slice(t.length)}function $O(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Tj(e){return typeof e!="number"?$O(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=ev(t),f=Jg(u),h=ka(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,b=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Mo(t);return j&&(x[u]+=b*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function FO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:b=!1,padding:x=0}=Ir(t,e),j=Tj(x),E=f[b?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const IO=50,PO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:FO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),b=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ir(e,t)||{};if(m==null)return{};const g=Tj(y),b={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-b[x]-l.floating[j],A=b[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=Na(g[_],U),X=Na(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Mj(Z,ae,Q),be=!h.arrow&&Mo(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return RO.some(t=>e[t]>=0)}const HO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ir(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Oj=new Set(["left","top"]);async function qO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=ka(n),f=Mo(n),h=rr(n)==="y",m=Oj.has(u)?-1:1,y=l&&h?-1:1,g=Ir(t,e);let{mainAxis:b,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:b*m}:{x:b*m,y:x*y}}const BO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await qO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},GO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ir(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),b=rr(i),x=Wg(b);let j=y[x],S=y[b];const E=(N,R)=>Mj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(b,S));const _=h.fn({...t,[x]:j,[b]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[b]:f}}}}}},KO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ir(e,t),b={x:i,y:l},x=rr(u),j=Wg(x);let S=b[j],E=b[x];const _=Ir(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Oj.has(ka(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},ZO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ir(e,t),h=await i.detectOverflow(t,f),m=ka(n),y=Mo(n),g=rr(n)==="y",{width:b,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=b-h.left-h.right,N=Na(x-h[j],E),R=Na(b-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=b-2*zr(h.left,h.right):M=x-2*zr(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return b!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function To(e){return Aj(e)?(e.nodeName||"").toLowerCase():"#document"}function Wn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ur(e){var t;return(t=(Aj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Aj(e){return Qd()?e instanceof Node||e instanceof Wn(e).Node:!1}function lr(e){return Qd()?e instanceof Element||e instanceof Wn(e).Element:!1}function Oa(e){return Qd()?e instanceof HTMLElement||e instanceof Wn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function YO(e){return/^(table|td|th)$/.test(To(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const QO=/transform|translate|scale|rotate|perspective|filter/,XO=/paint|layout|strict|content/,ai=e=>!!e&&e!=="none";let Ym;function tv(e){const t=lr(e)?cr(e):e;return ai(t.transform)||ai(t.translate)||ai(t.scale)||ai(t.rotate)||ai(t.perspective)||!nv()&&(ai(t.backdropFilter)||ai(t.filter))||QO.test(t.willChange||"")||XO.test(t.contain||"")}function WO(e){let t=gi(e);for(;Oa(t)&&!Hl(t);){if(tv(t))return t;if(Wd(t))return null;t=gi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function Hl(e){return/^(html|body|#document)$/.test(To(e))}function cr(e){return Wn(e).getComputedStyle(e)}function Jd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function gi(e){if(To(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Ur(e);return Fw(t)?t.host:t}function Dj(e){const t=gi(e);return Hl(t)?(e.ownerDocument||e).body:Oa(t)&&Xd(t)?t:Dj(t)}function ql(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Dj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Wn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?ql(f):[])}else return t.concat(i,ql(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function zj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Oa(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return lr(e)?e:e.contextElement}function wo(e){const t=sv(e);if(!Oa(t))return Lr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=zj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const JO=Lr(0);function Lj(e){const t=Wn(e);return!nv()||!t.visualViewport?JO:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function eA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Wn(e)}function vi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Lr(1);t&&(r?lr(r)&&(u=wo(r)):u=wo(e));const f=eA(l,n,r)?Lj(l):Lr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const b=Wn(l),x=lr(r)?Wn(r):r;let j=b,S=Ip(j);for(;S&&x!==j;){const E=wo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Wn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:vi(Ur(e)).left+n}function $j(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function tA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Ur(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Lr(1);const y=Lr(0),g=Oa(r);if((g||!l)&&((To(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=vi(r);m=wo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const b=u&&!g&&!l?$j(u,h):Lr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+b.x,y:n.y*m.y-h.scrollTop*m.y+y.y+b.y}}function nA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function sA(e){const t=Jd(e),n=e.ownerDocument.body,r=zr(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=zr(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=zr(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const rA=25;function aA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Wn(e),l=Ur(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const b=!nv()||t==="fixed";r?b||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,b&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const b=l.ownerDocument,x=b.body,j=getComputedStyle(x),S=b.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=rA&&(f-=_)}return{width:f,height:h,x:m,y}}function iA(e,t){const n=vi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=wo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=aA(e,n,t);else if(t==="document")r=sA(Ur(e));else if(lr(t))r=iA(t,n);else{const i=Lj(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function oA(e,t){const n=t.get(e);if(n)return n;let r=ql(e,[],!1).filter(f=>lr(f)&&To(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?gi(e):e;for(;lr(u)&&!Hl(u);){const f=cr(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=gi(u)}return t.set(e,r),r}function lA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:oA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let b=1;b{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Wn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function pA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?ql(m):[],...t?ql(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?mA(m,n,l):null;let b=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(b),b=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?vi(e):null;h&&E();function E(){const _=vi(e);S&&!Ij(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const gA=BO,vA=GO,yA=VO,xA=ZO,bA=HO,Uw=UO,wA=KO,SA=(e,t,n)=>{const r=new Map,i=n??{},l={...hA,...i.platform,_c:r};return PO(e,t,{...i,platform:l})};var jA=typeof document<"u",CA=function(){},ad=jA?w.useLayoutEffect:CA;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Pj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Pj(e);return Math.round(t*n)/n}function Xm(e){const t=w.useRef(e);return ad(()=>{t.current=e}),t}function _A(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=w.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[b,x]=w.useState(r);jd(b,r)||x(r);const[j,S]=w.useState(null),[E,_]=w.useState(null),N=w.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=w.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=w.useRef(null),L=w.useRef(null),H=w.useRef(y),U=h!=null,Z=Xm(h),X=Xm(i),Q=Xm(m),ae=w.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:b};X.current&&(V.platform=X.current),SA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[b,t,n,X,Q]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=w.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=w.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=w.useMemo(()=>({reference:T,floating:A}),[T,A]),q=w.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Pj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return w.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const EA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},NA=(e,t)=>{const n=gA(e);return{name:n.name,fn:n.fn,options:[e,t]}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>({fn:wA(e).fn,options:[e,t]}),MA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=EA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var DA="Arrow",Uj=w.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(ot.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Uj.displayName=DA;var zA=Uj,rv="Popper",[Vj,tf]=Ta(rv),[LA,Hj]=Vj(rv),qj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=w.useState(null),[l,u]=w.useState(void 0);return o.jsx(LA,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};qj.displayName=rv;var Bj="PopperAnchor",Gj=w.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=Hj(Bj,n),u=w.useRef(null),f=l.onAnchorChange,h=w.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Gt(t,h),y=w.useRef(null);w.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),b=g?.[0],x=g?.[1];return r?null:o.jsx(ot.div,{"data-radix-popper-side":b,"data-radix-popper-align":x,...i,ref:m})});Gj.displayName=Bj;var av="PopperContent",[$A,FA]=Vj(av),Kj=w.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:b=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=Hj(av,n),[_,N]=w.useState(null),R=Gt(t,N),[T,A]=w.useState(null),M=kO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(PA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=_A({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>pA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[NA({mainAxis:i+H,alignmentAxis:u}),h&&kA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?RA():void 0,...ae}),h&&MA({...ae}),TA({...ae,apply:({elements:we,rects:_e,availableWidth:ve,availableHeight:Ae})=>{const{width:Ze,height:dt}=_e.reference,st=we.floating.style;st.setProperty("--radix-popper-available-width",`${ve}px`),st.setProperty("--radix-popper-available-height",`${Ae}px`),st.setProperty("--radix-popper-anchor-width",`${Ze}px`),st.setProperty("--radix-popper-anchor-height",`${dt}px`)}}),T&&AA({element:T,padding:f}),UA({arrowWidth:L,arrowHeight:H}),b&&OA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Fr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=w.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx($A,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Kj.displayName=av;var Zj="PopperArrow",IA={top:"bottom",right:"left",bottom:"top",left:"right"},Yj=w.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=FA(Zj,r),u=IA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(zA,{...i,ref:n,style:{...i.style,display:"block"}})})});Yj.displayName=Zj;function PA(e){return e!==null}var UA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],b=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${b}px`,S=`${-h}px`):m==="top"?(j=u?g:`${b}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Qj=qj,Xj=Gj,Wj=Kj,Jj=Yj,Wm=!1;function VA(){const[e,t]=w.useState(Wm);return w.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var eC=Hd[" useSyncExternalStore ".trim().toString()];function HA(){return()=>{}}function qA(){return eC(HA,()=>!0,()=>!1)}var BA=typeof eC=="function"?qA:VA,Jm="rovingFocusGroup.onEntryFocus",GA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,tC,KA]=ij(rc),[ZA,nC]=Ta(rc,[KA]),[YA,QA]=ZA(rc),sC=w.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(XA,{...e,ref:t})})}));sC.displayName=rc;var XA=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,b=w.useRef(null),x=Gt(t,b),j=oj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=w.useState(!1),R=Fr(m),T=tC(n),A=w.useRef(!1),[M,L]=w.useState(0);return w.useEffect(()=>{const H=b.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(YA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:w.useCallback(H=>E(H),[E]),onItemShiftTab:w.useCallback(()=>N(!0),[]),onFocusableItemAdd:w.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:w.useCallback(()=>L(H=>H-1),[]),children:o.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,GA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);iC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),rC="RovingFocusGroupItem",aC=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ls(),m=l||h,y=QA(rC,n),g=y.currentTabStopId===m,b=tC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=BA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),w.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=eD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=b().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?tD(T,A+1):T.slice(A+1)}setTimeout(()=>iC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});aC.displayName=rC;var WA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JA(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function eD(e,t,n){const r=JA(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return WA[r]}function iC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function tD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var nD=sC,sD=aC,Up=["Enter"," "],rD=["ArrowDown","PageUp","Home"],oC=["ArrowUp","PageDown","End"],aD=[...rD,...oC],iD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},oD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Bl,lD,cD]=ij(ac),[Ci,nf]=Ta(ac,[cD,tf,nC]),sf=tf(),lC=nC(),[uD,_i]=Ci(ac),[dD,ic]=Ci(ac),cC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=w.useState(null),y=w.useRef(!1),g=Fr(l),b=oj(i);return w.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),w.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Qj,{...f,children:o.jsx(uD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(dD,{scope:t,onClose:w.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:b,modal:u,children:r})})})};cC.displayName=ac;var fD="MenuAnchor",ov=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Xj,{...i,...r,ref:t})});ov.displayName=fD;var lv="MenuPortal",[hD,uC]=Ci(lv,{forceMount:void 0}),dC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=_i(lv,t);return o.jsx(hD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};dC.displayName=lv;var ks="MenuContent",[mD,cv]=Ci(ks),fC=w.forwardRef((e,t)=>{const n=uC(ks,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=_i(ks,e.__scopeMenu),u=ic(ks,e.__scopeMenu);return o.jsx(Bl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Bl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(pD,{...i,ref:t}):o.jsx(gD,{...i,ref:t})})})})}),pD=w.forwardRef((e,t)=>{const n=_i(ks,e.__scopeMenu),r=w.useRef(null),i=Gt(t,r);return w.useEffect(()=>{const l=r.current;if(l)return xj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),gD=w.forwardRef((e,t)=>{const n=_i(ks,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),vD=_o("MenuContent.ScrollLock"),uv=w.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:b,onDismiss:x,disableOutsideScroll:j,...S}=e,E=_i(ks,n),_=ic(ks,n),N=sf(n),R=lC(n),T=lD(n),[A,M]=w.useState(null),L=w.useRef(null),H=Gt(t,L,E.onContentChange),U=w.useRef(0),Z=w.useRef(""),X=w.useRef(0),Q=w.useRef(null),ae=w.useRef("right"),le=w.useRef(0),be=j?Bg:w.Fragment,$=j?{as:vD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=RD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};w.useEffect(()=>()=>window.clearTimeout(U.current),[]),uj();const V=w.useCallback(ee=>ae.current===Q.current?.side&&TD(ee,Q.current?.area),[]);return o.jsx(mD,{scope:n,searchRef:Z,onItemEnter:w.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:w.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:w.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:w.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:b,onDismiss:x,children:o.jsx(nD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Wj,{role:"menu","aria-orientation":"vertical","data-state":kC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!aD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);oC.includes(ee.key)&&re.reverse(),ND(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Gl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});fC.displayName=ks;var yD="MenuGroup",dv=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=yD;var xD="MenuLabel",hC=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{...r,ref:t})});hC.displayName=xD;var Cd="MenuItem",Hw="menu.itemSelect",rf=w.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=w.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Gt(t,l),m=w.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const b=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),rj(g,b),b.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(mC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var mC=w.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=lC(n),h=w.useRef(null),m=Gt(t,h),[y,g]=w.useState(!1),[b,x]=w.useState("");return w.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Bl.ItemSlot,{scope:n,disabled:r,textValue:i??b,children:o.jsx(sD,{asChild:!0,...f,focusable:!r,children:o.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Gl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Gl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),bD="MenuCheckboxItem",pC=w.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(bC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});pC.displayName=bD;var gC="MenuRadioGroup",[wD,SD]=Ci(gC,{value:void 0,onValueChange:()=>{}}),vC=w.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Fr(r);return o.jsx(wD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});vC.displayName=gC;var yC="MenuRadioItem",xC=w.forwardRef((e,t)=>{const{value:n,...r}=e,i=SD(yC,e.__scopeMenu),l=n===i.value;return o.jsx(bC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});xC.displayName=yC;var fv="MenuItemIndicator",[bC,jD]=Ci(fv,{checked:!1}),wC=w.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=jD(fv,n);return o.jsx(dr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(ot.span,{...i,ref:t,"data-state":hv(l.checked)})})});wC.displayName=fv;var CD="MenuSeparator",SC=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});SC.displayName=CD;var _D="MenuArrow",jC=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Jj,{...i,...r,ref:t})});jC.displayName=_D;var ED="MenuSub",[IB,CC]=Ci(ED),Dl="MenuSubTrigger",_C=w.forwardRef((e,t)=>{const n=_i(Dl,e.__scopeMenu),r=ic(Dl,e.__scopeMenu),i=CC(Dl,e.__scopeMenu),l=cv(Dl,e.__scopeMenu),u=w.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=w.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);w.useEffect(()=>y,[y]),w.useEffect(()=>{const b=f.current;return()=>{window.clearTimeout(b),h(null)}},[f,h]);const g=Gt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(mC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":kC(n.open),...e,ref:g,onClick:b=>{e.onClick?.(b),!(e.disabled||b.defaultPrevented)&&(b.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Gl(b=>{l.onItemEnter(b),!b.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Gl(b=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:b.clientX+E,y:b.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(b),b.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,b=>{e.disabled||b.target!==b.currentTarget||l.searchRef.current!==""&&b.key===" "||iD[r.dir].includes(b.key)&&(n.onOpenChange(!0),n.content?.focus(),b.preventDefault())})})})});_C.displayName=Dl;var EC="MenuSubContent",NC=w.forwardRef((e,t)=>{const n=uC(ks,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=_i(ks,e.__scopeMenu),f=ic(ks,e.__scopeMenu),h=CC(EC,e.__scopeMenu),m=w.useRef(null),y=Gt(t,m);return o.jsx(Bl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Bl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const b=g.currentTarget.contains(g.target),x=oD[f.dir].includes(g.key);b&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});NC.displayName=EC;function kC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function ND(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=kD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function MD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=b>r&&n<(g-m)*(r-y)/(b-y)+m&&(i=!i)}return i}function TD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return MD(n,t)}function Gl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var RC=cC,MC=ov,TC=dC,OC=fC,AC=dv,DC=hC,zC=rf,LC=pC,$C=vC,FC=xC,IC=wC,PC=SC,UC=jC,VC=_C,HC=NC,af="ContextMenu",[OD]=Ta(af,[nf]),Vn=nf(),[AD,qC]=OD(af),BC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=w.useRef(!1);{const g=w.useRef(!1);w.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Vn(t);return o.jsx(AD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(RC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};BC.displayName=af;var GC="ContextMenuTrigger",KC=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=qC(GC,n),u=Vn(n),[f,h]=w.useState({x:0,y:0}),m=w.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=w.useRef(0),g=w.useCallback(()=>window.clearTimeout(y.current),[]),b=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return w.useEffect(()=>g,[g]),w.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(MC,{...u,virtualRef:m}),o.jsx(ot.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),b(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>b(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});KC.displayName=GC;var DD="ContextMenuPortal",ZC=e=>{const{__scopeContextMenu:t,...n}=e,r=Vn(t);return o.jsx(TC,{...r,...n})};ZC.displayName=DD;var YC="ContextMenuContent",QC=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=qC(YC,n),l=Vn(n),u=w.useRef(!1);return o.jsx(OC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});QC.displayName=YC;var zD="ContextMenuGroup",LD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(AC,{...i,...r,ref:t})});LD.displayName=zD;var $D="ContextMenuLabel",FD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});FD.displayName=$D;var ID="ContextMenuItem",XC=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});XC.displayName=ID;var PD="ContextMenuCheckboxItem",UD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});UD.displayName=PD;var VD="ContextMenuRadioGroup",HD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});HD.displayName=VD;var qD="ContextMenuRadioItem",BD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});BD.displayName=qD;var GD="ContextMenuItemIndicator",KD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});KD.displayName=GD;var ZD="ContextMenuSeparator",WC=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});WC.displayName=ZD;var YD="ContextMenuArrow",QD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});QD.displayName=YD;var XD="ContextMenuSubTrigger",WD=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});WD.displayName=XD;var JD="ContextMenuSubContent",ez=w.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ez.displayName=JD;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var tz=BC,nz=KC,sz=ZC,rz=QC,az=XC,iz=WC,of="DropdownMenu",[oz]=Ta(of,[nf]),Hn=nf(),[lz,JC]=oz(of),e_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Hn(t),m=w.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(lz,{scope:t,triggerId:ls(),triggerRef:m,contentId:ls(),open:y,onOpenChange:g,onOpenToggle:w.useCallback(()=>g(b=>!b),[g]),modal:f,children:o.jsx(RC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};e_.displayName=of;var t_="DropdownMenuTrigger",n_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=JC(t_,n),u=Hn(n),f=Gt(t,l.triggerRef);return o.jsx(MC,{asChild:!0,...u,children:o.jsx(ot.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});n_.displayName=t_;var cz="DropdownMenuPortal",s_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Hn(t);return o.jsx(TC,{...r,...n})};s_.displayName=cz;var r_="DropdownMenuContent",a_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=JC(r_,n),l=Hn(n),u=w.useRef(!1);return o.jsx(OC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});a_.displayName=r_;var uz="DropdownMenuGroup",dz=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(AC,{...i,...r,ref:t})});dz.displayName=uz;var fz="DropdownMenuLabel",i_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(DC,{...i,...r,ref:t})});i_.displayName=fz;var hz="DropdownMenuItem",o_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuCheckboxItem",pz=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(LC,{...i,...r,ref:t})});pz.displayName=mz;var gz="DropdownMenuRadioGroup",l_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx($C,{...i,...r,ref:t})});l_.displayName=gz;var vz="DropdownMenuRadioItem",c_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuItemIndicator",u_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuSeparator",d_=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuArrow",wz=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(UC,{...i,...r,ref:t})});wz.displayName=bz;var Sz="DropdownMenuSubTrigger",jz=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(VC,{...i,...r,ref:t})});jz.displayName=Sz;var Cz="DropdownMenuSubContent",_z=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Hn(n);return o.jsx(HC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_z.displayName=Cz;var Ez=e_,Nz=n_,kz=s_,Rz=a_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz="Label",f_=w.forwardRef((e,t)=>o.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));f_.displayName=Lz;var $z=f_,Fz="Separator",qw="horizontal",Iz=["horizontal","vertical"],h_=w.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Pz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(ot.div,{"data-orientation":l,...f,...i,ref:t})});h_.displayName=Fz;function Pz(e){return Iz.includes(e)}var Uz=h_,[lf]=Ta("Tooltip",[tf]),cf=tf(),m_="TooltipProvider",Vz=700,Vp="tooltip.open",[Hz,mv]=lf(m_),p_=e=>{const{__scopeTooltip:t,delayDuration:n=Vz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=w.useRef(!0),f=w.useRef(!1),h=w.useRef(0);return w.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(Hz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:w.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:w.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:w.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};p_.displayName=m_;var Kl="Tooltip",[qz,oc]=lf(Kl),g_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Kl,e.__scopeTooltip),m=cf(t),[y,g]=w.useState(null),b=ls(),x=w.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=w.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Kl}),R=w.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=w.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=w.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=w.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return w.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Qj,{...m,children:o.jsx(qz,{scope:t,contentId:b,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:w.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:w.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};g_.displayName=Kl;var Hp="TooltipTrigger",v_=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=w.useRef(null),h=Gt(t,f,i.onTriggerChange),m=w.useRef(!1),y=w.useRef(!1),g=w.useCallback(()=>m.current=!1,[]);return w.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Xj,{asChild:!0,...u,children:o.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,b=>{b.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});v_.displayName=Hp;var pv="TooltipPortal",[Bz,Gz]=lf(pv,{forceMount:void 0}),y_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Bz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};y_.displayName=pv;var No="TooltipContent",x_=w.forwardRef((e,t)=>{const n=Gz(No,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(No,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(b_,{side:i,...l,ref:t}):o.jsx(Kz,{side:i,...l,ref:t})})}),Kz=w.forwardRef((e,t)=>{const n=oc(No,e.__scopeTooltip),r=mv(No,e.__scopeTooltip),i=w.useRef(null),l=Gt(t,i),[u,f]=w.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,b=w.useCallback(()=>{f(null),g(!1)},[g]),x=w.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Xz(_,E.getBoundingClientRect()),R=Wz(_,N),T=Jz(S.getBoundingClientRect()),A=t4([...R,...T]);f(A),g(!0)},[g]);return w.useEffect(()=>()=>b(),[b]),w.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,b]),w.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!e4(_,u);N?b():R&&(b(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,b]),o.jsx(b_,{...e,ref:l})}),[Zz,Yz]=lf(Kl,{isInside:!1}),Qz=YM("TooltipContent"),b_=w.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(No,n),m=cf(n),{onClose:y}=h;return w.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),w.useEffect(()=>{if(h.trigger){const g=b=>{b.target instanceof Node&&b.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Wj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Qz,{children:r}),o.jsx(Zz,{scope:n,isInside:!0,children:o.jsx(oT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});x_.displayName=No;var w_="TooltipArrow",S_=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Yz(w_,n).isInside?null:o.jsx(Jj,{...i,...r,ref:t})});S_.displayName=w_;function Xz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Wz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Jz(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function e4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=b>r&&n<(g-m)*(r-y)/(b-y)+m&&(i=!i)}return i}function t4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),n4(t)}function n4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var s4=p_,r4=g_,a4=v_,i4=y_,o4=x_,l4=S_;function j_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),__=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],d4="arbitrary..",f4=e=>{const t=m4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return h4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return E_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?c4(m,h):h:m||Bw}return n[u]||Bw}}},E_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=E_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?d4+r:void 0})(),m4=e=>{const{theme:t,classGroups:n}=e;return p4(n,t)},p4=(e,t)=>{const n=__();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){v4(e,t,n);return}if(typeof e=="function"){y4(e,t,n,r);return}x4(e,t,n,r)},v4=(e,t,n)=>{const r=e===""?t:N_(t,e);r.classGroupId=n},y4=(e,t,n,r)=>{if(b4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(u4(n,e))},x4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,w4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",S4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),j4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,b,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(S4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},C4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},_4=e=>({cache:w4(e.cacheSize),parseClassName:j4(e),sortModifiers:C4(e),postfixLookupClassGroupIds:E4(e),...f4(e)}),E4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(N4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:b,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(b){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},R4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=_4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=k4(h,n);return i(h,y),y};return l=u,(...h)=>l(R4(...h))},T4=[],ln=e=>{const t=n=>n[e]||T4;return t.isThemeGetter=!0,t},R_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,M_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,O4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,A4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,D4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,z4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,L4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,$4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,wa=e=>O4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),Tr=e=>A4.test(e),T_=()=>!0,F4=e=>D4.test(e)&&!z4.test(e),vv=()=>!1,I4=e=>L4.test(e),P4=e=>$4.test(e),U4=e=>!Re(e)&&!Me(e),V4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),H4=e=>Aa(e,D_,vv),Re=e=>R_.test(e),ii=e=>Aa(e,z_,F4),Zw=e=>Aa(e,X4,Ye),q4=e=>Aa(e,$_,T_),B4=e=>Aa(e,L_,vv),Yw=e=>Aa(e,O_,vv),G4=e=>Aa(e,A_,P4),Vu=e=>Aa(e,F_,I4),Me=e=>M_.test(e),Rl=e=>Ei(e,z_),K4=e=>Ei(e,L_),Qw=e=>Ei(e,O_),Z4=e=>Ei(e,D_),Y4=e=>Ei(e,A_),Hu=e=>Ei(e,F_,!0),Q4=e=>Ei(e,$_,!0),Aa=(e,t,n)=>{const r=R_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Ei=(e,t,n=!1)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n:!1},O_=e=>e==="position"||e==="percentage",A_=e=>e==="image"||e==="url",D_=e=>e==="length"||e==="size"||e==="bg-size",z_=e=>e==="length",X4=e=>e==="number",L_=e=>e==="family-name",$_=e=>e==="number"||e==="weight",F_=e=>e==="shadow",W4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),b=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Me,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Me,Re,h],U=()=>[wa,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Me,Re],X=()=>["auto",{span:["full",Js,Me,Re]},Js,Me,Re],Q=()=>[Js,"auto",Me,Re],ae=()=>["auto","min","max","fr",Me,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[wa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[wa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[wa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Me,Re],O=()=>[...T(),Qw,Yw,{position:[Me,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Z4,H4,{size:[Me,Re]}],P=()=>[ep,Rl,ii],I=()=>["","none","full",m,Me,Re],re=()=>["",Ye,Rl,ii],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],_e=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Me,Re],Ae=()=>["none",Ye,Me,Re],Ze=()=>["none",Ye,Me,Re],dt=()=>[Ye,Me,Re],st=()=>[wa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tr],breakpoint:[Tr],color:[T_],container:[Tr],"drop-shadow":[Tr],ease:["in","out","in-out"],font:[U4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tr],shadow:[Tr],spacing:["px",Ye],text:[Tr],"text-shadow":[Tr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",wa,Re,Me,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Me,Re]}],"container-named":[V4],columns:[{columns:[Ye,Re,Me,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Me,Re]}],basis:[{basis:[wa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,wa,"auto","initial","none",Re]}],grow:[{grow:["",Ye,Me,Re]}],shrink:[{shrink:["",Ye,Me,Re]}],order:[{order:[Js,"first","last","none",Me,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Rl,ii]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,Q4,q4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Re]}],"font-family":[{font:[K4,B4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Me,Re]}],"line-clamp":[{"line-clamp":[Ye,"none",Me,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Me,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Me,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Me,ii]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Me,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Me,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Me,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Me,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Me,Re],radial:["",Me,Re],conic:[Js,Me,Re]},Y4,G4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Me,Re]}],"outline-w":[{outline:["",Ye,Rl,ii]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,ii]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",b,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Me,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":_e()}],"mask-image-linear-to-pos":[{"mask-linear-to":_e()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":_e()}],"mask-image-t-to-pos":[{"mask-t-to":_e()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":_e()}],"mask-image-r-to-pos":[{"mask-r-to":_e()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":_e()}],"mask-image-b-to-pos":[{"mask-b-to":_e()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":_e()}],"mask-image-l-to-pos":[{"mask-l-to":_e()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":_e()}],"mask-image-x-to-pos":[{"mask-x-to":_e()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":_e()}],"mask-image-y-to-pos":[{"mask-y-to":_e()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Me,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":_e()}],"mask-image-radial-to-pos":[{"mask-radial-to":_e()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":_e()}],"mask-image-conic-to-pos":[{"mask-conic-to":_e()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Me,Re]}],filter:[{filter:["","none",Me,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Me,Re]}],contrast:[{contrast:[Ye,Me,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Me,Re]}],"hue-rotate":[{"hue-rotate":[Ye,Me,Re]}],invert:[{invert:["",Ye,Me,Re]}],saturate:[{saturate:[Ye,Me,Re]}],sepia:[{sepia:["",Ye,Me,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Me,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Me,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Me,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Me,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Me,Re]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Me,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Me,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Me,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Me,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Me,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Me,Re]}],ease:[{ease:["linear","initial",_,Me,Re]}],delay:[{delay:[Ye,Me,Re]}],animate:[{animate:["none",N,Me,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Me,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Ae()}],"rotate-x":[{"rotate-x":Ae()}],"rotate-y":[{"rotate-y":Ae()}],"rotate-z":[{"rotate-z":Ae()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:dt()}],"skew-x":[{"skew-x":dt()}],"skew-y":[{"skew-y":dt()}],transform:[{transform:[Me,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:st()}],"translate-x":[{"translate-x":st()}],"translate-y":[{"translate-y":st()}],"translate-z":[{"translate-z":st()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Me,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Me,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Me,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Rl,ii,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},J4=M4(W4);function nt(...e){return J4(C_(e))}function e3({delayDuration:e=0,...t}){return o.jsx(s4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(r4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(a4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(i4,{children:o.jsxs(o4,{"data-slot":"tooltip-content",sideOffset:t,className:nt("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(l4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function t3(e){return Bp.add(e),()=>Bp.delete(e)}function So(e){for(const t of Bp)t(e)}const ui=/\.(md|markdown)$/i,I_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Or=/\.html?$/i,id=/\.pdf$/i,P_=/\.(csv|tsv)$/i,n3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Zl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function yi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Dn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const V_="bdrive.lastProject";function r3(){try{return localStorage.getItem(V_)||""}catch{return""}}function a3(e){try{localStorage.setItem(V_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function H_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const q_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const i3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const o3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=o3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const l3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},c3=w.createContext({}),u3=()=>w.useContext(c3),d3=w.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:b="currentColor",className:x=""}=u3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return w.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??b,strokeWidth:j,className:q_("lucide",x,i),...!l&&!l3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>w.createElement(S,E)),...Array.isArray(l)?l:[l]])});const je=(e,t)=>{const n=w.forwardRef(({className:r,...i},l)=>w.createElement(d3,{ref:l,iconNode:t,className:q_(`lucide-${i3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const f3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],h3=je("activity",f3);const m3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],p3=je("archive",m3);const g3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],v3=je("arrow-down-wide-narrow",g3);const y3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],x3=je("beaker",y3);const b3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],w3=je("bell-off",b3);const S3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],j3=je("book-open",S3);const C3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],_3=je("briefcase",C3);const E3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],N3=je("bug",E3);const k3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],R3=je("building-2",k3);const M3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],B_=je("calendar",M3);const T3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],O3=je("chart-no-axes-combined",T3);const A3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],D3=je("check",A3);const z3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],L3=je("chevron-down",z3);const $3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],F3=je("chevron-left",$3);const I3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],P3=je("chevron-right",I3);const U3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],V3=je("chevrons-up-down",U3);const H3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],q3=je("circle-check",H3);const B3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],G3=je("circle",B3);const K3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],G_=je("clock",K3);const Z3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Y3=je("code",Z3);const Q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],X3=je("compass",Q3);const W3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],J3=je("copy",W3);const e5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],t5=je("corner-up-left",e5);const n5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],s5=je("credit-card",n5);const r5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],a5=je("database",r5);const i5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],o5=je("download",i5);const l5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],c5=je("ellipsis",l5);const u5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],d5=je("eye",u5);const f5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],h5=je("file-plus",f5);const m5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],K_=je("file-text",m5);const p5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],g5=je("flag",p5);const v5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],y5=je("folder-cog",v5);const x5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],b5=je("folder-open",x5);const w5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=je("folder",w5);const S5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],j5=je("gauge",S5);const C5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],_5=je("gavel",C5);const E5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Z_=je("globe",E5);const N5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],k5=je("graduation-cap",N5);const R5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],M5=je("heart",R5);const T5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],O5=je("history",T5);const A5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],D5=je("house",A5);const z5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],L5=je("image",z5);const $5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],F5=je("info",$5);const I5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],P5=je("laptop-minimal",I5);const U5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],V5=je("layout-dashboard",U5);const H5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],q5=je("lightbulb",H5);const B5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],G5=je("link",B5);const K5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Z5=je("loader-circle",K5);const Y5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Y_=je("lock",Y5);const Q5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],X5=je("log-out",Q5);const W5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],J5=je("maximize-2",W5);const e6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],t6=je("megaphone",e6);const n6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],s6=je("menu",n6);const r6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],a6=je("message-square",r6);const i6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],o6=je("minimize-2",i6);const l6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],c6=je("monitor",l6);const u6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],d6=je("moon",u6);const f6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],h6=je("music",f6);const m6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],p6=je("octagon-x",m6);const g6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],v6=je("package",g6);const y6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],x6=je("panel-left",y6);const b6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],w6=je("pen-line",b6);const S6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],j6=je("pencil",S6);const C6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],_6=je("plug",C6);const E6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N6=je("plus",E6);const k6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],R6=je("printer",k6);const M6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],T6=je("rocket",M6);const O6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Q_=je("search",O6);const A6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],D6=je("settings",A6);const z6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],L6=je("share-2",z6);const $6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],X_=je("shield",$6);const F6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],I6=je("sparkles",F6);const P6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],W_=je("square-terminal",P6);const U6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],J_=je("star",U6);const V6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],H6=je("sun",V6);const q6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],B6=je("tag",q6);const G6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],K6=je("trash-2",G6);const Z6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],eE=je("triangle-alert",Z6);const Y6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Q6=je("upload",Y6);const X6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=je("users",X6);const W6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],J6=je("wrench",W6);const eL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],tE=je("x",eL),nE="bdrive.sbCollapsed";function sE(){window.innerWidth<=wv?tL():nL(!document.body.classList.contains("sb-collapsed"))}function tL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),xi(),e?document.getElementById("sidebar")?.querySelector(sL)?.focus():document.getElementById("menu-btn")?.focus()}function nL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(nE,e?"1":"0")}catch{}xi()}const sL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function cs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),xi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function rL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function xi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",rE=210,aE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(aE,Math.max(rE,e)));function aL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":rE,"aria-valuemax":aE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(nE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",xi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){cs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&rL(e.target))return;e.preventDefault(),sE()}})}const iL={alert:eE,building:R3,card:s5,check:D3,chev:P3,chevd:L3,chevl:F3,clock:G_,copy:J3,doc:K_,dots:c5,download:o5,expand:J5,folder:xv,dashboard:V5,activity:h3,insights:O3,fileplus:h5,sort:v3,folderopen:b5,home:D5,laptop:P5,star:J_,system:y5,gear:D6,globe:Z_,hist:O5,link:G5,lock:Y_,menu:s6,comment:a6,plug:_6,plus:N6,power:X5,printer:R6,search:Q_,share:L6,sidebar:x6,shield:X_,shrink:o6,terminal:W_,trash:K6,upload:Q6,users:bv,x:tE,pencil:j6,eye:d5,tag:B6,jump:t5,sparkle:I6,calendar:B_};function ge({name:e}){const t=iL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":j3,"file-text":K_,"pen-line":w6,users:bv,briefcase:_3,megaphone:t6,rocket:T6,lightbulb:q5,flag:g5,star:J_,heart:M5,code:Y3,"square-terminal":W_,bug:N3,wrench:J6,database:a5,package:v6,beaker:x3,gauge:j5,shield:X_,lock:Y_,gavel:_5,globe:Z_,compass:X3,calendar:B_,clock:G_,"graduation-cap":k5,image:L5,music:h6};function hi({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function yo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function oL(e){e&&xi()}function di(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:cs}),o.jsxs("aside",{id:"sidebar",ref:oL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(aL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(iE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function iE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Zl?"⌘K":"Ctrl+K",onClick:()=>So()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function fi(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:sE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Zl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function lL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const cL=e=>{switch(e){case"success":return fL;case"info":return mL;case"warning":return hL;case"error":return pL;default:return null}},uL=Array(12).fill(0),dL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},uL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),fL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),vL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class yL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(bL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,b=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:b,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,b=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:b,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,b=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:b,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new yL,xL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},bL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",wL=xL,SL=()=>Qn.toasts,jL=()=>Qn.getActiveToasts(),Ww=Object.assign(wL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:SL,getToasts:jL});lL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const CL=3,_L="24px",EL="16px",Jw=4e3,NL=356,kL=14,RL=45,ML=200;function er(...e){return e.filter(Boolean).join(" ")}function TL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const OL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:b,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[_e,ve]=ye.useState(!1),[Ae,Ze]=ye.useState(!1),[dt,st]=ye.useState(0),[Pe,_t]=ye.useState(0),Ut=ye.useRef(g.duration||Q||Jw),En=ye.useRef(null),rt=ye.useRef(null),sn=_===0,Hs=_+1<=S,At=g.type,Dt=g.dismissible!==!1,$t=g.className||"",hr=g.descriptionClassName||"",Ms=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),ds=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Ts=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),qs=ye.useRef(0),dn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,ft,St)=>St>=Ms?Le:Le+ft.height,0),[E,Ms]),xe=vL(),Ce=g.invert||y,Se=At==="loading";dn.current=ye.useMemo(()=>Ms*le+me,[Ms,me]),ye.useEffect(()=>{Ut.current=Ts},[Ts]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=rt.current;if(Le){const ft=Le.getBoundingClientRect().height;return _t(ft),j(St=>[{toastId:g.id,height:ft,position:g.position},...St]),()=>j(St=>St.filter(zt=>zt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=rt.current,ft=Le.style.height;Le.style.height="auto";const St=Le.getBoundingClientRect().height;Le.style.height=ft,_t(St),j(zt=>zt.find(Nt=>Nt.toastId===g.id)?zt.map(Nt=>Nt.toastId===g.id?{...Nt,height:St}:Nt):[{toastId:g.id,height:St,position:g.position},...zt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Te=ye.useCallback(()=>{re(!0),st(dn.current),j(Le=>Le.filter(ft=>ft.toastId!==g.id)),setTimeout(()=>{T(g)},ML)},[g,T,j,dn]);ye.useEffect(()=>{if(g.promise&&At==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Te()},Ut.current)),()=>clearTimeout(Le)},[R,x,g,At,xe,Te]),ye.useEffect(()=>{g.delete&&(Te(),g.onDismiss==null||g.onDismiss.call(g,g))},[Te,g.delete]);function it(){var Le;if(q?.loading){var ft;return ye.createElement("div",{className:er($?.loader,g==null||(ft=g.classNames)==null?void 0:ft.loader,"sonner-loader"),"data-visible":At==="loading"},q.loading)}return ye.createElement(dL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:At==="loading"})}const Ct=g.icon||q?.[At]||cL(At);var Kt,Et;return ye.createElement("li",{tabIndex:0,ref:rt,className:er(Z,$t,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[At],g==null||(n=g.classNames)==null?void 0:n[At]),"data-sonner-toast":"","data-rich-colors":(Kt=g.richColors)!=null?Kt:A,"data-styled":!(g.jsx||g.unstyled||b),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Ae,"data-removed":I,"data-visible":Hs,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":sn,"data-swiping":he,"data-dismissible":Dt,"data-type":At,"data-invert":Ce,"data-swipe-out":_e,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?dt:dn.current}px`,"--initial-height":be?"auto":`${Pe}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(Se||!Dt||(En.current=new Date,st(dn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,ft,St;if(_e||!Dt)return;Y.current=null;const zt=Number(((Le=rt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),zn=Number(((ft=rt.current)==null?void 0:ft.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Nt=new Date().getTime()-((St=En.current)==null?void 0:St.getTime()),Nn=ee==="x"?zt:zn,fs=Math.abs(Nn)/Nt;if(Math.abs(Nn)>=RL||fs>.11){st(dn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?zt>0?"right":"left":zn>0?"down":"up"),Te(),ve(!0);return}else{var kn,pn;(kn=rt.current)==null||kn.style.setProperty("--swipe-amount-x","0px"),(pn=rt.current)==null||pn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:Le=>{var ft,St,zt;if(!Y.current||!Dt||((ft=window.getSelection())==null?void 0:ft.toString().length)>0)return;const Nt=Le.clientY-Y.current.y,Nn=Le.clientX-Y.current.x;var fs;const kn=(fs=e.swipeDirections)!=null?fs:TL(ae);!ee&&(Math.abs(Nn)>1||Math.abs(Nt)>1)&&K(Math.abs(Nn)>Math.abs(Nt)?"x":"y");let pn={x:0,y:0};const Vr=Rn=>1/(1.5+Math.abs(Rn)/20);if(ee==="y"){if(kn.includes("top")||kn.includes("bottom"))if(kn.includes("top")&&Nt<0||kn.includes("bottom")&&Nt>0)pn.y=Nt;else{const Rn=Nt*Vr(Nt);pn.y=Math.abs(Rn)0)pn.x=Nn;else{const Rn=Nn*Vr(Nn);pn.x=Math.abs(Rn)0||Math.abs(pn.y)>0)&&Ze(!0),(St=rt.current)==null||St.style.setProperty("--swipe-amount-x",`${pn.x}px`),(zt=rt.current)==null||zt.style.setProperty("--swipe-amount-y",`${pn.y}px`)}},ds&&!g.jsx&&At!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":Se,"data-close-button":!0,onClick:Se||!Dt?()=>{}:()=>{Te(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Et=q?.close)!=null?Et:gL):null,(At||g.icon||g.promise)&&g.icon!==null&&(q?.[At]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||it():null,g.type!=="loading"?Ct:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,hr,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{qu(g.cancel)&&Dt&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Te())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Te())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function AL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?EL:_L;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const DL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:b="light",richColors:x,duration:j,style:S,visibleToasts:E=CL,toastOptions:_,dir:N=e1(),gap:R=kL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(b!=="system"?b:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{KM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(b!=="system"){q(b);return}if(b==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[b]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${NL}px`,"--gap":`${R}px`,...S,...AL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,_e)=>{var ve,Ae;return ye.createElement(OL,{key:we.id,icons:T,index:_e,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Ae=_?.closeButton)!=null?Ae:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",oE="(prefers-color-scheme: dark)";let lE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return lE}}function zL(e){if(e!=="system")return e;try{return window.matchMedia(oE).matches?"dark":"light"}catch{return"dark"}}function LL(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=zL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function $L(e){lE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function FL(){if(!t1){t1=!0,ld();try{window.matchMedia(oE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function IL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${LL()}`}function _v(){const[e,t]=w.useSyncExternalStore(IL,n1,n1).split(":");return{pref:e,theme:t,setPref:$L}}const PL=({...e})=>{const{theme:t}=_v();return o.jsx(DL,{theme:t,className:"toaster group",icons:{success:o.jsx(q3,{className:"size-4"}),info:o.jsx(F5,{className:"size-4"}),warning:o.jsx(eE,{className:"size-4"}),error:o.jsx(p6,{className:"size-4"}),loading:o.jsx(Z5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function UL(){return o.jsx(PL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=C_,VL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const b=s1(y)||s1(g);return i[m][b]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,b]=y;return b===void 0||(m[g]=b),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:b,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,b]:m},[]);return r1(e,u,h,n?.class,n?.className)},HL=VL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Fe({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?ZM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:nt(HL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function qL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function BL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:nt("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(qL,{"data-slot":"dialog-portal",children:[o.jsx(BL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:nt("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Rj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(tE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Oo({className:e,...t}){return o.jsx(_j,{"data-slot":"dialog-title",className:nt("text-lg leading-none font-semibold",e),...t})}function GL({className:e,...t}){return o.jsx(Nj,{"data-slot":"dialog-description",className:nt("text-sm text-muted-foreground",e),...t})}let cE=null,cd=[];function uc(e){cE=e,cd.forEach(t=>t())}function Yl(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function KL(){const e=w.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>cE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(ZL,{m:e}):o.jsx(YL,{m:e})})})}function ZL({m:e}){const t=w.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=w.useState(""),[l,u]=w.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(Oo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Fe,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Fe,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function YL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(Oo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Fe,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Fe,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function PB(e,t){Ev({...t,path:e,from:t})}function UB(e){kd?.from===e&&Ev(null)}function QL(){const e=w.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=w.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(Oo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(GL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:yi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":yi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Fe,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Fe,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const uE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function XL(e){return tt({...uE,enabled:e,select:t=>t.projects||[]})}function WL(){const e=mn();return()=>e.fetchQuery(uE)}function dE(e){return tt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return tt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function fE(e){return tt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function hE(e,t=!0){return tt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function mE(e){return tt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function pE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function gE(e){return e.split("/").map(encodeURIComponent).join("/")}function JL(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(JL).join("/")}const e$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function t$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function n$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function s$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const r$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function vE(e,t){let n="";return e.view?(n=r$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=a$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function a$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=t$(u),h=n$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function Xn(e,t,n,r,i){const l=gE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function i$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+e$[e];return n&&(i+="/"+gE(n.replace(/\/+$/,""))),i+(e==="history"?s$(r):"")}function o$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function yE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",yE()});function bt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",yE())}function Ov(){return w.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function l$(){return Tv}function Un(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),bt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function oi({to:e}){return w.useEffect(()=>{bt(e,{replace:!0})},[e]),null}function xE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Ca(e,t){return typeof e=="function"?e(t):e}function us(e,t){return n=>{t.setState(r=>({...r,[e]:Ca(n,r[e])}))}}function gf(e){return e instanceof Function}function c$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function u$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,b=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function d$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function f$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=b=>{let x=b;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=b=>b[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var b;return[g,...(b=g.columns)==null?void 0:b.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],b=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return b(j)}return[g]},He(e.options,"debugColumns"))};for(const b of e._features)b.createColumn==null||b.createColumn(g,e);return g}const An="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const h$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(b=>b.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(b=>b.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,An)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,An)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,An)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,An)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,An)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,An)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,An)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,An)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,An)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,An)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,An)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,An)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,An)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,An)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,An)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,An))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(b,x){x===void 0&&(x=1),u=Math.max(u,x),b.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(b,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];b.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((b,x)=>c1(n,b,{depth:u,index:x}));m(y,u-1),h.reverse();const g=b=>b.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const m$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>u$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>d$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},bE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};bE.autoRemove=e=>Is(e);const wE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});CE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const _E=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>e.getValue(t)===n;EE.autoRemove=e=>Is(e);const NE=(e,t,n)=>e.getValue(t)==n;NE.autoRemove=e=>Is(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const Ar={includesString:bE,includesStringSensitive:wE,equalsString:SE,arrIncludes:jE,arrIncludesAll:CE,arrIncludesSome:_E,equals:EE,weakEquals:NE,inNumberRange:Av};function Is(e){return e==null||e===""}const g$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:us("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?Ar.includesString:typeof r=="number"?Ar.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Ar.equals:Array.isArray(r)?Ar.arrIncludes:Ar.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:Ar[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Ca(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Ca(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const v$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),y$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},b$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},S$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!c$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},j$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),C$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,_$=(e,t)=>t.length,sp={sum:v$,min:y$,max:x$,extent:b$,mean:w$,median:S$,unique:j$,uniqueCount:C$,count:_$},E$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:us("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function N$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const k$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:us("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[$l(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=$l(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=$l(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return N$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),R$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:us("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function M$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),T$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:us("columnSizing",e),onColumnSizingInfoChange:us("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,$l(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,$l(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),b=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=M$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),b(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),b((N=_.touches[0])==null?void 0:N.clientX)}},E=O$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function O$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const A$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:us("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function $l(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const D$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},z$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:us("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>Ar.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:Ar[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},L$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:us("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),$$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:us("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Ca(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Ca(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Ca(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Ca(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),F$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:us("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,b;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((b=h?.bottom)!=null?b:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},I$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:us("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,P$=(e,t,n)=>kE(Ra(e.getValue(n)).toLowerCase(),Ra(t.getValue(n)).toLowerCase()),U$=(e,t,n)=>kE(Ra(e.getValue(n)),Ra(t.getValue(n))),V$=(e,t,n)=>zv(Ra(e.getValue(n)).toLowerCase(),Ra(t.getValue(n)).toLowerCase()),H$=(e,t,n)=>zv(Ra(e.getValue(n)),Ra(t.getValue(n))),q$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Ra(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function kE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Ml={alphanumeric:P$,alphanumericCaseSensitive:U$,text:V$,textCaseSensitive:H$,datetime:q$,basic:B$},G$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:us("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Ml.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Ml.alphanumeric}return r?Ml.text:Ml.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Ml[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var b;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((b=t.options.maxMultiSortColCount)!=null?b:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},K$=[h$,A$,k$,R$,p$,g$,D$,z$,G$,E$,L$,$$,F$,I$,T$];function Z$(e){var t,n;const r=[...K$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((b,x)=>Object.assign(b,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=b=>i.options.mergeOptions?i.options.mergeOptions(l,b):{...l,...b};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(b=>{var x;h=(x=b.getInitialState==null?void 0:b.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:b=>{m.push(b),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:b=>{const x=Ca(b,i.options);i.options=u(x)},getState:()=>i.options.state,setState:b=>{i.options.onStateChange==null||i.options.onStateChange(b)},_getRowId:(b,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(b,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(b,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[b];if(!j&&(j=i.getCoreRowModel().rowsById[b],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],b=>{var x;return b=(x=b)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...b}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],b=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=f$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(b)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],b=>b.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],b=>b.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(b,x)=>{let j=b.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:b=>i._getAllFlatColumnsById()[b]};Object.assign(i,g);for(let b=0;bVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function ME(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Y$(e)?w.createElement(e,t):e:null}function Y$(e){return Q$(e)||typeof e=="function"||X$(e)}function Q$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function X$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function TE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=w.useState(()=>({current:Z$(t)})),[r,i]=w.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",_a=e=>e instanceof Date,Sn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!Sn(e)&&!Array.isArray(e)&&Lv(e)&&!_a(e),W$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,J$=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),OE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function qt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&OE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=qt(e[i]));return r}const fo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},AE="root",$v=["__proto__","constructor","prototype"],e8=/^\w*$/;var fc=e=>e8.test(e),Mt=e=>e===void 0;const t8=/[.[\]'"]/;var yf=e=>e.split(t8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>Sn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Cs=e=>typeof e=="function",xt=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const r8=vf?ye.useLayoutEffect:ye.useEffect;var jn=e=>typeof e=="string",a8=(e,t,n,r,i)=>jn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),ig=e=>Sn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!OE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(_a(e)&&_a(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(_a(f)&&_a(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Fl=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Fl(f,t))break}else if(Pt(f)&&Fl(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return xt(i,AE,t[n]),xt(e,n,i),e},wn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var DE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var zE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(jn(e)||Array.isArray(e)&&e.every(jn)||tr(e)&&!e)return{type:n,message:jn(e)?e:"",ref:t}}var ho=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:b,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Mt(u.value)&&Mt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||Sn(N))||tr(N)&&!N||L&&!DE(f).isValid||M&&!zE(f).isValid)){const{value:Q,message:ae}=jn(h)?{value:!!h,message:h}:ho(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!Sn(g)||!Sn(b))){let Q,ae;const le=ho(b),be=ho(g);if(!Sn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;Sn(le.value)||(Q=$>le.value),Sn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";jn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),jn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!Sn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&jn(N)){const{value:Q,message:ae}=ho(x);if(Md(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Cs(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Q={};for(const ae in j){if(!wn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!wn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],LE=e=>Array.isArray(e)?e.filter(Boolean):[];function i8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:i8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Pt(r)&&wn(r)||Array.isArray(r)&&o8(r))&&Bt(e,n.slice(0,-1)),e}const $E=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!_a(e[n])){const r=$E(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},l8=ye.createContext(null);l8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function FE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Pt(i)&&l){const u=FE(i,l);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var IE=e=>e.type==="select-multiple",c8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,u8=e=>{for(const t in e)if(Cs(e[t]))return!0;return!1};function PE(e){return Array.isArray(e)||Pt(e)&&!u8(e)}function UE(e){return!!(e&&"_f"in e)}function VE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];PE(i)&&(!Array.isArray(i)||!UE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),VE(t[r])&&og(t,r)):Mt(i)||(t[r]=!0)}return t}function li(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];PE(l)&&(!Array.isArray(l)||!UE(u))?(Mt(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):li(l,Sn(t)?{}:t[i],n[i],u),VE(n[i])&&og(n,i)):nr(l,t[i])?og(n,i):n[i]=!0}return n}var HE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&jn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?zE(e.refs).value:IE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?DE(e.refs).value:HE(Mt(t.value)?e.ref.value:t.value,e)}var d8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&xt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Tl=e=>Mt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var f8=e=>{if(!e||!e.validate)return!1;if(Cs(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},h8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var m8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},p8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),g8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,v8=(e,t)=>!LE(ke(e,t)).length&&Bt(e,t);const y8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},fp="form",qE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function x8(e={}){let t={...y8,...e},n={...qt(qE),isLoading:Cs(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?qt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:qt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),b=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=wn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:fo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?xt(n.validatingFields,W,Y):Bt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!wn(n.validatingFields)}))},M=()=>{n.dirtyFields=li(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const Ce=W(ke(r,z),de.argA,de.argB);me&&xt(r,z,Ce)}if(xe&&Array.isArray(ke(n.errors,z))){const Ce=W(ke(n.errors,z),de.argA,de.argB);me&&xt(n.errors,z,Ce),v8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const Ce=W(ke(n.touchedFields,z),de.argA,de.argB);me&&xt(n.touchedFields,z,Ce)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else xt(l,z,Y)},H=(z,Y)=>{xt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=fc(z)?[z]:yf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),Ce=ke(l,z,Mt(W)?ke(i,z):W);Mt(Ce)||de&&de.defaultChecked||Y?xt(l,z,Y?Ce:x1(me._f)):D(z,Ce),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&up(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,Ce=!1;const Se={name:z};if(!t.disabled||de===!0){if(!W||de){const Te=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(Ce=n.isDirty,n.isDirty=Se.isDirty=!Te||ee(),xe=Ce!==Se.isDirty),Ce=!!ke(n.dirtyFields,z),Te!==n.isDirty?n.dirtyFields=li(i,l,void 0,r):Te?Bt(n.dirtyFields,z):xt(n.dirtyFields,z,!0),Se.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Ce!==!Te}if(W){const Te=ke(n.touchedFields,z);Te||(xt(n.touchedFields,z,W),Se.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Te!==W)}xe&&me&&E.state.next(Se)}return xe?Se:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?xt(n.errors,z,W):Bt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!wn(de)||xe){const Ce={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...Ce},E.state.next(Ce)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,d8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Pt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):xt(n.errors,W,de):Bt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Pt(W))for(const de in W){const me=W[de];me&&dt(`${fp}.${de}`,{message:jn(me.message)?me.message:"",type:me.type||Ls.validate})}else jn(W)||!W?dt(fp,{message:W||"",type:Ls.validate}):Ze(fp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const Ce=z[xe];if(Ce){const{_f:Se,...Te}=Ce;if(Se){const it=f.array.has(Se.name),Ct=Ce._f&&f8(Ce._f),Kt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Ct&&Kt&&A([Se.name],!0);const Et=await v1(Ce,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,it);if(Ct&&Kt&&A([Se.name]),Et[Se.name]&&(me.valid=!1,Y)||(!Y&&(ke(Et,Se.name)?it?f1(n.errors,Et,Se.name):xt(n.errors,Se.name,Et[Se.name]):Bt(n.errors,Se.name)),e.shouldUseNativeValidation&&Et[Se.name]))break}!wn(Te)&&await q({context:me,onlyCheckValid:Y,fields:Te,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!dp(W)):!dp(Y._f.ref))&&Ut(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&xt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>a8(z,f,{...u.mount?l:Mt(Y)?i:jn(z)?{[z]:Y}:Y},W,Y),O=z=>LE(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let Ce=Y;if(xe){const Se=xe._f;Se&&(!Se.disabled&&xt(l,z,HE(Y,Se)),Ce=Rd(Se.ref)&&Sn(Y)?"":Y,IE(Se.ref)?[...Se.ref.options].forEach(Te=>Te.selected=Ce.includes(Te.value)):Se.refs?dc(Se.ref)?Se.refs.forEach(Te=>{(!Te.defaultChecked||!Te.disabled)&&(Array.isArray(Ce)?Te.checked=!!Ce.find(it=>it===Te.value):Te.checked=Ce===Te.value||!!Ce)}):Se.refs.forEach(Te=>Te.checked=Te.value===Ce):Fv(Se.ref)?Se.ref.value="":(Se.ref.value=Ce,!Se.ref.type&&!me&&E.state.next({name:z,values:de?l:qt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,Ce,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&_e(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const Ce=Y[xe],Se=z+"."+xe,Te=ke(r,Se);(f.array.has(z)||Pt(Ce)||Te&&!Te._f)&&!_a(Ce)?B(Se,Ce,W,de,me):D(Se,Ce,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),Ce=f.array.has(z),Se=de?Y:qt(Y),Te=ke(l,z),it=nr(Te,Se);if(it||xt(l,z,Se),Ce)E.array.next({name:z,values:de?l:qt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,Se)}));else{const Ct=Array.isArray(Se)&&!Se.length||wn(Se);!xe||xe._f||Sn(Se)||Ct?D(z,Se,W,de,me):B(z,Se,W,de,me)}if(!it&&!me){const Ct=up(z,f),Kt=de?l:qt(l);E.state.next({...Ct&&n,name:u.mount||Ct?z:void 0,values:Kt})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Cs(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=$E(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=Ce=>{de=Number.isNaN(Ce)||_a(Ce)&&isNaN(Ce.getTime())||nr(Ce,ke(l,W,Ce))};if(me){let Ce,Se;const Te=Y.type?x1(me._f):W$(z),it=z.type===fo.BLUR||z.type===fo.FOCUS_OUT,Ct=!h8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,Kt=Ct||g8(it,ke(n.touchedFields,W),n.isSubmitted,b,g),Et=up(W,f,it);if(xt(l,W,Te),it){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const St=h[W];St&&St(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Te,it),ft=!wn(Le)||Et;if(!it&&E.state.next({name:W,type:z.type,...y?{values:qt(l)}:{}}),Kt)return(!Ct||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?it&&T():it||T()),ft&&E.state.next({name:W,...Et?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!it&&Et&&E.state.next({...n}),t.resolver){const{errors:St}=await le([W]);if(A([W]),xe(Te),!de){!wn(Le)&&E.state.next(Le);return}const zt=w1(n.errors,r,W),zn=w1(St,r,zt.name||W);Ce=zn.error,W=zn.name,Se=wn(St)}else A([W],!0),Ce=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Te),de&&(Ce?Se=!1:(j.isValid||S.isValid)&&(Se=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&_e(me._f.deps),ae(W,Se,Ce,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},_e=async(z,Y={})=>{let W,de;const me=dd(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=wn(xe),de=z?!me.some(Ce=>ke(xe,Ce)):W}else z?(de=(await Promise.all(me.map(async xe=>{const Ce=ke(r,xe);return await q({fields:Ce&&Ce._f?{[xe]:Ce}:Ce,eventType:fo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:fo.TRIGGER});if(Y.delayError&&t.delayError&&jn(z)){const xe=ke(n.errors,z);xe?(Bt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!jn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Fl(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=FE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:jn(z)?ke(W,z):z.map(de=>ke(W,de))},Ae=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ze=z=>{const Y=z?dd(z):void 0;Y?.forEach(W=>Bt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},dt=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:Ce,type:Se,...Te}=me;xt(n.errors,z,{...Te,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},st=(z,Y)=>{if(Cs(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},Pe=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(p8(z.name,xe.name,z.exact)&&m8(xe,z.formState||j,ds,z.reRenderRoot)){const Ce={...l};z.callback({values:Ce,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},_t=z=>(u.mount=!0,S={...S,...z.formState},Pe({...z,formState:{...x,...z.formState}})),Ut=(z,Y={})=>{for(const W of z?dd(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Bt(r,W),Bt(l,W)),!Y.keepError&&Bt(n.errors,W),!Y.keepDirty&&Bt(n.dirtyFields,W),!Y.keepTouched&&Bt(n.touchedFields,W),!Y.keepIsValidating&&Bt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Bt(i,W);E.state.next({values:qt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},En=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},rt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return xt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?En({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Tl(Y.min),max:Tl(Y.max),minLength:Tl(Y.minLength),maxLength:Tl(Y.maxLength),pattern:Tl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),rt(z,Y),f.registerName.delete(z),W=ke(r,z);const Ce=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,Se=c8(Ce),Te=W._f.refs||[];if(Se?Te.find(it=>it===Ce):Ce===W._f.ref)return;xt(r,z,{_f:{...W._f,...Se?{refs:[...Te.filter(dp),Ce,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:Ce.type,name:z}}:{ref:Ce}}}),X(z,!1,void 0,Ce)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(J$(f.array,z)&&u.action)&&f.unMount.add(z)}}},sn=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Fl(r,we,f.mount),Hs=z=>{tr(z)&&(E.state.next({disabled:z}),Fl(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},At=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=qt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Ce}=await le();A(),n.errors=xe,me=qt(Ce)}else await q({fields:r,eventType:fo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Bt(me,xe);if(Bt(n.errors,AE),wn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),sn(),setTimeout(sn);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:wn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},Dt=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,qt(ke(i,z))):(I(z,Y.defaultValue),xt(i,z,qt(Y.defaultValue))),Y.keepTouched||Bt(n.touchedFields,z),Y.keepDirty||(Bt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,qt(ke(i,z))):ee()),Y.keepError||(Bt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},$t=(z,Y={})=>{const W=z?qt(z):i,de=qt(W),me=wn(z),xe=de,Ce=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const Se=new Set([...f.mount,...Object.keys(li(i,l,void 0,Ce))]);for(const Te of Array.from(Se)){const it=ke(n.dirtyFields,Te),Ct=ke(l,Te),Kt=ke(xe,Te);it&&!Mt(Ct)?xt(xe,Te,Ct):!it&&!Mt(Kt)&&I(Te,Kt)}}else{if(vf&&Mt(z))for(const Se of f.mount){const Te=ke(r,Se);if(Te&&Te._f){const it=Array.isArray(Te._f.refs)?Te._f.refs[0]:Te._f.ref;if(Rd(it)){const Ct=it.closest("form");if(Ct){Ct.reset();break}}}}if(Y.keepFieldsRef)for(const Se of f.mount)I(Se,ke(xe,Se));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?qt(i):{},Y.keepFieldsRef)for(const Se of f.mount)xt(l,Se,ke(xe,Se))}else l=qt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!wn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?li(i,l,void 0,Ce):n.dirtyFields:Y.keepDefaultValues&&z?li(i,z,void 0,Ce):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},hr=(z,Y)=>$t(Cs(z)?z(l):z,{...t.resetOptions,...Y}),Ms=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Cs(me.select)&&me.select()})}},ds=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},dn={control:{register:rt,unregister:Ut,getFieldState:Ae,handleSubmit:At,setError:dt,_subscribe:Pe,_runSchema:le,_updateIsValidating:A,_focusError:sn,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:En,_setErrors:U,_getFieldArray:O,_reset:$t,_resetDefaultValues:()=>Cs(t.defaultValues)&&t.defaultValues().then(z=>{hr(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:Hs,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),b=Zu(t.reValidateMode)}},subscribe:_t,trigger:_e,register:rt,handleSubmit:At,watch:st,setValue:I,setValues:re,getValues:ve,reset:hr,resetField:Dt,resetDefaultValues:(z,Y={})=>{if(i=qt(z),!Y.keepDirty){const W=li(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!wn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:Ut,setError:dt,setFocus:Ms,getFieldState:Ae};return{...dn,formControl:dn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...qt(qE),isLoading:Cs(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Cs(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Cs(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=x8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,r8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>s8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(b8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));xt(u,"root",l),xt(n,r,u)}else xt(n,r,l)}return n},b8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class jo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class BE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function bi(e){return Vv}function GE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function wt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ni(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Da(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function w8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const KE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const S8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ql(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ZE(e){return Ql(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const j8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function za(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function C8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function _8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Da(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ni(this,"shape",u),u},checks:[]});return za(e,l)}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Da(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ni(this,"shape",u),u},checks:[]});return za(e,l)}function N8(e,t){if(!Ql(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Da(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ni(this,"shape",l),l}});return za(e,i)}function k8(e,t){if(!Ql(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Da(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ni(this,"shape",r),r}});return za(e,n)}function R8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Da(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ni(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return za(e,n)}function M8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Da(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ni(this,"shape",h),h},checks:[]});return za(t,u)}function T8(e,t,n){const r=Da(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ni(this,"shape",l),l}});return za(t,r)}function xo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function wi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Xl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const QE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",QE),bf=pe("$ZodError",QE,{Parent:Error});function A8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function D8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new jo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>wi(h,l,bi())));throw KE(f,i?.callee),f}return u.value},z8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>wi(h,l,bi())));throw KE(f,i?.callee),f}return u.value},L8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new jo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>wi(u,i,bi())))}:{success:!0,data:l.value}},$8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>wi(u,i,bi())))}:{success:!0,data:l.value}},F8=Cf(bf),I8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},P8=e=>(t,n,r)=>wf(e)(t,n,r),U8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},V8=e=>async(t,n,r)=>Sf(e)(t,n,r),H8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},q8=e=>(t,n,r)=>jf(e)(t,n,r),B8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},G8=e=>async(t,n,r)=>Cf(e)(t,n,r),K8=/^[cC][0-9a-z]{6,}$/,Z8=/^[0-9a-z]+$/,Y8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Q8=/^[0-9a-vA-V]{20}$/,X8=/^[A-Za-z0-9]{27}$/,W8=/^[a-zA-Z0-9_-]{21}$/,J8=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,eF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sF(){return new RegExp(nF,"u")}const rF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,iF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,oF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,XE=/^[A-Za-z0-9_-]*$/,cF=/^https?$/,uF=/^\+[1-9]\d{6,14}$/,WE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",dF=new RegExp(`^${WE}$`);function JE(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fF(e){return new RegExp(`^${JE(e)}$`)}function hF(e){const t=JE({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${WE}T(?:${r})$`)}const mF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},pF=/^(?:true|false)$/i,gF=/^[^A-Z]*$/,vF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),yF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),xF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),wF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),SF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gF),_f.init(e,t)}),jF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),_F=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class kF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` -`).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>` ${l}`)];return new t(...n,i.join(` -`))}}const RF={major:4,minor:4,patch:3},tn=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=RF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=xo(u),y;for(const g of f){if(g._zod.def.when){if(O8(u)||!g._zod.def.when(u))continue}else if(m)continue;const b=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new jo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==b&&(m||(m=xo(u,b)))});else{if(u.issues.length===b)continue;m||(m=xo(u,b))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(xo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new jo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new jo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}wt(e,"~standard",()=>({validate:i=>{try{const l=$8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return F8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{tn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??mF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ot=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),MF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=eF),Ot.init(e,t)}),TF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Ot.init(e,t)}),OF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tF),Ot.init(e,t)}),AF=pe("$ZodURL",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===cF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),DF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sF()),Ot.init(e,t)}),zF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=W8),Ot.init(e,t)}),LF=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=K8),Ot.init(e,t)}),$F=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Z8),Ot.init(e,t)}),FF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Y8),Ot.init(e,t)}),IF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Q8),Ot.init(e,t)}),PF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=X8),Ot.init(e,t)}),UF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Ot.init(e,t)}),VF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=dF),Ot.init(e,t)}),HF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=fF(t)),Ot.init(e,t)}),qF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=J8),Ot.init(e,t)}),BF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rF),Ot.init(e,t),e._zod.bag.format="ipv4"}),GF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=aF),Ot.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),KF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=iF),Ot.init(e,t)}),ZF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=oF),Ot.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function e2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const YF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=lF),Ot.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{e2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function QF(e){if(!XE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return e2(n)}const XF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=XE),Ot.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{QF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),WF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=uF),Ot.init(e,t)});function JF(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const eI=pe("$ZodJWT",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{JF(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),tI=pe("$ZodBoolean",(e,t)=>{tn.init(e,t),e._zod.pattern=pF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),nI=pe("$ZodUnknown",(e,t)=>{tn.init(e,t),e._zod.parse=n=>n}),sI=pe("$ZodNever",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...YE(n,e.issues)),t.value[n]=e.value}const rI=pe("$ZodArray",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...YE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function t2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=C8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function n2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const b in t){if(b==="__proto__"||f.has(b))continue;if(m==="never"){u.push(b);continue}const x=h.run({value:t[b],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,b,t,y,g))):Od(x,n,b,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const aI=pe("$ZodObject",(e,t)=>{if(tn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>t2(t));wt(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const b of u.keys){const x=g[b],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[b],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,b,m,j,S))):Od(E,f,b,m,j,S)}return l?n2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),iI=pe("$ZodObjectJIT",(e,t)=>{aI.init(e,t);const n=e._zod.parse,r=Hv(()=>t2(t)),i=b=>{const x=new kF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=b[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` - if (${T}.issues.length) { - if (${A} in input) { - payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${A}, ...iss.path] : [${A}] - }))); - } - } - - if (${T}.value === undefined) { - if (${A} in input) { - newResult[${A}] = undefined; - } - } else { - newResult[${A}] = ${T}.value; - } - - `):L?x.write(` - if (${T}.issues.length) { - payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${A}, ...iss.path] : [${A}] - }))); - } - - if (${T}.value === undefined) { - if (${A} in input) { - newResult[${A}] = undefined; - } - } else { - newResult[${A}] = ${T}.value; - } - - `):x.write(` - const ${T}_present = ${A} in input; - if (${T}.issues.length) { - payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${A}, ...iss.path] : [${A}] - }))); - } - if (!${T}_present && !${T}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${A}] - }); - } - - if (${T}_present) { - if (${T}.value === undefined) { - newResult[${A}] = undefined; - } else { - newResult[${A}] = ${T}.value; - } - } - - `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(b,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&S8.value,y=t.catchall;let g;e._zod.parse=(b,x)=>{g??(g=r.value);const j=b.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),b=l(b,x),y?n2([],j,b,x,g,e):b):n(b,x):(b.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),b)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!xo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>wi(u,r,bi())))}),t)}const oI=pe("$ZodUnion",(e,t)=>{tn.init(e,t),wt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),wt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),wt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),wt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),lI=pe("$ZodIntersection",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ql(e)&&Ql(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),xo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const cI=pe("$ZodEnum",(e,t)=>{tn.init(e,t);const n=GE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>j8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),uI=pe("$ZodTransform",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new BE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new jo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const s2=pe("$ZodOptional",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",wt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),wt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),dI=pe("$ZodExactOptional",(e,t)=>{s2.init(e,t),wt(e._zod,"values",()=>t.innerType._zod.values),wt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),fI=pe("$ZodNullable",(e,t)=>{tn.init(e,t),wt(e._zod,"optin",()=>t.innerType._zod.optin),wt(e._zod,"optout",()=>t.innerType._zod.optout),wt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),wt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),hI=pe("$ZodDefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",wt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const mI=pe("$ZodPrefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",wt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),pI=pe("$ZodNonOptional",(e,t)=>{tn.init(e,t),wt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const gI=pe("$ZodCatch",(e,t)=>{tn.init(e,t),e._zod.optin="optional",wt(e._zod,"optout",()=>t.innerType._zod.optout),wt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>wi(u,r,bi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>wi(l,r,bi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),vI=pe("$ZodPipe",(e,t)=>{tn.init(e,t),wt(e._zod,"values",()=>t.in._zod.values),wt(e._zod,"optin",()=>t.in._zod.optin),wt(e._zod,"optout",()=>t.out._zod.optout),wt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const yI=pe("$ZodReadonly",(e,t)=>{tn.init(e,t),wt(e._zod,"propValues",()=>t.innerType._zod.propValues),wt(e._zod,"values",()=>t.innerType._zod.values),wt(e._zod,"optin",()=>t.innerType?._zod?.optin),wt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const xI=pe("$ZodCustom",(e,t)=>{fr.init(e,t),tn.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Xl(i))}}var $1;class bI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function wI(){return new bI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=wI());const zl=globalThis.__zod_globalRegistry;function SI(e,t){return new e({type:"string",...qe(t)})}function jI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function CI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function kI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function RI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function BI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function GI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function KI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function ZI(e,t){return new e({type:"boolean",...qe(t)})}function YI(e){return new e({type:"unknown"})}function QI(e,t){return new e({type:"never",...qe(t)})}function r2(e,t){return new yF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new xF({check:"min_length",...qe(t),minimum:e})}function a2(e,t){return new bF({check:"length_equals",...qe(t),length:e})}function XI(e,t){return new wF({check:"string_format",format:"regex",...qe(t),pattern:e})}function WI(e){return new SF({check:"string_format",format:"lowercase",...qe(e)})}function JI(e){return new jF({check:"string_format",format:"uppercase",...qe(e)})}function eP(e,t){return new CF({check:"string_format",format:"includes",...qe(t),includes:e})}function tP(e,t){return new _F({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function nP(e,t){return new EF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Ao(e){return new NF({check:"overwrite",tx:e})}function sP(e){return Ao(t=>t.normalize(e))}function rP(){return Ao(e=>e.trim())}function aP(){return Ao(e=>e.toLowerCase())}function iP(){return Ao(e=>e.toUpperCase())}function oP(){return Ao(e=>w8(e))}function lP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function cP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function uP(e,t){const n=dP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Xl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Xl(l))}},e(r.value,r)),t);return n}function dP(e,t){const n=new fr({check:"custom",...qe(t)});return n._zod.check=e,n}function i2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??zl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function _n(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const b=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,b,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),_n(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Fn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function o2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,b=e.external.uri??(j=>j);if(g)return{ref:b(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${b("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const b=f._zod.parent;if(b&&b!==g){r(b);const x=e.seen.get(b);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Fn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Fn(r.element,n);if(r.type==="set")return Fn(r.valueType,n);if(r.type==="lazy")return Fn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Fn(r.innerType,n);if(r.type==="intersection")return Fn(r.left,n)||Fn(r.right,n);if(r.type==="record"||r.type==="map")return Fn(r.keyType,n)||Fn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Fn(r.in,n)||Fn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Fn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Fn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Fn(i,n))return!0;return!!(r.rest&&Fn(r.rest,n))}return!1}const fP=(e,t={})=>n=>{const r=i2({...n,processors:t});return _n(e,r),o2(r,e),l2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=i2({...i??{},target:l,io:t,processors:n});return _n(e,u),o2(u,e),l2(u,e)},hP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},mP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=hP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},pP=(e,t,n,r)=>{n.type="boolean"},gP=(e,t,n,r)=>{n.not={}},vP=(e,t,n,r)=>{},yP=(e,t,n,r)=>{const i=e._zod.def,l=GE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},xP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=_n(l.element,t,{...r,path:[...r.path,"items"]})},SP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=_n(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=_n(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},jP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>_n(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},CP=(e,t,n,r)=>{const i=e._zod.def,l=_n(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=_n(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},_P=(e,t,n,r)=>{const i=e._zod.def,l=_n(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},EP=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},NP=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},kP=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},RP=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},MP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;_n(u,t,r);const f=t.seen.get(e);f.ref=u},TP=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},c2=(e,t,n,r)=>{const i=e._zod.def;_n(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(b){return e.push(fg({},b,{path:[].concat(i.path,b.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(OP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?z8:L8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(AP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const DP=pe("ZodISODateTime",(e,t)=>{UF.init(e,t),Lt.init(e,t)});function zP(e){return qI(DP,e)}const LP=pe("ZodISODate",(e,t)=>{VF.init(e,t),Lt.init(e,t)});function $P(e){return BI(LP,e)}const FP=pe("ZodISOTime",(e,t)=>{HF.init(e,t),Lt.init(e,t)});function IP(e){return GI(FP,e)}const PP=pe("ZodISODuration",(e,t)=>{qF.init(e,t),Lt.init(e,t)});function UP(e){return KI(PP,e)}const VP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>D8(e,n)},flatten:{value:n=>A8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Rs=pe("ZodError",VP,{Parent:Error}),HP=wf(Rs),qP=Sf(Rs),BP=jf(Rs),GP=Cf(Rs),KP=I8(Rs),ZP=P8(Rs),YP=U8(Rs),QP=V8(Rs),XP=H8(Rs),WP=q8(Rs),JP=B8(Rs),e9=G8(Rs),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const nn=pe("ZodType",(e,t)=>(tn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=fP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>HP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>BP(e,n,r),e.parseAsync=async(n,r)=>qP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>GP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>KP(e,n,r),e.decode=(n,r)=>ZP(e,n,r),e.encodeAsync=async(n,r)=>YP(e,n,r),e.decodeAsync=async(n,r)=>QP(e,n,r),e.safeEncode=(n,r)=>XP(e,n,r),e.safeDecode=(n,r)=>WP(e,n,r),e.safeEncodeAsync=async(n,r)=>JP(e,n,r),e.safeDecodeAsync=async(n,r)=>e9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Da(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return za(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(K9(n,r))},superRefine(n,r){return this.check(Z9(n,r))},overwrite(n){return this.check(Ao(n))},optional(){return q1(this)},exactOptional(){return D9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return P9(this,n)},array(){return C9(this)},or(n){return N9([this,n])},and(n){return R9(this,n)},transform(n){return G1(this,O9(n))},default(n){return $9(this,n)},prefault(n){return I9(this,n)},catch(n){return V9(this,n)},pipe(n){return G1(this,n)},readonly(){return B9(this)},describe(n){const r=this.clone();return zl.add(r,{description:n}),r},meta(...n){if(n.length===0)return zl.get(this);const r=this.clone();return zl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return zl.get(e)?.description},configurable:!0}),e)),u2=pe("_ZodString",(e,t)=>{Zv.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>mP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(XI(...r))},includes(...r){return this.check(eP(...r))},startsWith(...r){return this.check(tP(...r))},endsWith(...r){return this.check(nP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(r2(...r))},length(...r){return this.check(a2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(WI(r))},uppercase(r){return this.check(JI(r))},trim(){return this.check(rP())},normalize(...r){return this.check(sP(...r))},toLowerCase(){return this.check(aP())},toUpperCase(){return this.check(iP())},slugify(){return this.check(oP())}})}),t9=pe("ZodString",(e,t)=>{Zv.init(e,t),u2.init(e,t),e.email=n=>e.check(jI(n9,n)),e.url=n=>e.check(kI(s9,n)),e.jwt=n=>e.check(HI(y9,n)),e.emoji=n=>e.check(RI(r9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(CI(Xu,n)),e.uuidv4=n=>e.check(_I(Xu,n)),e.uuidv6=n=>e.check(EI(Xu,n)),e.uuidv7=n=>e.check(NI(Xu,n)),e.nanoid=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(TI(i9,n)),e.cuid2=n=>e.check(OI(o9,n)),e.ulid=n=>e.check(AI(l9,n)),e.base64=n=>e.check(PI(p9,n)),e.base64url=n=>e.check(UI(g9,n)),e.xid=n=>e.check(DI(c9,n)),e.ksuid=n=>e.check(zI(u9,n)),e.ipv4=n=>e.check(LI(d9,n)),e.ipv6=n=>e.check($I(f9,n)),e.cidrv4=n=>e.check(FI(h9,n)),e.cidrv6=n=>e.check(II(m9,n)),e.e164=n=>e.check(VI(v9,n)),e.datetime=n=>e.check(zP(n)),e.date=n=>e.check($P(n)),e.time=n=>e.check(IP(n)),e.duration=n=>e.check(UP(n))});function fd(e){return SI(t9,e)}const Lt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),u2.init(e,t)}),n9=pe("ZodEmail",(e,t)=>{OF.init(e,t),Lt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{MF.init(e,t),Lt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{TF.init(e,t),Lt.init(e,t)}),s9=pe("ZodURL",(e,t)=>{AF.init(e,t),Lt.init(e,t)}),r9=pe("ZodEmoji",(e,t)=>{DF.init(e,t),Lt.init(e,t)}),a9=pe("ZodNanoID",(e,t)=>{zF.init(e,t),Lt.init(e,t)}),i9=pe("ZodCUID",(e,t)=>{LF.init(e,t),Lt.init(e,t)}),o9=pe("ZodCUID2",(e,t)=>{$F.init(e,t),Lt.init(e,t)}),l9=pe("ZodULID",(e,t)=>{FF.init(e,t),Lt.init(e,t)}),c9=pe("ZodXID",(e,t)=>{IF.init(e,t),Lt.init(e,t)}),u9=pe("ZodKSUID",(e,t)=>{PF.init(e,t),Lt.init(e,t)}),d9=pe("ZodIPv4",(e,t)=>{BF.init(e,t),Lt.init(e,t)}),f9=pe("ZodIPv6",(e,t)=>{GF.init(e,t),Lt.init(e,t)}),h9=pe("ZodCIDRv4",(e,t)=>{KF.init(e,t),Lt.init(e,t)}),m9=pe("ZodCIDRv6",(e,t)=>{ZF.init(e,t),Lt.init(e,t)}),p9=pe("ZodBase64",(e,t)=>{YF.init(e,t),Lt.init(e,t)}),g9=pe("ZodBase64URL",(e,t)=>{XF.init(e,t),Lt.init(e,t)}),v9=pe("ZodE164",(e,t)=>{WF.init(e,t),Lt.init(e,t)}),y9=pe("ZodJWT",(e,t)=>{eI.init(e,t),Lt.init(e,t)}),x9=pe("ZodBoolean",(e,t)=>{tI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pP(e,n,r)});function V1(e){return ZI(x9,e)}const b9=pe("ZodUnknown",(e,t)=>{nI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP()});function H1(){return YI(b9)}const w9=pe("ZodNever",(e,t)=>{sI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function S9(e){return QI(w9,e)}const j9=pe("ZodArray",(e,t)=>{rI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(r2(n,r))},length(n,r){return this.check(a2(n,r))},unwrap(){return this.element}})});function C9(e,t){return lP(j9,e,t)}const _9=pe("ZodObject",(e,t)=>{iI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),wt(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return M9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:S9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return N8(this,n)},safeExtend(n){return k8(this,n)},merge(n){return R8(this,n)},pick(n){return _8(this,n)},omit(n){return E8(this,n)},partial(...n){return M8(d2,this,n[0])},required(...n){return T8(f2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new _9(n)}const E9=pe("ZodUnion",(e,t)=>{oI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),e.options=t.options});function N9(e,t){return new E9({type:"union",options:e,...qe(t)})}const k9=pe("ZodIntersection",(e,t)=>{lI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i)});function R9(e,t){return new k9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{cI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>yP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function M9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const T9=pe("ZodTransform",(e,t)=>{uI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new BE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Xl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Xl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function O9(e){return new T9({type:"transform",transform:e})}const d2=pe("ZodOptional",(e,t)=>{s2.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>c2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new d2({type:"optional",innerType:e})}const A9=pe("ZodExactOptional",(e,t)=>{dI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>c2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function D9(e){return new A9({type:"optional",innerType:e})}const z9=pe("ZodNullable",(e,t)=>{fI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new z9({type:"nullable",innerType:e})}const L9=pe("ZodDefault",(e,t)=>{hI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $9(e,t){return new L9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ZE(t)}})}const F9=pe("ZodPrefault",(e,t)=>{mI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function I9(e,t){return new F9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ZE(t)}})}const f2=pe("ZodNonOptional",(e,t)=>{pI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new f2({type:"nonoptional",innerType:e,...qe(t)})}const U9=pe("ZodCatch",(e,t)=>{gI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function V9(e,t){return new U9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const H9=pe("ZodPipe",(e,t)=>{vI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new H9({type:"pipe",in:e,out:t})}const q9=pe("ZodReadonly",(e,t)=>{yI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B9(e){return new q9({type:"readonly",innerType:e})}const G9=pe("ZodCustom",(e,t)=>{xI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xP(e,n)});function K9(e,t={}){return cP(G9,e,t)}function Z9(e,t){return uP(e,t)}function Y9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:nt("w-full caption-bottom text-sm",e),...t})})}function Q9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:nt("[&_tr]:border-b",e),...t})}function X9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:nt("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:nt("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:nt("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function W9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:nt("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function h2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Y9,{className:"admin-table",children:[o.jsx(Q9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(J9,{header:r},r.id))},n.id))}),o.jsx(X9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(W9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function m2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function eU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function p2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(m2(e.expires));const r=eU(e);return r&&n.push(r),n.join(" · ")}const g2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function v2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=w.useState([]),h=w.useMemo(()=>xE(),[]),m=w.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Un(Xn(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>p2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Dn(g.row.original.url).then(b=>Ne(b?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>y2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=TE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:RE(),getSortedRowModel:ME()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(h2,{table:y,className:"shares-table"})}async function y2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await en("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const tU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function nU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(tU),values:{name:e.name}}),{data:m}=tt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=tt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),b=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await en("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Fe,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(rU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[b.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),b.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Fe,{variant:"primary",onClick:async()=>{try{const x=await Cn(`/api/orgs/${e.id}/invites`),j=await Dn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Dn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await en("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(v2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(sU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function sU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=tt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Dn(u),await Yl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Fe,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Yl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Cn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Dn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Fe,{variant:"subtle",onClick:()=>i(async()=>l((await Cn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>en("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>en("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function rU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=w.useState([{id:"email",desc:!1}]),u=w.useMemo(()=>xE(),[]),f=w.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async b=>{try{await en("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:b.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await en("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(b){Ne(b.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=TE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:RE(),getSortedRowModel:ME()});return o.jsx(h2,{table:h})}const aU=Qv({require_verification:V1(),require_approval:V1()});function iU(){const e=mn(),{data:t,error:n}=tt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=mE(!0),i=Uv({resolver:Yv(aU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(w.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Cn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Cn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Fe,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Fe,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function _s({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:nt("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:nt("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:nt("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:nt("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:nt("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function oU({projects:e}){const t=mn(),n=tt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=$M({mutationFn:u=>en("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(_s,{children:o.jsxs(Es,{children:[o.jsx(Ns,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(_s,{className:"mcp-grant",children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Fe,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Ez,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(kz,{children:o.jsx(Rz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:nt("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function js({className:e,inset:t,variant:n="default",...r}){return o.jsx(Tz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function lU({...e}){return o.jsx(Oz,{"data-slot":"dropdown-menu-radio-group",...e})}function cU({className:e,children:t,...n}){return o.jsxs(Az,{"data-slot":"dropdown-menu-radio-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(Dz,{children:o.jsx(G3,{className:"size-2 fill-current"})})}),t]})}function uU({className:e,inset:t,...n}){return o.jsx(Mz,{"data-slot":"dropdown-menu-label","data-inset":t,className:nt("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(zz,{"data-slot":"dropdown-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function dU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,x2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function fU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function hU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function mU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return w.useSyncExternalStore(ny,()=>e?fU(e):0)}const gg=new Map,pU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(x2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(x2(e),JSON.stringify(r)),ty()}function gU(e){return w.useSyncExternalStore(ny,()=>e?ry(e):pU)}const b2="bdrive.treeOrder";function vU(){return w.useSyncExternalStore(ny,()=>ey(b2)==="recent"?"recent":"name")}function yU(e){hc(b2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const $r="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function xU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function bU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const wU=7;function SU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const jU=(e,t)=>t-el.reads-i.reads).slice(0,_U)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*EU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const w2=10,S2=30,j2=(e,t)=>e>=w2&&t>=S2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function C2(e,t){const n=ay(t);return!e||n===null||!j2(Ps(e),n)?"":`stale · last changed ${iy(n)}`}function _2(e,t=!0){const n=tt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=w.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const E2=e=>({...e,children:e.children?.map(E2)}),N2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&N2(t)}},k2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=k2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function kU(e,t){const n=E2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hb.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(b=>b.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(b=>b.name!==m||b.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}N2(n),k2(n)}return n}function RU(e,t){return tt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function MU(e,t,n){return tt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const R2=e=>"/api/p/"+e+"/",$d=100;function M2(e,t=!0){const n=sy(e),r=e?R2(e):"";return tt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function T2(e,t=!0){const n=M2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function TU(e,t){const n=e?R2(e):"",r=tt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=_2(n,!!e),l=w.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function OU(e,t){const n=tt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return w.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function po(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},md=0,O2=null;const vg=new Set;function Nf(e){ur=e;for(const t of vg)t()}function oy(){return w.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>ur)}function A2(e){e!==ur.query&&Nf({query:e,sel:0})}function yg(){A2("")}function AU(e,t){md=e,O2=t,ur.sel>=e&&Nf({...ur,sel:Math.max(0,e-1)})}function DU(e){md!==0&&Nf({...ur,sel:(ur.sel+e+md)%md})}function J1(e){e!==ur.sel&&Nf({...ur,sel:e})}function zU(){O2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function D2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":D2(e)}}const z2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=T2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx(L2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(hi,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(V3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx($2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:z2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function L2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=w.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),b=r?.org??null,x=b?Un(b.manage_url):null,j=r?.billing?Un(r.billing.url):null,S=Un("/connections"),E=!!b&&!b.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(js,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&&bt("/"+_.id),cs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(hi,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(js,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||b||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(js,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),b&&o.jsx(js,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:b.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(js,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(js,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(uU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(lU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:LU.map(({value:_,label:N,Glyph:R})=>o.jsx(cU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(js,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(js,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(js,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const LU=[{value:"system",label:"System",Glyph:c6},{value:"light",label:"Light",Glyph:H6},{value:"dark",label:"Dark",Glyph:d6}];function $U(){const[,e]=w.useState(0);w.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function FU({pid:e,readsEnabled:t,active:n,onOpen:r}){$U();const{devices:i,synced:l}=TU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+po(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function $2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),So(),cs())},onChange:t=>A2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),DU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?So(e.trim()):zU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{So(),cs()},children:Zl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Zl?"⌘K":"Ctrl+K"})]})]})]})}function IU({pid:e,menu:t}){const n=T2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:z2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function PU(e){return o.jsx(L2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(hi,{name:e.current.icon})})})})}const UU="https://github.com/runbear-io/beardrive";function VU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function HU(){return o.jsxs("a",{className:"gh-star",href:UU,target:"_blank",rel:"noreferrer",children:[o.jsx(VU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function qU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(HU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Dr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Uz,{"data-slot":"separator",decorative:n,orientation:t,className:nt("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function BU({url:e}){const t=tt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(_s,{children:[o.jsxs(Es,{children:[o.jsxs(Ns,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Dr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(_s,{children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Dr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Fe,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(_s,{children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Dr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Fe,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:nt("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx($z,{"data-slot":"label",className:nt("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function GU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:nt("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Pn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,KU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function ZU({project:e,org:t,onDeleted:n}){const r=pE(),i=Pn(e.perm,"admin"),l=Uv({resolver:Yv(KU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});w.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await en("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(b){Ne(b.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!Pn(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(_s,{children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Dr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(hi,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Fe,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(js,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(hi,{})}),Object.keys(Yp).map(m=>o.jsx(js,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(hi,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(GU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Dr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Fe,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(QU,{project:e}),o.jsx(WU,{project:e,org:t}),o.jsxs(_s,{id:"ps-devices",children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Fe,{asChild:!0,variant:"outline",children:o.jsx("a",{...Un(cn("install",e.id)),children:"Connect a device"})})})]}),Pn(e.perm,"write")&&o.jsx(YU,{project:e,onChanged:r}),o.jsxs(_s,{children:[o.jsx(Es,{children:o.jsx(Ns,{children:"About"})}),o.jsx(Dr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(_s,{className:"ps-danger",children:[o.jsx(Es,{children:o.jsx(Ns,{children:"Danger zone"})}),o.jsx(Dr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Fe,{variant:"danger",onClick:async()=>{if(await Yl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await en("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function YU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(_s,{id:"ps-data",children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Fe,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await en("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function QU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=hE(e.id);return r?null:o.jsxs(_s,{children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",g2]})]})]}),o.jsx(Dr,{}),o.jsx(Fs,{children:o.jsx(v2,{shares:n||[],loading:i,canRevoke:Pn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],XU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function WU({project:e,org:t}){const n=mn(),{data:r,error:i}=Nv(e.id),l=Pn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],b=async()=>{const x=await Yl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>en("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(_s,{className:"ps-people",children:[o.jsxs(Es,{children:[o.jsx(Ns,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Dr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Fe,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Cn(`/api/orgs/${t.id}/invites`),j=await Dn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>en("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Fe,{type:"button",variant:"subtle",onClick:b,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>en("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${XU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>en("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const JU="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${JU} -to set up ${l} on ${e}. ${u}${f}.`}function F2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive -bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(hi,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Wl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Wl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Wl({code:e}){const[t,n]=w.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Dn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function eV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Fe,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Wl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function tV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Fe,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function nV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function sV({onStarted:e}){const[t,n]=w.useState(""),[r,i]=w.useState("team"),[l,u]=w.useState(!0),[f,h]=w.useState(null),[m,y]=w.useState(!1),[g,b]=w.useState(""),[x,j]=w.useState(!1),S=w.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);w.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=w.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=w.useCallback(async()=>{y(!0),b("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){b((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Fe,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(nV,{data:f,name:r})]})]})}function rV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=w.useState({phase:"creating",name:t}),i=w.useRef(!1);w.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function aV({st:e}){const[t,n]=w.useState(""),[r,i]=w.useState(!1),[l,u]=w.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,b)=>{try{await navigator.clipboard.writeText(b),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const b=(await Qe("/api/orgs")).orgs[0]?.id;if(!b)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${b}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Fe,{id:"setup-open",onClick:()=>bt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Wl,{code:h}),o.jsx(Fe,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Fe,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function iV({step:e,signedIn:t,onSignIn:n}){const[r,i]=w.useState(null);return w.useEffect(()=>{e==="welcome"&&t&&bt("/setup/connect"),e!=="welcome"&&!t&&bt("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(tV,{onStart:n}),e==="connect"&&o.jsx(sV,{onStarted:l=>bt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(rV,{onDone:l=>{i(l),bt("/setup/done")}}),e==="done"&&o.jsx(aV,{st:r??{}})]})}const I2="__existing__";function oV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:I2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=w.useState(""),[u,f]=w.useState(r[0].value),[h,m]=w.useState(""),[y,g]=w.useState(!1),b=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(Oo,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&b()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Fe,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Fe,{variant:"primary",onClick:b,disabled:y,children:"Create"})]})]})})}const P2=1<<20,lV=8192;function cV(e){if(e.byteLength>P2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,lV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function Jl(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await HM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>P2)return{kind:"too-large",size:n};const r=cV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function ko(e,t,n){return n?Jl(e,n,t):e+"file?path="+encodeURIComponent(t)}function uV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return tt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&uV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function ec(e,t,n){return ly(t?Jl(e,t):"",["blob",e,t],n&&!!t,!0)}function U2(e,t,n,r){const{data:i,isError:l,refetch:u}=tt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const dV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function fV(e,t=!0,n){const r=mn(),i=w.useRef(n);i.current=n,w.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>dV(M,U)),H=(U,Z,X)=>{if(!Z)return;const Q=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Q.has(be)?!1:(Q.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,X)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},b=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],X=>X&&kU(X,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const X of L.paths)r.invalidateQueries({queryKey:["render",e,X]}),r.invalidateQueries({queryKey:["text",ko(e,X)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),b(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),b(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>b(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function hV(e,t,n=!0){const[r,i]=w.useState([]),l=w.useRef(t);return l.current=t,w.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Cn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),w.useEffect(()=>{if(n)return()=>{Cn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function mV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` -`).filter(f=>f.trim()).join(` -`),t.push(i),i=null)};for(const u of e.split(` -`)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function V2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function VB(e,t=90){const n=e.body.split(` -`).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const H2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function pV(e){const t=cy(e),n=[];let r=0;return e.split(` -`).forEach((i,l)=>{const u=H2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:V2(t,r)?.name??"",line:l+1})}r+=i.length+1}),n}function gV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` -`)}function HB(e){return e.split(` -`).filter(t=>H2.exec(t)?.[1]===" ").map(t=>t.trim())}function qB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const vV=256;function BB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=vV&&t*5new TextEncoder().encode(e).length;function xV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function bV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function wV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function GB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function q2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=wV;function B2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:q2(e)})}function SV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:q2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function G2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function jV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const CV=(e,t)=>Math.abs(e-t)<1.01,_V=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Ol;const gp=()=>{if(Ol!==void 0)return Ol;if(typeof navigator>"u")return Ol=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ol=!0;const e=navigator.maxTouchPoints;return Ol=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},EV=e=>e,NV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},RV=typeof window>"u"?!0:"onscrollend"in window,MV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&RV;let u=0;const f=l?null:_V(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},TV=(e,t)=>MV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),OV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},AV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},DV=AV;class zV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:EV,rangeExtractor:NV,onChange:()=>{},measureElement:OV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const b in n){const x=n[b];x!==void 0&&(l[b]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const b=u.count,x=l.count,j=this.getMeasurements(),S=b>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=b>0?((i=j[b-1])==null?void 0:i.key)??u.getItemKey(b-1):null;if(x!==b||b>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=b>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>b&&this.isAtEnd(u.scrollEndThreshold)&&(b===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[b,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=mo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=mo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=mo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const b=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&b>0&&A.set(N.subarray(0,b*2)),N=A,this._flatMeasurements=N}let R;if(b===0)R=r+i;else{const A=b-1;R=N[A*2]+N[A*2+1]+m}for(let A=b;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=mo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=$V(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=mo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const b=this.measurementsCache[n];if(!b)return;h=b.key,f=b.start,u=b.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const b=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=b?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=K2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&CV(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const K2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function LV(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function $V(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=LV(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?w.useLayoutEffect:w.useEffect;function FV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=w.useReducer(m=>m+1,0)[1],l=w.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const b=!!m.options.horizontal,x=y.mode==="transform",j=b?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=b?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const b=l.current;let x=!0;if(b.enabled){u(m);const j=m.range,S=b.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(b.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=w.useState(()=>{const m=new zV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const b=m.getTotalSize();g.lastSize=b;const x=m.options.horizontal?"width":"height";y.style[x]=`${b}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function IV(e){return FV({observeElementRect:kV,observeElementOffset:TV,scrollToFn:DV,...e})}function PV({...e}){return o.jsx(tz,{"data-slot":"context-menu",...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu-trigger",...e})}function VV({className:e,...t}){return o.jsx(sz,{children:o.jsx(rz,{"data-slot":"context-menu-content",className:nt("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function HV({className:e,inset:t,variant:n="default",...r}){return o.jsx(az,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function qV({className:e,...t}){return o.jsx(iz,{"data-slot":"context-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function BV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const GV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Pr(e){const t=GV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function KB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Z2=-.005,jg=-.005,Y2=-.01,Cg=1,Il=[0,.9,.8,.6,.7],KV=.5,ZV=2,YV=1,QV=5,XV=5,WV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function JV(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function tH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,nH=2e5;function X2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=JV(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),b=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:b>0?g.slice(0,b):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=nH&&Ju.clear(),Ju.set(e,t),t}let Pl=new Int32Array(64);function aS(e,t,n){Pl.length0&&(N=Math.max(h[y+_-1]+Il[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[b+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[b+_]=E=E+S;[m,g]=[g,m],[y,b]=[b,y]}return h[y+l-1]}function rH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let b=0;b0&&(N=Math.max(m[_-l-1]+Il[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let b=i-1,x=l-1;b>=0;b--)for(;x>=0;x--){const j=b*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=b>0&&x>0&&m[j]===h[j-l-1]+Cg,y[b]=n+x--;break}}return r.push(...y),m[i*l-1]}function aH(e){const t=eH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=XV){const l=new Set;for(let u=0;u=0;i--){const u=Sa[i+1]>n?t.lastIndexOf(e[i],Sa[i+1]-1):-1;if(u=0;i--)Sa[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function oH(e,t,n,r){if(!iH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-YV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=oH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=ZV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function lH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function W2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=aH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(QV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const b=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>b&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:lH(_,t[S])}}),total:h+x.size}}const cH=[/^\./,/^_lint\.py$/];function oS(e){return cH.some(t=>t.test(e))}const uH=5;function J2(e){return"\0sys:"+e}const dH=e=>e&&Date.parse(e)||0;function fH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[b,x]=f(g);m+=b,y=Math.max(y,x)}else{l.add(g.path),Pr(g.path)&&u.push(g.path);const b=dH(g.time);i.set(g.path,b),t>0&&b>t&&m++,y=Math.max(y,b)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Pr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function hH(e,t){const n=Pr(e);return!!n&&t.conflicts.has(n.original)}function mH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??uH,f=[],h=(b,x)=>(i.latest.get(x.path)||0)-(i.latest.get(b.path)||0),m=b=>l===b||l.startsWith(b+"/"),y=(b,x)=>{for(const j of b)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(b,x)=>{const j=(b.children||[]).filter(_=>!hH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(b.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:b.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=J2(b.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:b.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const pH=5,gH=100;function vH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=W2(e,u.map(X2),{limit:h,nameOnly:!0});return{list:m.map(b=>{const x=u[b.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:b.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,pH),l=r([...n].map(u=>u.path).filter(u=>!Pr(u)),!1,gH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function eN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function bH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function wH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=w.useRef(null),[g,b]=w.useState(()=>new Set),[x,j]=w.useState(null),[S,E]=w.useState(null),_=w.useRef(0),N=w.useRef(""),R=w.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=w.useMemo(()=>mH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=IV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});w.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>b(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(J2(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||cs()};return o.jsxs(PV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Xv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(UV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),bH(q.currentTarget);return}wp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:yH})})]}),o.jsx(VV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]},U.key)})})})}const SH=5,Sp=8;function jH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=w.useState(!1);w.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=w.useMemo(()=>vH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,SH),g=i?f:f.slice(0,Sp),b=[...y,...g],x=t.trim();w.useEffect(()=>{AU(b.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||cs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:eN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),b.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===b.length?" sel":""),role:"option","aria-selected":r===b.length,onMouseEnter:()=>J1(b.length),onClick:()=>So(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Zl?"⌘↵":"Ctrl+↵"})]})]})}function CH(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function _H(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&!g&&(b.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:b=>{b.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function EH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function NH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function mi(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function kH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function RH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function tN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=kH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",RH(r.until));const i=n.toString();return i?"&"+i:""}function MH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function TH(e){return e?.range&&uy[e.range]||30}function OH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===mi(t))return"Today";if(e===mi(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function nN(e,t){return t||(e==="add"?"":void 0)}function Si(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function AH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` -`);return t[t.length-1]===""&&t.pop(),t}const DH=4e6;function zH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>DH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let b=0,x=0;for(;b=g[b][x+1]?m(b++):y(x++);for(;br.op==="+").length,del:n.filter(r=>r.op==="-").length}}function ZB(e,t){if(e===t)return null;const n=Math.min(e.length,t.length);let r=0;for(;ri.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>w.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function $H({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=C2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",yi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",H_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:$r,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",$r]})]})]})]})}function FH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=w.useMemo(()=>LH(t),[t]),u=fy(),[f,h]=w.useState(!1),m=PH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(b=>o.jsx("li",{className:(b.level===3?"sub":"")+(b.id===m?" on":""),children:o.jsx("a",{href:"#"+b.id,"aria-current":b.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(b.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+b.id))},children:b.text})},b.id))})]}),r&&y>0&&o.jsx(IH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(b=>o.jsxs("div",{children:[o.jsx("dt",{children:b.key}),o.jsx("dd",{children:b.code?o.jsx("code",{children:b.value}):b.value})]},b.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:b=>{b.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function IH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:$r,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",$r]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function PH(e){const[t,n]=w.useState(e[0]?.id??null);return w.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const sN=5e3;function UH(e,t,n=sN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function qH(e=[]){return`BearDrive found ${rN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function BH(e=[]){return`This file contains ${rN(e)}.`}const fS=6;function GH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=w.useState(!1),h=w.useMemo(()=>pV(r),[r]),m=w.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(KH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Dn(gV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(ZH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function KH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(B2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function ZH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=w.useState(""),{data:f}=tt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const b=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Cn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+b+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const b=(g.size??0)===0;return o.jsxs("li",{className:b?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(b?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let aN=null,iN=null,hS=null,mS=null;const oN=()=>hS??=US(()=>import("./Editor-m3pwH2dA.js"),__vite__mapDeps([0,1,2,3])).then(e=>aN=e).catch(e=>{throw hS=null,e}),lN=()=>mS??=US(()=>import("./VisualEdit-DpNpdB4J.js"),__vite__mapDeps([4,1,2,3])).then(e=>iN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=w.useState(e),[i,l]=w.useState(!1),[u,f]=w.useState(0);return w.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){oN(),lN()}const YH=2e3;function gS(e,t,n){const r=ko(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function QH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=ko(t,n,r);w.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(t7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(n7,{...e}):ui.test(n)?o.jsx(r7,{...e}):Or.test(n)?o.jsx(XH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):I_.test(n)?o.jsx(i7,{src:l,alt:n,version:r,onRendered:e.onRendered}):P_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):n3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(WH,{...e,fileURL:l})}function XH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=U2(t,n,e.fileURL,r),u=l.url,f=w.useRef(l.fresh);f.current=l.fresh;const[h,m]=w.useState(0);return w.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(b=>b+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function WH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return w.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(JH,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${yi(u.size)}).`:"No preview for this file type."}):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function e7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function t7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;w.useEffect(()=>l?.(),[l]);const u=e7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function n7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Or.test(n)&&!e.editSource,l=ko(t,n),u=U2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=w.useMemo(()=>Date.now(),[l]),[y,g]=w.useState(null),{refetch:b}=f;w.useEffect(()=>{let Pe=!0;return b({cancelRefetch:!0}).then(_t=>{Pe&&_t.status==="success"&&!_t.isRefetchError&&g(l)}),()=>{Pe=!1}},[b,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-YH?f.data:void 0,S=pS(aN,oN),E=pS(iN,lN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=w.useState("clean"),[M,L]=w.useState("connecting"),H=ui.test(n),U=mV(n),[Z,X]=w.useState(H?"write":"markdown"),[Q,ae]=w.useState(null),[le,be]=w.useState(0),[$,q]=w.useState(null),[,V]=w.useState(0),[ee,K]=w.useState([]),[O,D]=w.useState(new Set);w.useEffect(()=>{const Pe=setInterval(()=>V(_t=>_t+1),5e3);return()=>clearInterval(Pe)},[]),w.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=w.useRef("");P.current=Q?.text??"",w.useEffect(()=>{if(!B)return;const Pe=()=>{const _t=[];B.awareness.getStates().forEach(rt=>{const sn=rt.user?.name;sn&&_t.push(sn)}),K([...new Set(_t)]);const Ut=cy(P.current),En=new Set;for(const rt of B.remoteCursors()){const sn=V2(Ut,rt.pos);sn&&En.add(sn.name)}D(En)};return Pe(),B.awareness.on("change",Pe),()=>B.awareness.off("change",Pe)},[B]);const[I,re]=w.useState(!1),he=w.useRef(0),we=mn(),_e=w.useRef(null),ve=async Pe=>{try{const _t=await Rf(l),Ut=_e.current;if(_t.kind==="text"&&Ut){const En=Ut.merge(_t.text,_t.sha,{held:Pe});re(En==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},Ae=w.useRef(0),Ze=Pe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Pe.split("/").pop()??Pe))};w.useEffect(()=>{const Pe=_t=>{if(_t.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ae.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Pe),()=>window.removeEventListener("bdrive:changed",Pe)},[n,i]);const dt=M==="offline",st=dt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:dt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+bV($):"");return w.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),st]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Pe=>o.jsx(B2,{name:Pe,title:Pe+" is editing"},Pe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,st,le,ee,r]),w.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),dt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Pe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Pe,"aria-selected":Z===Pe,className:Z===Pe?"on":"",onClick:()=>X(Pe),children:[o.jsx(ge,{name:Pe==="write"?"pencil":Pe==="markdown"?"code":"eye"}),Pe==="write"?"Write":Pe==="markdown"?"Markdown":"Preview"]},Pe))}),H&&!i&&o.jsx(GH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Fe,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:Ze,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Pe=>{Ae.current=Pe},me:e.me,onRendered:e.onRendered}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Pe=>Pe.path),onInfo:ae,onPending:be,handle:_e,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:Ze,onExternal:Pe=>{re(Pe==="blocked"),Pe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Pe=>{Ae.current=Pe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(s7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",yi(yV(Q?.text??x.text))," ·"," ",xV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function s7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=tt(hy(t,n)),f=w.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function r7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=tt(hy(n,r,i)),b=w.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=w.useState(null),E=w.useRef(null);if(w.useEffect(()=>{if(E.current!==b&&S(null),E.current=b,!IR(b))return;let R=!1;return PR(b,x==="light"?UR:VR).then(T=>{R||S(T)}),()=>{R=!0}},[b,x]),w.useEffect(()=>{b&&m?.()},[b,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(cN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(FH,{html:b,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(a7,{findings:y.findings}),!t&&N,o.jsx($H,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??b},onClick:R=>my(R,r,h)}),t&&N]})}function cN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function a7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:BH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(U_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(U_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=s3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Xn(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function i7(e){const[t,n]=w.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=tt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});w.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=w.useMemo(()=>i&&u!=null?UH(u,i,sN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(o7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function o7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function l7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:Jl(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:Jl(e,r,i,!0),children:"download this version"})]})}function uN({apiBase:e,path:t,prev:n,cur:r}){const i=ec(e,n,!0),l=ec(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=w.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(l7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,b)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},b))})]})}function c7(e,t,n,r){const i=ec(e,t,r&&!!t),l=ec(e,n,r&&t!==void 0);return w.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function u7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const d7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function f7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=w.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:d7.map(([g,b])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:b},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(uN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?nN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(h7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(m7,{apiBase:e,sha:y})]})]})}function h7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=tt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=w.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:Jl(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function m7({apiBase:e,sha:t}){const n=ec(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` -`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const p7={add:"added",edit:"edited",delete:"deleted"};function dN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:b,idx:x}){const[j,S]=w.useState(!1),[E,_]=w.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=H_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=c7(t,nN(N,r?.prev),e.blob,!!b&&N!=="delete"&&!!e.blob),V=N!=="delete"?Pr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":Si(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:p7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(u7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?yi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(dN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(uN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function fN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,b)=>Number(b.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(b.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:$r}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let b="";if(g.dir){const _=(g.children||[]).length;b=_+(_===1?" item":" items")}else b=[g.size?yi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(b=Wu(x)+(b?" · "+b:""));const j=g.dir?null:Pr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":C2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+xU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+$r,title:Wu(x)+" in 30 days. "+$r}),o.jsx("span",{className:"dl-meta",children:b})]},g.path)})}),e.hub&&o.jsx(g7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function g7(e){const t=MU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return w.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const v7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],hN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=hN.filter(e=>e.value!=="");function y7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=fE(e.id),{data:m}=Nv(e.id),{data:y}=dE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",b=Pn(e.perm,"admin"),x=Pn(e.perm,"write"),j=n?t+"/":t,S=w.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=G2(S,j),[N,R]=w.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=w.useState(!1),[L,H]=w.useState(""),[U,Z]=w.useState("read"),[X,Q]=w.useState(null),[ae,le]=w.useState(""),be=w.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Dn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(Oo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!b||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:hN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||b)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:D2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!b||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),b&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Fe,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Fe,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:qH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Fe,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Fe,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:v7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:m2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Fe,{ref:be,variant:"primary",onClick:()=>Dn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Fe,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function x7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",g2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:p2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Fe,{variant:"subtle",onClick:()=>Dn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Fe,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>y2(r,n),children:"Revoke"})]})]},r.token))]})}function b7(e,t,n){return tt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function mN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,b)=>b===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Cn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Cn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Ll(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function S7(e,t){const n=Ll(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Ll(e),l=w7(r,n,Ll(t.prefix||"").text,Ll(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function j7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const C7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function pN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(C7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=pN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Ll(f).text)return null;const h={quote:f,...j7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` -`).length),h}function E7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function N7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=w.useRef(null),[b,x]=w.useState(null);w.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=w.useState(null),[E,_]=w.useState(""),[N,R]=w.useState(!1),T=mN(t),A=w.useMemo(()=>vN(l),[l]),M=w.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);w.useEffect(()=>{S(null),_("")},[n]);const L=w.useRef(new Map),[H,U]=w.useState([]),[Z,X]=w.useState(0);w.useEffect(()=>{if(r||!b)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(b,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(b),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,b]),w.useLayoutEffect(()=>{if(r||!b)return;const V=new Map;for(const B of M){const P=B.anchor.quote?_7(b,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=b.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,b]);const Q=w.useRef(null);w.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Q.current?V.set(ed,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),w.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),w.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),w.useLayoutEffect(()=>{if(r||!b)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!b.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(b,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=E7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return b.addEventListener("mouseup",V),b.addEventListener("keyup",V),b.addEventListener("click",ee),()=>{b.removeEventListener("mouseup",V),b.removeEventListener("keyup",V),b.removeEventListener("click",ee)}},[r,b,i,f,h]);const ae=w.useCallback(()=>b?.querySelector("iframe.htmlview")??null,[b]),le=w.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=w.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);w.useEffect(()=>{r&&be()},[r,be]),w.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),w.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),w.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),w.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?T7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(gN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Fe,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Fe,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function k7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,b=mN(t),x=w.useMemo(()=>vN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=w.useState("open"),N=!!i&&S.some(U=>U.id===i);w.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=w.useState(""),[M,L]=w.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await b.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Fe,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(R7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:b,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Fe,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function R7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=w.useState(""),[y,g]=w.useState(!1),b=w.useRef(null);w.useEffect(()=>{n&&b.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:b,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(gN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:M7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Fe,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Fe,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Fe,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function gN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function M7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function vN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function T7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,O7=.9,A7=.8,D7=.17,Cp=.1,_p=.999,z7=.9999,L7=.99,$7=/[\\\/_+.#"@\[\(\{&]/,F7=/[\\\/_+.#"@\[\(\{&]/g,I7=/[\s-]/,yN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:L7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,b,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:$7.test(e.charAt(m-1))?(g*=A7,x=e.slice(i,m-1).match(F7),x&&i>0&&(g*=Math.pow(_p,x.length))):I7.test(e.charAt(m-1))?(g*=O7,j=e.slice(i,m-1).match(yN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=D7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=z7)),(gg&&(g=b*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(yN," ")}function P7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Al='[cmdk-group=""]',Ep='[cmdk-group-items=""]',U7='[cmdk-group-heading=""]',xN='[cmdk-item=""]',NS=`${xN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",go="data-value",V7=(e,t,n)=>P7(e,t,n),bN=w.createContext(void 0),pc=()=>w.useContext(bN),wN=w.createContext(void 0),vy=()=>w.useContext(wN),SN=w.createContext(void 0),jN=w.forwardRef((e,t)=>{let n=vo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=vo(()=>new Set),i=vo(()=>new Map),l=vo(()=>new Map),u=vo(()=>new Set),f=CN(e),{label:h,children:m,value:y,onValueChange:g,filter:b,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ls(),R=ls(),T=ls(),A=w.useRef(null),M=J7();ji(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),ji(()=>{M(6,ae)},[]);let L=w.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let _e=document.getElementById(T);_e?_e.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var _e;n.current.selectedItemId=(_e=le())==null?void 0:_e.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let _e=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,_e);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=w.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:V7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let _e=D.get(we);he=Math.max(_e,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let _e=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(_e))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Al}[${go}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(go);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",_e=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,_e);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let _e of we)if(n.current.filtered.items.get(_e)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Al))==null?void 0:B.querySelector(U7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${xN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(go))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(go))}function V(D){let B=le(),P=B?.closest(Al),I;for(;P&&!I;)P=D>0?X7(P,Al):W7(P,Al),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(go)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return w.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},w.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:tq},h),Of(e,D=>w.createElement(wN.Provider,{value:L},w.createElement(bN.Provider,{value:H},D))))}),H7=w.forwardRef((e,t)=>{var n,r;let i=ls(),l=w.useRef(null),u=w.useContext(SN),f=pc(),h=CN(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;ji(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=_N(i,l,[e.value,e.children,l],e.keywords),g=vy(),b=Ma(M=>M.value&&M.value===y.current),x=Ma(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);w.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return w.createElement(ot.div,{ref:Co(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!b,"data-disabled":!!E,"data-selected":!!b,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),q7=w.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ls(),f=w.useRef(null),h=w.useRef(null),m=ls(),y=pc(),g=Ma(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);ji(()=>y.group(u),[]),_N(u,f,[e.value,e.heading,h]);let b=w.useMemo(()=>({id:u,forceMount:i}),[i]);return w.createElement(ot.div,{ref:Co(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&w.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>w.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},w.createElement(SN.Provider,{value:b},x))))}),B7=w.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=w.useRef(null),l=Ma(u=>!u.search);return!n&&!l?null:w.createElement(ot.div,{ref:Co(i,t),...r,"cmdk-separator":"",role:"separator"})}),G7=w.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=Ma(m=>m.search),f=Ma(m=>m.selectedItemId),h=pc();return w.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),w.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),K7=w.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=w.useRef(null),u=w.useRef(null),f=Ma(m=>m.selectedItemId),h=pc();return w.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,b=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return b.observe(m),()=>{cancelAnimationFrame(g),b.unobserve(m)}}},[]),w.createElement(ot.div,{ref:Co(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>w.createElement("div",{ref:Co(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Z7=w.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return w.createElement(Gg,{open:n,onOpenChange:r},w.createElement(Zg,{container:u},w.createElement(Yg,{"cmdk-overlay":"",className:i}),w.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},w.createElement(jN,{ref:t,...f}))))}),Y7=w.forwardRef((e,t)=>Ma(n=>n.filtered.count===0)?w.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),Q7=w.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return w.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>w.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(jN,{List:K7,Item:H7,Input:G7,Group:q7,Separator:B7,Dialog:Z7,Empty:Y7,Loading:Q7});function X7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function W7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function CN(e){let t=w.useRef(e);return ji(()=>{t.current=e}),t}var ji=typeof window>"u"?w.useEffect:w.useLayoutEffect;function vo(e){let t=w.useRef();return t.current===void 0&&(t.current=e()),t}function Ma(e){let t=vy(),n=()=>e(t.snapshot());return w.useSyncExternalStore(t.subscribe,n,n)}function _N(e,t,n,r=[]){let i=w.useRef(),l=pc();return ji(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(go,f),i.current=f}),i}var J7=()=>{let[e,t]=w.useState(),n=vo(()=>new Map);return ji(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function eq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&w.isValidElement(t)?w.cloneElement(eq(t),{ref:t.ref},n(t.props.children)):n(t)}var tq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function nq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:nt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function sq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(Q_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:nt("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function rq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:nt("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function aq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:nt("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const iq=40,oq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function lq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=w.useState("");w.useEffect(()=>{e&&u(i)},[e,i]);const f=w.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=w.useMemo(()=>h?f.map(x=>X2(x.label)):[],[f,h]),y=w.useMemo(()=>W2(l,m,{limit:iq}).hits,[l,m]),g=w.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,oq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),b=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(Oo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(nq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(sq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(rq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>b(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(aq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>b(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const EN=e=>"bdrive.recent."+e,cq=12;function uq(e,t,n,r=cq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function dq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,fq=[],Ag=new Set;function hq(e){return Ag.add(e),()=>{Ag.delete(e)}}function NN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(EN(e))}catch{}t=dq(n),Og.set(e,t)}return t}function mq(e,t){const n=uq(NN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(EN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function kN(e){return w.useSyncExternalStore(hq,()=>e?NN(e):fq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function RN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function pq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function gq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),Si(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function vq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function yq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&Si(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const xq=15*6e4;function bq(e){const t=[];for(const n of e){const r=Pr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function wq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Ps(u);j2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function Sq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function jq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:Sq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const Cq=200,_q=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Eq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=_q(l),f=sy(l),h=kN(l),[m,y]=w.useState(""),g=M2(l),b=tt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+Cq),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=tt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=w.useMemo(()=>g.data?.entries||[],[g.data]),S=w.useMemo(()=>vq(j,b.data?.entries||[]),[j,b.data]),E=w.useMemo(()=>gq(j,j.length>=$d),[j]),_=w.useMemo(()=>yq(S,i?.email),[S,i?.email]),N=w.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=w.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=w.useMemo(()=>{const U=bq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(wq(n,r))},[n,x.data,r,i]),A=w.useMemo(()=>jq(e.tree,r),[e.tree,r]),M=w.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===Si(Z)):S;return{list:U,items:RN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(F2,{project:t,existing:e.existing})});const L=U=>Xn(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:pq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${po(f)}.`:`Since your last visit ${po(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Un(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",po(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(Nq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Un(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),b.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):b.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=Si(Z),ae=Q?Mf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${yy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Un(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:po(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Wl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Un(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Un(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Un(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(fN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function Nq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Un(t(e.path)),children:l})]})}function kq(e,t){return tt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Rq=["all","human","agent","share"],MN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},TN="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Mq(){try{const e=AS(localStorage.getItem(TN));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:w2,stale:S2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Tq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Tq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function ON({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Oq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=tt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Aq(e){const t=Oq(e.apiBase,e.flatFiles),[n,r]=w.useState("all"),[i,l]=w.useState(Mq);w.useEffect(()=>{try{localStorage.setItem(TN,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Un(e.installHref),children:"Set up a device →"})]})]});const b=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=bU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Rq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),MN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${$r}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+$r}),o.jsx(Dq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Iq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Kq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Xq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(Jq,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,b&&b.length>0&&o.jsx(sB,{devices:b,lens:n})]})}function Df(e){const[t,n]=w.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function Dq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),b=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(b,"time")}`:"no empty file is being read"})]})]})}function zq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function Lq({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function $q({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Fq=8;function Iq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Fq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx(Lq,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(ON,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx($q,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:zq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Pq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const b=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/b;x=Math.max(x,S/b,b/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const b=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/b;m?h.push({item:j.it,x:t,y:n+x,w:b,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:b}),x+=S}m?(t+=b,r-=b):(n+=b,i-=b)}return h}function Uq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Vq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function Hq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function AN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function qq(e,t){const n=new Map;for(const r of e){const i=AN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:Hq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Bq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Gq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,DN=8;function Kq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=w.useState(null);w.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=SU(e.map(_=>_.days)),m=!!h&&jU(h.min,h.max),y=Uq(h?h.max:0),g=l===null?e:e.filter(_=>AN(_.path,f)===l),b=l===null?qq(e,f):Bq(g,l||f),x=Pq(b,0,0,Np,DS),j=new Set(b.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,DN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...b].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Vq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Gq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Zq,{range:h,flat:m,edges:y})]})}function Zq({range:e,flat:t,edges:n}){if(!e)return null;const r=CU(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",DN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Yq={agent:"What agents load",human:"What people open",share:"What share links serve"},Qq=8;function Xq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Qq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Wq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Wq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Yq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(ON,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function Jq({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),b=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=NU(b.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const eB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function tB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function nB({name:e}){const t=e==="users"?bv:e==="off"?w3:p3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function sB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,b]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+b);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,b)=>g+b,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=tB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",MN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const b=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+eB(b),title:`${y.name} × ${g.name||"(root)"}: ${Us(b,"agent read")}/30d`,children:b||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(nB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const rB=[["","Everyone"],["agent","Agents"],["human","People"]],aB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function iB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=w.useState(t?.q??""),h=w.useRef(!1);w.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),w.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=w.useState(!1),g=m||!!t?.since||!!t?.until,b=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=aB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:rB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:b,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function oB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function lB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function cB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=w.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),b=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=w.useMemo(()=>b+tN(m),[b,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=FM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=w.useState(!1),[L,H]=w.useState(0);w.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),dB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=w.useRef(new Set),X=w.useRef(new Map);w.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),w.useEffect(()=>{S&&l?.()},[S,l]);const Q=w.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of lB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Ae])=>({id:ve,name:Ae})).sort((ve,Ae)=>ve.name.localeCompare(Ae.name)),le=e.onFilters&&o.jsx(iB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(mB,{apiBase:t,scope:b,filters:m}),$=w.useMemo(()=>RN(Q),[Q]),q=w.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=w.useState(null);if(w.useEffect(()=>ee(null),[x]),w.useEffect(()=>{const ve=Ae=>{if(Ae.metaKey||Ae.ctrlKey||Ae.altKey||Ae.defaultPrevented)return;const Ze=Ae.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Ae.key==="Escape"&&V!==null){ee(null);return}if(Ae.key!=="j"&&Ae.key!=="k"||!q.length)return;Ae.preventDefault();const dt=V===null?-1:q.indexOf(V),st=Ae.key==="j"?Math.min(q.length-1,dt+1):Math.max(0,dt===-1?0:dt-1);ee(q[st])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),w.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(hB,{onRetry:U,timedOut:!E}):_&&o.jsx(fB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Ae=ve+1;Ae{const Ae=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Ae&&Ae===O.get(Q[ve].path)?void 0:Ae},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Ae=K(ve);return Ae&&Ae!==O.get(Q[ve].path)?Ae:void 0},I=oB(m,ae);let re="";const he=new Map;for(const ve of Q){const Ae=mi(new Date(ve.time));he.set(Ae,(he.get(Ae)??0)+1)}const we=V!==null?Q[V]:void 0,_e=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Ae])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Ae),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Ae)=>{const Ze=mi(new Date(Q[ve.i].time)),dt=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===mi(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const st=ve.run?o.jsx(gB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Ae):o.jsx(gy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return dt?[dt,st]:st}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(pB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:_e>0?()=>ee(q[_e-1]):void 0,onNext:_eee(q[_e+1]):void 0},V):Q.length>0&&o.jsx(uB,{})]})}function uB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const dB=1e4;function fB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function hB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function mB({apiBase:e,scope:t,filters:n}){const r=TH(n),i=tN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(MH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=tt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=mi(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),b=f.days.length,x=b?b===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[b-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=OH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function pB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=Si(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:Si(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(mi(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Dn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(f7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function gB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[b,x]=w.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=tt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=vB(Math.min(...L),Math.max(...L)),U=AH(Math.max(...L)-Math.min(...L)),Z=yy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(b?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":b,title:b?"Collapse this run":"Expand this run",onClick:()=>x(!b),children:o.jsx(ge,{name:b?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(dN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),b&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(gy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function vB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function yB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const xB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const bB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?bB:0;return r-l}function wB(e){const t=e.width??xB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const b=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",b),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",b),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const SB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function jB(e,t){return e.key!==t||e.attempts>=SB?null:(e.attempts++,e.want)}function CB(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function EB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function zN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=i$(Ov()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=_2(n,!i||!!l),b=!i||!!l,{people:x,setPeople:j}=hV(n,r.path??"",b);fV(n,b,j);const S=RU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=fE(i&&l?l?.id:void 0),_=w.useMemo(()=>E?.folders||[],[E]),N=w.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=kq(n,T);w.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;w.useEffect(()=>{i&&l&&Z&&!L&&mq(l.id,M)},[i,l,Z,M,L]),w.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ui.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=tt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=w.useState(null);w.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),bt(Xn(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=w.useState(()=>new Set),V=w.useRef(!0);w.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),w.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const $e of CH(H))Ee.add($e);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=w.useCallback(ie=>{q(Ee=>{const $e=new Set(Ee);return $e.has(ie)?$e.delete(ie):$e.add(ie),$e})},[]),K=w.useRef(null),O=w.useRef(new Map),D=w.useRef(IS("",0)),B=w.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=jB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);w.useEffect(()=>{D.current=IS(u,l$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=w.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),CB(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=w.useCallback((ie,Ee)=>{bt(Xn(ie,l?.id,Ee)),cs()},[l?.id]),re=w.useCallback(ie=>bt(cn("history",l?.id,ie)),[l?.id]),[he,we]=w.useState(""),[_e,ve]=w.useState(!1),[Ae,Ze]=w.useState(!1),[dt,st]=w.useState(!1),[Pe,_t]=w.useState("");w.useEffect(()=>t3(ie=>{_t(ie??""),st(!0)}),[]);const Ut=w.useRef(null),En=w.useRef(null),rt=e.panel??null,sn=!rt&&i&&!!l&&(Z||U)&&Pn(l.perm,"write"),Hs=ie=>G2(_,ie)?.me,At=!rt&&Z&&!L&&(!i||!!l&&Pn(Hs(M)??l.perm,"write")),Dt=!!r.editing&&At;w.useEffect(()=>{if(!At||!Z||Dt)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>jp())},[At,Z,Dt]);const[$t,hr]=w.useState(!1);w.useEffect(()=>{hr(!1)},[M,L]);const Ms=w.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let $e=0;$eTs||[],[Ts]),dn=qs.filter(ie=>!ie.resolved).length,[z,Y]=w.useState(!1),[W,de]=w.useState(null),[me,xe]=w.useState(!1),Ce=w.useCallback(()=>Y(!0),[]);w.useEffect(()=>{de(null),xe(!1)},[M]),w.useEffect(()=>{r.comment&&(Y(!0),de(r.comment))},[r.comment]);const Se=!!r.full&&!r.view&&!!M&&!U&&!rt,[Te,it]=w.useState(null),Ct=w.useRef(null),Kt=w.useRef(null),Et=w.useRef(!1);w.useEffect(()=>{Et.current=!1},[M]);const Le=w.useCallback(()=>{Et.current=!0,bt(Xn(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),ft=w.useCallback(()=>{Et.current?(Et.current=!1,history.back()):bt(Xn(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);w.useLayoutEffect(()=>{if(Se)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),xi(),()=>{document.body.classList.remove("full-view"),xi()}},[Se]),w.useEffect(()=>{if(!Se)return;const ie=Ee=>{Ee.key==="Escape"&&!dt&&ft()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Se,dt,ft]);const St=w.useRef(!1);w.useEffect(()=>{Se?Kt.current?.focus():St.current&&Ct.current?.focus(),St.current=Se},[Se]);const{data:zt}=hE(l?.id,i&&!!l),zn=w.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),Nt=Z?(zt||[]).filter(ie=>ie.path===M):[],{data:Nn}=tt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),fs=t.desktop&&l?Nn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,kn=w.useCallback(async()=>{if(!fs)return;const ie=fs+window.location.pathname,Ee=await Dn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[fs]),pn=!rt&&i&&!!l,Vr=!rt&&Z&&!r.view,Rn=!rt&&Z,La=Rn&&!I_.test(M)&&!id.test(M)&&!Or.test(M),$a=Rn&&!id.test(M)&&!Dt,Bs=!rt&&(Z||i&&!!l&&U),rn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),fn=!Or.test(M),Hr=ko(n,M,L)+"&print=1",Fa=w.useCallback(()=>{Ze(!1),fn?window.print():En.current?.click()},[fn]),Do=w.useCallback(async()=>{try{const ie=await Rf(ko(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Dn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),zo=w.useCallback(()=>ve(!0),[]),[yc,qr]=w.useState(""),mr=i&&!!l&&Pn(l?.perm,"write"),Br=w.useCallback(async(ie,Ee,$e)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+($e?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){qr(ie+Ee);try{await Cn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(ht){Ne("Restore failed: "+ht.message,!0)}finally{qr("")}}},[n,f]),[Gr,Kr]=w.useState(""),Gs=w.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Kr(ie);try{await Cn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Kr("")}}},[n,f]),[Zt,Lo]=w.useState(""),xc=w.useCallback(async ie=>{const Ee=ie.session||ie.note,$e=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ee);try{const ht=await Cn(n+"undo-run",{...$e,preview:!0}),gn=new Set(ht.changed_after);if(!ht.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",ht.undone.length," file",ht.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:ht.undone.map(Os=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Os.path}),gn.has(Os.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Os.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Os.path))}),gn.size>0&&o.jsxs("div",{className:"undo-warn",children:[gn.size," file",gn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",gn.size===1?"that change":"those changes"," too."]}),ht.skipped.length>0&&o.jsxs("div",{children:[ht.skipped.length," already hold",ht.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),ht.refused.length>0&&o.jsxs("div",{children:[ht.refused.length," path",ht.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",ht.refused.join(", "),"."]})]}),"Undo run",!0))return;const ms=await Cn(n+"undo-run",$e);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Va=ms.skipped.length?`, skipped ${ms.skipped.length} (already current)`:"";Ne(`Undid ${ms.undone.length} file${ms.undone.length===1?"":"s"}${Va}.`)}catch(ht){Ne("Undo failed: "+ht.message,!0)}finally{Lo("")}},[n,f]),hs=w.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);w.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),_t(""),st($e=>!$e))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const Zr=w.useCallback(()=>{const ie=[],Ee=$e=>ie.push($e);if(i&&l){const $e=l.id,ht=Tn=>()=>{e.onClosePanel?.(),bt(Tn)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:ht("/"+$e)});const gn=(Tn,ms,Va)=>Ee({icon:Tn,label:ms,kind:"page",group:"Go to",run:ht(Va)});gn("activity","Activity",cn("history",$e)),gn("insights","Insights",cn("dashboard",$e)),gn("gear","Settings",cn("settings",$e)),gn("laptop","Connect a device",cn("install",$e))}if(i&&l&&M){const $e=M.slice(M.lastIndexOf("/")+1),ht=(gn,Tn,ms)=>Ee({icon:gn,label:Tn,hint:$e,kind:"action",group:$e,run:ms});sn&&ht("share","Share",zo),ht("hist","History",hs),Z&&ht("download","Download",()=>Ut.current?.click()),$a&&ht("printer","Print",Fa),La&&ht("copy","Copy",Do)}if(i)for(const $e of e.projects||[])(!l||$e.id!==l.id)&&Ee({icon:"folder",label:$e.name,kind:"project",group:"Projects",run:()=>bt("/"+$e.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const $e of y.keys())Ee({icon:"folder",label:$e,kind:"folder",run:()=>I($e)});for(const $e of m)Pr($e.path)||Ee({icon:"doc",label:$e.path,kind:"file",run:()=>I($e.path)});return ie},[i,l,M,Z,sn,La,$a,t.auth?.enabled,y,m,e.projects,e.onClosePanel,zo,Do,Fa,hs,I]),bc=kN(i?l?.id:void 0),wc=w.useMemo(()=>bc.map(ie=>ie.path).filter(ie=>ie!==M),[bc,M]),Yt=i?l?.id:void 0;w.useEffect(()=>{if(!Yt)return;const ie=()=>hU(Yt);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[Yt]);const Sc=r.view==="history"&&!r.viewTarget;w.useEffect(()=>{Yt&&Sc&&mU(Yt)},[Yt,Sc]);const Ia=sy(Yt),Yr=w.useMemo(()=>fH(h,Ia),[h,Ia]),Jn=gU(Yt),Ln=OU(n,!!Yt&&!!t.comments&&Jn.length>0),$o=w.useMemo(()=>({comments:Ln,conflicts:Yr.conflicts}),[Ln,Yr.conflicts]),ki=w.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Fo=w.useCallback(ie=>ki.has(ie)||y.has(ie),[ki,y]),jc=w.useMemo(()=>[...y.keys()],[y]),{query:Pa}=oy(),Qr=vU();w.useEffect(()=>yg,[]);const Mn=i&&!!l&&t.upload.enabled&&Pn(l.perm,"write"),Ri=w.useCallback(ie=>!!l&&Pn(Hs(ie?ie+"/":"")??l.perm,"write"),[l,_]),Mi=w.useCallback(async ie=>{const Ee=(await Yl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const $e=(ie?ie+"/":"")+Ee;if(ki.has($e)||y.has($e)){Ne($e+" already exists",!0);return}try{await qM(n+"upload/content?path="+encodeURIComponent($e),""),await f.invalidateQueries({queryKey:["tree",n]}),bt(Xn($e,l?.id,void 0,!1,!0)),cs()}catch(ht){Ne("Could not create "+$e+": "+ht.message,!0)}},[n,ki,y,l?.id,f]),Xr=w.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mn?Mi:void 0,canCreateIn:Ri,pinned:Yt?ie=>ry(Yt).includes(ie):void 0,togglePin:Yt?ie=>W1(Yt,ie):void 0,copyPath:async ie=>{const Ee=await Dn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&Pn(l.perm,"write")?async ie=>{const Ee=(zt||[]).find($e=>$e.path===ie);if(Ee){const $e=await Dn(Ee.url);Ne($e?"Share link copied":Ee.url,!$e);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>bt(cn("dashboard",l.id,ie)):void 0,remove:mr?Gs:void 0}),[Mn,Mi,Ri,Yt,i,l,zt,I,re,mr,Gs,e.onClosePanel]);w.useEffect(()=>{if(!Ae)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Ae]);const Ks=w.useCallback(ie=>y.has(ie),[y]);let Zs="app",Ua,an;if(rt)an=rt.body;else if(r.view==="dashboard")Zs="wide",an=o.jsx(Aq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ks});else if(r.view==="history")Zs="wide",Ua="activity-page",an=o.jsx(cB,{apiBase:n,target:r.viewTarget||"",isFolder:Ks,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:mr?{onRestore:Br,busy:yc}:void 0,remove:mr?{onRemove:Gs,busy:Gr}:void 0,undoRun:mr?{onUndoRun:xc,busy:Zt}:void 0,filters:r.filters,linkFor:(ie,Ee)=>Xn(ie,l?.id,Ee),onFilters:ie=>bt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)an=ui.test(M)?o.jsx(cN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)an=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)an=o.jsx(fN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Zs=Or.test(M)||id.test(M)?"wide":"read",Ua="markdown",Se&&!ui.test(M)&&(Ua+=" bleed");const ie=Pr(M);an=o.jsxs(o.Fragment,{children:[L&&o.jsx(_B,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(EB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(QH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:Dt,editSource:$t,me:Ms,commentable:ds});return ds?o.jsx(N7,{apiBase:n,path:M,framed:Or.test(M),lines:!ui.test(M)&&!Or.test(M)&&!P_.test(M),threads:qs,focus:W,onFocus:de,onOpenPanel:Ce,picking:me,onPicking:xe,children:Ee}):Ee})()]})}else R?(m.length>0&&(Zs="wide"),an=o.jsx(Eq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):an=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(an=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),an]}));const zf=rt?rt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(NH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!Dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+yB(r.viewTarget||"",Ks):R?l.name:null,Cc=o.jsx(fi,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:zf,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(SV,{people:x,path:M}),ds&&o.jsxs(Fe,{id:"comments-btn",variant:"toolbar",className:"ghost",title:dn?`${dn} open comment${dn===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":z,onClick:()=>Y(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),dn>0&&o.jsx("span",{className:"cm-count",children:dn})]}),pn&&(Z||!M&&!r.view)&&o.jsxs(Fe,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:hs,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Fe,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{Dt||(jp(),gS(f,n,M))},onFocus:()=>{Dt||(jp(),gS(f,n,M))},title:Dt?"Stop editing":"Edit this file",onClick:()=>bt(Xn(M,l?.id,L,r.full,!Dt)),children:[!Dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:Dt?"Done":"Edit"})]}),Dt&&Or.test(M)&&o.jsx(Fe,{id:"edit-source-btn",variant:"toolbar",title:$t?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:$t?"Edit page":"Edit source"}),sn&&o.jsxs(Fe,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:zo,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Vr&&o.jsx(Fe,{id:"full-btn",ref:Ct,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Le,children:o.jsx(ge,{name:"expand"})}),Rn&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:rn,ref:Ut,children:"Download"}),$a&&!fn&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Hr,ref:En,children:"Print"}),Bs&&o.jsx(Fe,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Ae)},children:o.jsx(ge,{name:"dots"})}),Ae&&o.jsxs("div",{id:"more-menu",role:"menu",children:[pn&&o.jsx("button",{className:"more-item",onClick:hs,children:"History"}),Rn&&o.jsx("button",{className:"more-item",onClick:()=>Ut.current?.click(),children:"Download"}),$a&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fa,children:"Print"}),fs&&o.jsx("button",{className:"more-item",onClick:kn,children:"Copy web link"}),La&&o.jsx("button",{className:"more-item",onClick:Do,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),bt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(di,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(iE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(EH,{pins:Jn,badges:$o,onOpen:Xr.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx($2,{}),Pa.trim()?o.jsx(jH,{query:Pa,dirs:jc,files:m,onOpen:Xr.open}):o.jsxs(o.Fragment,{children:[Yt&&o.jsx(_H,{pins:Jn,badges:$o,exists:Fo,currentPath:H,onOpen:Xr.open,onUnpin:ie=>W1(Yt,ie)}),Yt&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Qr==="recent"?" on":""),id:"tree-sort-btn","aria-label":Qr==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Qr==="recent",title:Qr==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>yU(Qr==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mn&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Mi(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(wH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:Yr,order:Qr,actions:Xr})]})]}),topbar:Cc,exit:Se?o.jsxs("button",{id:"exit-full",ref:Kt,onClick:ft,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(yo,{width:Zs,className:Ua,style:Zs==="read"&&Te!==null?{"--page-read":Te+"px"}:void 0,children:[!rt&&Z&&o.jsx(x7,{shares:Nt,canRevoke:!!l&&Pn(l.perm,"write"),onChanged:zn}),an,Zs==="read"&&o.jsx(wB,{width:Te,onChange:it})]})}),_e&&l&&o.jsx(y7,{project:l,path:M,isDir:U,shares:zt||[],onChanged:zn,onOpenFolder:ie=>bt(Xn(ie,l.id)),onClose:()=>{ve(!1),zn()}}),ds&&z&&o.jsx(k7,{apiBase:n,path:M,threads:qs,focus:W,onFocus:de,onClose:()=>{Y(!1),xe(!1)},framed:Or.test(M),picking:me,onPicking:xe,me:t.me?.email,admin:Pn(l?.perm,"admin")}),o.jsx(lq,{open:dt,onClose:()=>st(!1),candidates:Zr,recent:wc,initialQuery:Pe})]})}function NB({config:e}){const t=Ov(),n=pE(),[r,i]=w.useState(null),[l,u]=w.useState(null);w.useEffect(()=>u(null),[t]);const f=w.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=w.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=w.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=WL(),{data:g}=XL(!h),{data:b}=dE(!h),x=!!e.auth.admin,{data:j}=mE(x),S=w.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=w.useState(!1),N=()=>e.desktop?bt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===I2;try{const we=await Cn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),bt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(oV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=w.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===r3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=w.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(w.useEffect(()=>{document.title=M?vE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),w.useEffect(()=>{M&&a3(M.id)},[M]),h)return o.jsx(kB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);bt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&b?.find(I=>I.id===M.org)||null,X=o.jsx(mf,{name:U,onHome:()=>bt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),yd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),cs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(qU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(di,{vault:X,topbar:o.jsx(fi,{}),children:o.jsx(yo,{children:o.jsx(iV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!b)return o.jsx(di,{vault:X,topbar:o.jsx(fi,{}),children:o.jsx(yo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(oi,{to:"/setup"});if(!M)return o.jsxs(di,{vault:X,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(fi,{}),children:[o.jsx(yo,{children:o.jsx(eV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(iU,{})}:null,q=S.org?b.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Un("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(nU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=o$(g,S.project);return I?o.jsx(oi,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Xn(S.path,I,S.version,S.full,S.editing)}):o.jsxs(di,{vault:X,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(fi,{}),children:[o.jsx(yo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Un("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(oU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(BU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(ZU,{project:H??M,org:Z,onDeleted:async()=>{await n(),bt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(F2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(oi,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(oi,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(oi,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(oi,{to:Xn(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),bt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),cs()}};return o.jsxs(o.Fragment,{children:[o.jsx(zN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(PU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(IU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(FU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),bt(cn("install",M.id)),cs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function kB({token:e,onDone:t}){return w.useEffect(()=>{let n=!1;return Cn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(di,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(fi,{}),children:o.jsx(yo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function RB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=w.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return w.useEffect(()=>{document.title=i?vE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(oi,{to:Xn(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(zN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function MB(){const{data:e}=GM();return o.jsxs(e3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(NB,{config:e}):o.jsx(RB,{config:e}):o.jsx(di,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(fi,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(UL,{}),o.jsx(KL,{}),o.jsx(QL,{})]})}const TB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function OB(e,t){if(!e.project||!TB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function AB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function DB(e,t){for(const{queryKey:n,url:r}of OB(Mv(t,"hub"),i=>ui.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>AB(r),retry:!1})}class zB extends w.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const LN=new _M({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});BM();DB(LN,location.pathname+location.search);FL();WR.createRoot(document.getElementById("root")).render(o.jsx(w.StrictMode,{children:o.jsx(zB,{children:o.jsx(EM,{client:LN,children:o.jsx(MB,{})})})}));export{Vg as H,PB as a,wg as b,VB as c,qB as d,ko as e,Rf as f,HB as g,ZB as h,qM as i,o as j,BB as k,yV as l,KB as m,GB as o,wV as p,w as r,cy as s,Ne as t,UB as w}; diff --git a/internal/webapp/static/assets/sharedfile-DXV-dXg-.js b/internal/webapp/static/assets/sharedfile-DXV-dXg-.js new file mode 100644 index 00000000..9dc115ef --- /dev/null +++ b/internal/webapp/static/assets/sharedfile-DXV-dXg-.js @@ -0,0 +1,16 @@ +import{H as at,h as un,i as Rt,k as $o,f as wr,e as mr,l as fn,m as Fo}from"./index-BD48v6-0.js";const Q=()=>new Map,ds=e=>{const t=Q();return e.forEach((n,s)=>{t.set(s,n)}),t},wt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Bo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Vo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Nt=()=>new Set,Zn=e=>e[e.length-1],jo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Dt((this._observers.get(t)||Q()).values()).forEach(s=>s(...n))}destroy(){this._observers=Q()}}class Jo{constructor(){this._observers=Q()}on(t,n){wt(this._observers,t,Nt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Dt((this._observers.get(t)||Q()).values()).forEach(s=>s(...n))}destroy(){this._observers=Q()}}const lt=Math.floor,mn=Math.abs,Ls=(e,t)=>ee>t?e:t,Po=Math.pow,Kr=e=>e!==0?e<0:1/e<0,yr=1,kr=2,ts=4,es=8,Be=32,Ct=64,tt=128,Mn=31,gs=63,Gt=127,Wo=2147483647,bn=Number.MAX_SAFE_INTEGER,Sr=Number.MIN_SAFE_INTEGER,Yo=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&<(e)===e),Qr=String.fromCharCode,zo=e=>e.toLowerCase(),Go=/^\s*/g,qo=e=>e.replace(Go,""),Xo=/([A-Z])/g,br=(e,t)=>qo(e.replace(Xo,n=>`${t}${zo(n)}`)),Ko=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rVe.encode(e),Zo=Ve?Qo:Ko;let $e=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});$e&&$e.decode(new Uint8Array).length===1&&($e=null);const tl=(e,t)=>Ho(t,()=>e).join("");class qe{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const z=()=>new qe,Os=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Os(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ps=J,b=(e,t)=>{for(;t>Gt;)J(e,tt|Gt&t),t=lt(t/128);J(e,Gt&t)},Rs=(e,t)=>{const n=Kr(t);for(n&&(t=-t),J(e,(t>gs?tt:0)|(n?Ct:0)|gs&t),t=lt(t/64);t>0;)J(e,(t>Gt?tt:0)|Gt&t),t=lt(t/128)},ws=new Uint8Array(3e4),nl=ws.length/3,sl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;b(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ls(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(te(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},N=(e,t)=>{b(e,t.byteLength),vn(e,t)},Us=(e,t)=>{el(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},il=(e,t)=>Us(e,4).setFloat32(0,t,!1),ol=(e,t)=>Us(e,8).setFloat64(0,t,!1),ll=(e,t)=>Us(e,8).setBigInt64(0,t,!1),_r=new DataView(new ArrayBuffer(4)),cl=e=>(_r.setFloat32(0,e),_r.getFloat32(0)===e),je=(e,t)=>{switch(typeof t){case"string":J(e,119),qt(e,t);break;case"number":Yo(t)&&mn(t)<=Wo?(J(e,125),Rs(e,t)):cl(t)?(J(e,124),il(e,t)):(J(e,123),ol(e,t));break;case"bigint":J(e,122),ll(e,t);break;case"object":if(t===null)J(e,126);else if(me(t)){J(e,117),b(e,t.length);for(let n=0;n0&&b(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Cr=e=>{e.count>0&&(Rs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&b(e.encoder,e.count-2))};class yn{constructor(){this.encoder=new qe,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Cr(this),this.count=1,this.s=t)}toUint8Array(){return Cr(this),v(this.encoder)}}const Dr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Rs(e.encoder,t),e.count>1&&b(e.encoder,e.count-2)}};class ns{constructor(){this.encoder=new qe,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Dr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Dr(this),v(this.encoder)}}class al{constructor(){this.sarr=[],this.s="",this.lensE=new yn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new qe;return this.sarr.push(this.s),this.s="",qt(t,this.sarr.join("")),vn(t,this.lensE.toUint8Array()),v(t)}}const dt=e=>new Error(e),ot=()=>{throw dt("Method unimplemented")},et=()=>{throw dt("Unexpected case")},Zr=dt("Unexpected end of array"),ti=dt("Integer out of Range");class Nn{constructor(t){this.arr=t,this.pos=0}}const Bt=e=>new Nn(e),hl=e=>e.pos!==e.arr.length,ul=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Y=e=>ul(e,_(e)),ye=e=>e.arr[e.pos++],_=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posbn)throw ti}throw Zr},Ms=e=>{let t=e.arr[e.pos++],n=t&gs,s=64;const r=(t&Ct)>0?-1:1;if((t&tt)===0)return r*n;const i=e.arr.length;for(;e.posbn)throw ti}throw Zr},fl=e=>{let t=_(e);if(t===0)return"";{let n=String.fromCodePoint(ye(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ye(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},dl=e=>$e.decode(Y(e)),vt=$e?dl:fl,vs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},gl=e=>vs(e,4).getFloat32(0,!1),pl=e=>vs(e,8).getFloat64(0,!1),wl=e=>vs(e,8).getBigInt64(0,!1),ml=[e=>{},e=>null,Ms,gl,pl,wl,e=>!1,e=>!0,vt,e=>{const t=_(e),n={};for(let s=0;s{const t=_(e),n=[];for(let s=0;sml[127-ye(e)](e);class Ar extends Nn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hl(this)?this.count=_(this)+1:this.count=-1),this.count--,this.s}}class kn extends Nn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ms(this);const t=Kr(this.s);this.count=1,t&&(this.s=-this.s,this.count=_(this)+2)}return this.count--,this.s}}class ss extends Nn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Ms(this),n=t&1;this.diff=lt(t/2),this.count=1,n&&(this.count=_(this)+2)}return this.s+=this.diff,this.count--,this.s}}class yl{constructor(t){this.decoder=new kn(t),this.str=vt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const kl=crypto.getRandomValues.bind(crypto),ei=()=>kl(new Uint32Array(1))[0],Sl="10000000-1000-4000-8000"+-1e11,bl=()=>Sl.replace(/[018]/g,e=>(e^ei()&15>>e/4).toString(16)),$t=Date.now,Ir=e=>new Promise(e);Promise.all.bind(Promise);const Tr=e=>e===void 0?null:e;class _l{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let ni=new _l,Ns=!0;try{typeof localStorage<"u"&&localStorage&&(ni=localStorage,Ns=!1)}catch{}const si=ni,El=e=>Ns||addEventListener("storage",e),Cl=e=>Ns||removeEventListener("storage",e),Je=Symbol("Equality"),ri=(e,t)=>e===t||!!e?.[Je]?.(t)||!1,Dl=e=>typeof e=="object",Al=Object.assign,Il=Object.keys,Tl=(e,t)=>{for(const n in e)t(e[n],n)},xl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},_n=e=>Il(e).length,Ll=e=>{for(const t in e)return!1;return!0},Xe=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},$s=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ol=(e,t)=>e===t||_n(e)===_n(t)&&Xe(e,(n,s)=>(n!==void 0||$s(t,s))&&ri(t[s],n)),Rl=Object.freeze,ii=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&ii(e[t])}return Rl(e)},Fs=(e,t,n=0)=>{try{for(;ne,ue=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Je]!=null)return e[Je](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var oi={};const Ft=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",li=typeof window<"u"&&typeof document<"u"&&!Ft;let ht;const vl=()=>{if(ht===void 0)if(Ft){ht=Q();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");ht.set(`--${br(t,"-")}`,n),ht.set(`-${br(t,"-")}`,n)}})):ht=Q();return ht},ms=e=>vl().has(e),En=e=>Tr(Ft?oi[e.toUpperCase().replaceAll("-","_")]:si.getItem(e)),ci=e=>ms("--"+e)||En(e)!==null,Nl=ci("production"),$l=Ft&&Ml(oi.FORCE_COLOR,["true","1","2"]),Fl=$l||!ms("--no-colors")&&!ci("no-color")&&(!Ft||process.stdout.isTTY)&&(!Ft||ms("--color")||En("COLORTERM")!==null||(En("TERM")||"").includes("color")),ai=e=>new Uint8Array(e),Bl=(e,t,n)=>new Uint8Array(e,t,n),Vl=e=>new Uint8Array(e),jl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Jl=e=>{const t=atob(e),n=ai(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Bl(t.buffer,t.byteOffset,t.byteLength)},Wl=li?jl:Hl,Yl=li?Jl:Pl,zl=e=>{const t=ai(e.byteLength);return t.set(e),t};class Gl{constructor(t,n){this.left=t,this.right=n}}const Et=(e,t)=>new Gl(e,t),ql=(e,t)=>e.forEach(n=>t(n.left,n.right)),xr=e=>e.next()>=.5,rs=(e,t,n)=>lt(e.next()*(n+1-t)+t),hi=(e,t,n)=>lt(e.next()*(n+1-t)+t),Bs=(e,t,n)=>hi(e,t,n),Xl=e=>Qr(Bs(e,97,122)),Kl=(e,t=0,n=20)=>{const s=Bs(e,t,n);let r="";for(let i=0;it[Bs(e,0,t.length-1)],Ql=Symbol("0schema");class Zl{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(tl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const ys=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Je]?ri(e,t):me(e)?Is(e,n=>Ts(t,s=>ys(n,s))):Dl(e)?Xe(e,(n,s)=>ys(n,t[s])):!1;class q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),ys(n,s)}equals(t){return this.constructor===t.constructor&&ue(this.shape,t.shape)}[Ql](){return!0}[Je](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ot()}get nullable(){return Ae(this,jn)}get optional(){return new di(this)}cast(t){return Lr(t,this),t}expect(t){return Lr(t,this),t}}class Vs extends q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const V=(e,t=null)=>new Vs(e,t);V(Vs);class js extends q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const W=e=>new js(e);V(js);class $n extends q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Fn=(...e)=>new $n(e),ui=V($n),tc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),fi=e=>{if(ke.check(e))return[tc(e)];if(ui.check(e))return e.shape.map(t=>t+"");if(_i.check(e))return["[+-]?\\d+.?\\d*"];if(Ei.check(e))return[".*"];if(Cn.check(e))return e.shape.map(fi).flat(1);et()};class ec extends q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(fi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}V(ec);const nc=Symbol("optional");class di extends q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[nc](){return!0}}const sc=V(di);class rc extends q{check(t,n){return n?.extend(null,"never",typeof t),!1}}V(rc);class Bn extends q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Bn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):Xe(this.shape,(s,r)=>{const i=this._isPartial&&!$s(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const ic=e=>new Bn(e),oc=V(Bn),lc=W(e=>e!=null&&(e.constructor===Object||e.constructor==null));class gi extends q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&Xe(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const pi=(e,t)=>new gi(e,t),cc=V(gi);class wi extends q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&Xe(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const ac=(...e)=>new wi(e);V(wi);class mi extends q{constructor(t){super(),this.shape=t.length===1?t[0]:new Hs(t)}check(t,n){const s=me(t)&&Is(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const yi=(...e)=>new mi(e),hc=V(mi),uc=W(e=>me(e));class ki extends q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const fc=(e,t=null)=>new ki(e,t);V(ki);const dc=fc(q);class gc extends q{constructor(t){super(),this.len=t.length-1,this.args=ac(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const pc=V(gc),wc=W(e=>typeof e=="function");class mc extends q{constructor(t){super(),this.shape=t}check(t,n){const s=Is(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}V(mc,e=>e.shape.length>0);class Hs extends q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ts(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ae=(...e)=>e.findIndex(t=>Cn.check(t))>=0?Ae(...e.map(t=>Pe(t)).map(t=>Cn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Hs(e),Cn=V(Hs),Si=()=>!0,Dn=W(Si),yc=V(js,e=>e.shape===Si),Js=W(e=>typeof e=="bigint"),kc=W(e=>e===Js),bi=W(e=>typeof e=="symbol");W(e=>e===bi);const fe=W(e=>typeof e=="number"),_i=W(e=>e===fe),ke=W(e=>typeof e=="string"),Ei=W(e=>e===ke),Vn=W(e=>typeof e=="boolean"),Sc=W(e=>e===Vn),Ci=Fn(void 0);V($n,e=>e.shape.length===1&&e.shape[0]===void 0);Fn(void 0);const jn=Fn(null),bc=V($n,e=>e.shape.length===1&&e.shape[0]===null);V(Uint8Array);V(Vs,e=>e.shape===Uint8Array);const _c=Ae(fe,ke,jn,Ci,Js,Vn,bi);(()=>{const e=yi(Dn),t=pi(ke,Dn),n=Ae(fe,ke,jn,Vn,e,t);return e.shape=n,t.shape.values=n,n})();const Pe=e=>{if(dc.check(e))return e;if(lc.check(e)){const t={};for(const n in e)t[n]=Pe(e[n]);return ic(t)}else{if(uc.check(e))return Ae(...e.map(Pe));if(_c.check(e))return Fn(e);if(wc.check(e))return V(e)}et()},Lr=Nl?()=>{}:(e,t)=>{const n=new Zl;if(!t.check(e,n))throw dt(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Ec{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Pe(t),h:n}),this}else(t){return this.if(Dn,t)}done(){return(t,n)=>{for(let s=0;snew Ec(e),Di=Cc(Dn).if(_i,(e,t)=>rs(t,Sr,bn)).if(Ei,(e,t)=>Kl(t)).if(Sc,(e,t)=>xr(t)).if(kc,(e,t)=>BigInt(rs(t,Sr,bn))).if(Cn,(e,t)=>ie(t,is(t,e.shape))).if(oc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(sc.check(r)){if(xr(t))continue;r=r.shape}n[s]=Di(r,t)}return n}).if(hc,(e,t)=>{const n=[],s=hi(t,0,42);for(let r=0;ris(t,e.shape)).if(bc,(e,t)=>null).if(pc,(e,t)=>{const n=ie(t,e.res);return()=>n}).if(yc,(e,t)=>ie(t,is(t,[fe,ke,jn,Ci,Js,Vn,yi(fe),pi(Ae("a","b","c"),fe)]))).if(cc,(e,t)=>{const n={},s=rs(t,0,3);for(let r=0;rDi(Pe(t),e),mt=typeof document<"u"?document:{},Dc=e=>mt.createElement(e),Ac=()=>mt.createDocumentFragment();W(e=>e.nodeType===vc);const Ic=e=>mt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Tc=(e,t)=>(ql(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),xc=e=>{const t=Ac();for(let n=0;n(Ai(e,xc(t)),e),Hh=(e,t=[],n=[])=>Lc(Tc(Dc(e),t),n);W(e=>e.nodeType===Rc);const Jh=Ic;W(e=>e.nodeType===Uc);const Oc=e=>Bo(e,(t,n)=>`${n}:${t};`).join(""),Ai=(e,t)=>e.appendChild(t),Rc=mt.ELEMENT_NODE,Uc=mt.TEXT_NODE;mt.CDATA_SECTION_NODE;mt.COMMENT_NODE;const Mc=mt.DOCUMENT_NODE;mt.DOCUMENT_TYPE_NODE;const vc=mt.DOCUMENT_FRAGMENT_NODE;W(e=>e.nodeType===Mc);const At=Symbol,Ii=At(),Ti=At(),Nc=At(),$c=At(),Fc=At(),xi=At(),Bc=At(),Ps=At(),Vc=At(),jc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=Q();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Li(e)),Ri.forEach(t=>t.print(e))},Oi=(...e)=>{console.warn(...Li(e)),e.unshift(Ps),Ri.forEach(t=>t.print(e))},Ri=Nt(),Ui=e=>({[Symbol.iterator](){return this},next:e}),Wc=(e,t)=>Ui(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),os=(e,t)=>Ui(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Hn{constructor(t,n){this.clock=t,this.len=n}}class Ie{constructor(){this.clients=new Map}}const Se=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=lt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Yc(n,t.clock)!==null},Ws=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Hn(r.clock,te(r.len,i.clock+i.len-r.clock)):(s{const t=new Ie;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{wt(e.clients,t,()=>[]).push(new Hn(n,s))},zc=()=>new Ie,Gc=e=>{const t=zc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Te=(e,t)=>{b(e.restEncoder,t.clients.size),Dt(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),b(e.restEncoder,n);const r=s.length;b(e.restEncoder,r);for(let i=0;i{const t=new Ie,n=_(e.restDecoder);for(let s=0;s0){const o=wt(t.clients,r,()=>[]);for(let l=0;l{const s=new Ie,r=_(e.restDecoder);for(let i=0;i0){const i=new Kt;return b(i.restEncoder,0),Te(i,s),i.toUint8Array()}return null},Mi=ei;class ee extends xs{constructor({guid:t=bl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Mi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new zi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ir(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Ir(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&R(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Dt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return R(this,t,n)}get(t,n=P){const s=wt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==P&&r!==n)if(r===P){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,pe)}getText(t=""){return this.get(t,Ee)}getMap(t=""){return this.get(t,_e)}getXmlElement(t=""){return this.get(t,Ce)}getXmlFragment(t=""){return this.get(t,Qt)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Dt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ee({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,R(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class vi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return _(this.restDecoder)}readDsLen(){return _(this.restDecoder)}}class Ni extends vi{readLeftID(){return C(_(this.restDecoder),_(this.restDecoder))}readRightID(){return C(_(this.restDecoder),_(this.restDecoder))}readClient(){return _(this.restDecoder)}readInfo(){return ye(this.restDecoder)}readString(){return vt(this.restDecoder)}readParentInfo(){return _(this.restDecoder)===1}readTypeRef(){return _(this.restDecoder)}readLen(){return _(this.restDecoder)}readAny(){return He(this.restDecoder)}readBuf(){return zl(Y(this.restDecoder))}readJSON(){return JSON.parse(vt(this.restDecoder))}readKey(){return vt(this.restDecoder)}}class qc{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=_(this.restDecoder),this.dsCurrVal}readDsLen(){const t=_(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class be extends qc{constructor(t){super(t),this.keys=[],_(t),this.keyClockDecoder=new ss(Y(t)),this.clientDecoder=new kn(Y(t)),this.leftClockDecoder=new ss(Y(t)),this.rightClockDecoder=new ss(Y(t)),this.infoDecoder=new Ar(Y(t),ye),this.stringDecoder=new yl(Y(t)),this.parentInfoDecoder=new Ar(Y(t),ye),this.typeRefDecoder=new kn(Y(t)),this.lenDecoder=new kn(Y(t))}readLeftID(){return new de(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new de(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return He(this.restDecoder)}readBuf(){return Y(this.restDecoder)}readJSON(){return He(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=te(s,t[0].id.clock);const r=gt(t,s);b(e.restEncoder,t.length-r),e.writeClient(n),b(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{$(t,i)>r&&s.set(i,r)}),Jn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),b(e.restEncoder,s.size),Dt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{Xc(e,t.clients.get(r),r,i)})},Kc=(e,t)=>{const n=Q(),s=_(e.restDecoder);for(let r=0;r{const s=[];let r=Dt(n.keys()).sort((d,g)=>d-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new zi,c=new Map,a=(d,g)=>{const m=c.get(d);(m==null||m>g)&&c.set(d,g)};let u=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const g=d.id.client,m=n.get(g);m?(m.i--,l.clients.set(g,m.refs.slice(m.i)),n.delete(g),m.i=0,m.refs=[]):l.clients.set(g,[d]),r=r.filter(S=>S!==g)}s.length=0};for(;;){if(u.constructor!==rt){const g=wt(h,u.id.client,()=>$(t,u.id.client))-u.id.clock;if(g<0)s.push(u),a(u.id.client,u.id.clock-1),f();else{const m=u.getMissing(e,t);if(m!==null){s.push(u);const S=n.get(m)||{refs:[],i:0};if(S.refs.length===S.i)a(m,$(t,m)),f();else{u=S.refs[S.i++];continue}}else(g===0||g0)u=s.pop();else if(o!==null&&o.i0){const d=new Kt;return zs(d,l,new Map),b(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},Zc=(e,t)=>zs(e,t.doc.store,t.beforeState),ta=(e,t,n,s=new be(e))=>R(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=Kc(s,o),a=Qc(r,l,c),u=l.pendingStructs;if(u){for(const[f,d]of u.missing)if(d<$(l,f)){i=!0;break}if(a){for(const[f,d]of a.missing){const g=u.missing.get(f);(g==null||g>d)&&u.missing.set(f,d)}u.update=In([u.update,a.update])}}else l.pendingStructs=a;const h=Or(s,r,l);if(l.pendingDs){const f=new be(Bt(l.pendingDs));_(f.restDecoder);const d=Or(f,r,l);h&&d?l.pendingDs=In([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Bi(r.doc,f)}},n,!1),Bi=(e,t,n,s=be)=>{const r=Bt(t);ta(r,e,n,new s(r))},Vi=(e,t,n)=>Bi(e,t,n,Ni),ea=(e,t,n=new Map)=>{zs(e,t.store,n),Te(e,Gc(t.store))},na=(e,t=new Uint8Array([0]),n=new Kt)=>{const s=Hi(t);ea(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(_a(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Qe)return Sa(r.map((i,o)=>o===0?i:Ca(i)));if(n.constructor===Kt)return In(r)}return r[0]},ji=(e,t)=>na(e,t,new Qe),sa=e=>{const t=new Map,n=_(e.restDecoder);for(let s=0;ssa(new vi(Bt(e))),Ji=(e,t)=>(b(e.restEncoder,t.size),Dt(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{b(e.restEncoder,n),b(e.restEncoder,s)}),e),ra=(e,t)=>Ji(e,Jn(t.store)),ia=(e,t=new Fi)=>(e instanceof Map?Ji(t,e):ra(t,e),t.toUint8Array()),oa=e=>ia(e,new $i);class la{constructor(){this.l=[]}}const Rr=()=>new la,Ur=(e,t)=>e.l.push(t),Mr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Pi=(e,t,n)=>Fs(e.l,[t,n]);class de{constructor(t,n){this.client=t,this.clock=n}}const he=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new de(e,t),Wi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw et()},An=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Yi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Ph=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ca=e=>new Yi(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class aa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ha=(e,t,n=0)=>new aa(e,t,n),dn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Wi(e):s=C(e._item.id.client,e._item.id.clock),new Yi(s,r,t,n)},Wh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return dn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return dn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return dn(e,s.lastId,n);s=s.right}return dn(e,null,n)},ua=(e,t)=>{const n=ge(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},fa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if($(s,r.client)<=r.clock)return null;const u=n?Es(s,r):ua(s,r),h=u.item;if(!(h instanceof U))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(a+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if($(s,i.client)<=i.clock)return null;const{item:u}=n?Es(s,i):{item:ge(s,i)};if(u instanceof U&&u.content instanceof yt)c=u.content.type;else return null}else throw et();l>=0?a=c._length:a=0}return ha(c,a,e.assoc)},Yh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&he(e.item,t.item)&&he(e.type,t.type)&&e.assoc===t.assoc,ce=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Ke(t.ds,e.id),Ss=(e,t)=>{const n=wt(e.meta,Ss,Nt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r<$(s,i)&&K(e,C(i,r))}),Se(e,t.ds,r=>{}),n.add(t))};class zi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Jn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},$=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Gi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw et()}n.push(t)},gt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=lt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[gt(n,t.clock)]},ge=da,bs=(e,t,n)=>{const s=gt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[bs(e,n,t.clock)]},vr=(e,t,n)=>{const s=t.clients.get(n.client),r=gt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==st&&s.splice(r+1,0,Un(e,i,n.clock-i.id.clock+1)),i},ga=(e,t,n)=>{const s=e.clients.get(t.id.client);s[gt(s,t.id.clock)]=n},qi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=bs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Vo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ws(t.deleteSet),Zc(e,t),Te(e,t.deleteSet),!0),$r=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&wt(e.changed,t,Nt).add(n)},Sn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof U&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},wa=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=gt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ls(r.length-1,1+gt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+Sn(r,c)}})},Xi=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Pi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Fa(n)})}),Fs(l,[])}finally{s.gc&&wa(i,r,s.gcFilter),ma(i,r),n.afterState.forEach((u,h)=>{const f=n.beforeState.get(h)||0;if(f!==u){const d=r.clients.get(h),g=te(gt(d,f),1);for(let m=d.length-1;m>=g;)m-=1+Sn(d,m)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:f}=o[u].id,d=r.clients.get(h),g=gt(d,f);g+11||g>0&&Sn(d,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Pc(Ps,Ii,"[yjs] ",Ti,xi,"Changed the client-id because another client seems to be using it."),s.clientID=Mi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new Qe;Nr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new Kt;Nr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):Xi(e,t+1)}}},R=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new pa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&Xi(r,0)}}return o};class ya{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Fr=(e,t,n)=>{Se(e,n.deletions,s=>{s instanceof U&&t.scope.some(r=>r===e.doc||An(r,s))&&er(s,!1)})},Br=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;R(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let f=!1;Se(l,a.insertions,d=>{if(d instanceof U){if(d.redone!==null){let{item:g,diff:m}=Es(c,d.id);m>0&&(g=K(l,C(g.id.client,g.id.clock+m))),d=g}!d.deleted&&i.some(g=>g===l.doc||An(g,d))&&h.push(d)}}),Se(l,a.deletions,d=>{d instanceof U&&i.some(g=>g===l.doc||An(g,d))&&!Ke(a.insertions,d.id)&&u.add(d)}),u.forEach(d=>{f=po(l,d,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const g=h[d];e.deleteFilter(g)&&(g.delete(l),f=!0)}e.currStackItem=f?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class zh extends xs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=me(t)?t[0].doc:t instanceof ee?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const f=new Ie;c.afterState.forEach((S,w)=>{const D=c.beforeState.get(w)||0,I=S-D;I>0&&We(f,w,D,I)});const d=$t();let g=!1;if(this.lastChange>0&&d-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=ks([S.deletions,c.deleteSet]),S.insertions=ks([S.insertions,f])}else h.push(new ya(c.deleteSet,f)),g=!0;!a&&!u&&(this.lastChange=d),Se(c,c.deleteSet,S=>{S instanceof U&&this.scope.some(w=>w===c.doc||An(w,S))&&er(S,!0)});const m=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",m):this.emit("stack-item-updated",m)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=me(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof P?s.doc!==this.doc:s!==this.doc)&&Oi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Fr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Fr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Br(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Br(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*ka(e){const t=_(e.restDecoder);for(let n=0;nIn(e,Ni,Qe),ba=(e,t)=>{if(e.constructor===st){const{client:n,clock:s}=e.id;return new st(C(n,s+t),e.length-t)}else if(e.constructor===rt){const{client:n,clock:s}=e.id;return new rt(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new U(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},In=(e,t=be,n=Kt)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Bt(u)));let r=s.map(u=>new Gs(u,!0)),i=null;const o=new n,l=new qs(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const g=f.curr.id.clock-d.curr.id.clock;return g===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===rt?1:-1:g}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let f=u.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=u.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Ut(l,i.struct,i.offset),i={struct:f,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===rt?i.struct.length-=g:f=ba(f,g)),i.struct.mergeWith(f)||(Ut(l,i.struct,i.offset),i={struct:f,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let f=u.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==rt;f=u.next())Ut(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Ut(l,i.struct,i.offset),i=null),Xs(l);const c=s.map(u=>Ys(u)),a=ks(c);return Te(o,a),o.toUint8Array()},_a=(e,t,n=be,s=Kt)=>{const r=Hi(t),i=new s,o=new qs(i),l=new n(Bt(e)),c=new Gs(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,f=r.get(h)||0;if(c.curr.constructor===rt){c.next();continue}if(u.id.clock+u.length>f)for(Ut(o,u,te(f-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Ut(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}Xs(o);const a=Ys(l);return Te(i,a),i.toUint8Array()},Ki=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=z(),e.written=0)},Ut=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ki(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Xs=e=>{Ki(e);const t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n{const r=new n(Bt(e)),i=new Gs(r,!1),o=new s,l=new qs(o);for(let a=i.curr;a!==null;a=i.next())Ut(l,t(a),0);Xs(l);const c=Ys(r);return Te(o,c),o.toUint8Array()},Ca=e=>Ea(e,Ul,be,Qe),Vr="You must not compute changes after the event-handler fired.";class Pn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Da(this.currentTarget,this.target))}deletes(t){return Ke(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw dt(Vr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=Zn(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=Zn(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=Zn(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw dt(Vr);const n=this.target,s=Nt(),r=Nt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Da=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},G=()=>{Oi("Invalid access: Add Yjs type to a document before reading data.")},Qi=80;let Ks=0;class Aa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Ks++}}const Ia=e=>{e.timestamp=Ks++},Zi=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ks++},Ta=(e,t,n)=>{if(e.length>=Qi){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>mn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&mn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=te(t,r.index+n))}},Yn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;wt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Pi(s._eH,n,t)};class P{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Rr(),this._dEH=Rr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ot()}clone(){throw ot()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Ur(this._eH,t)}observeDeep(t){Ur(this._dEH,t)}unobserve(t){Mr(this._eH,t)}unobserveDeep(t){Mr(this._dEH,t)}toJSON(){}}const to=(e,t,n)=>{e.doc??G(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},eo=e=>{e.doc??G();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??G();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return ze(e,(s,r)=>{n.push(t(s,r,e))}),n},xa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},so=(e,t)=>{e.doc??G();const n=Wn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Zt(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Ze(new Uint8Array(h))),r.integrate(e,0);break;case ee:r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new tn(h)),r.integrate(e,0);break;default:if(h instanceof P)r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new yt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ro=()=>dt("Length exceeded!"),io=(e,t,n,s)=>{if(n>t._length)throw ro();if(n===0)return t._searchMarker&&Ye(t._searchMarker,n,s.length),Tn(e,t,null,s);const r=n,i=Wn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Tn(e,t,r,n)},oo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Wn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw ro();t._searchMarker&&Ye(t._searchMarker,r,-i+s)},xn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},Qs=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new Zt([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Zt([s]);break;case Uint8Array:l=new Ze(s);break;case ee:l=new tn(s);break;default:if(s instanceof P)l=new yt(s);else throw new Error("Unexpected content type")}new U(C(o,$(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},Zs=(e,t)=>{e.doc??G();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},lo=e=>{const t={};return e.doc??G(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},co=(e,t)=>{e.doc??G();const n=e._map.get(t);return n!==void 0&&!n.deleted},Oa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&ce(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},gn=e=>(e.doc??G(),Wc(e._map.entries(),t=>!t[1].deleted));class Ra extends Pn{}class pe extends P{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new pe;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new pe}clone(){const t=new pe;return t.insert(0,this.toArray().map(n=>n instanceof P?n.clone():n)),t}get length(){return this.doc??G(),this._length}_callObserver(t,n){super._callObserver(t,n),Yn(this,t,new Ra(this,t))}insert(t,n){this.doc!==null?R(this.doc,s=>{io(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?R(this.doc,n=>{La(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?R(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return so(this,t)}toArray(){return eo(this)}slice(t=0,n=this.length){return to(this,t,n)}toJSON(){return this.map(t=>t instanceof P?t.toJSON():t)}map(t){return no(this,t)}forEach(t){ze(this,t)}[Symbol.iterator](){return xa(this)}_write(t){t.writeTypeRef(sh)}}const Ua=e=>new pe;class Ma extends Pn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class _e extends P{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new _e}clone(){const t=new _e;return this.forEach((n,s)=>{t.set(s,n instanceof P?n.clone():n)}),t}_callObserver(t,n){Yn(this,t,new Ma(this,t,n))}toJSON(){this.doc??G();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof P?r.toJSON():r}}),t}get size(){return[...gn(this)].length}keys(){return os(gn(this),t=>t[0])}values(){return os(gn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return os(gn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??G(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return Zs(this,t)}has(t){return co(this,t)}clear(){this.doc!==null?R(this.doc,t=>{this.forEach(function(n,s,r){xn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(rh)}}const va=e=>new _e,Mt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Ol(e,t);class _s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&et(),this.right.content.constructor===j?this.right.deleted||xe(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const jr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===j?t.right.deleted||xe(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Wn(t,n):null;if(i){const o=new _s(i.p.left,i.p,i.index,r);return jr(e,o,n-i.index)}else{const o=new _s(null,t._start,0,r);return jr(e,o,n)}},ao=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===j&&Mt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new U(C(i,$(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new j(l,o));u.integrate(e,0),n.right=u,n.forward()})},xe=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},ho=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===j&&Mt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},uo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Mt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new U(C(i,$(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new j(l,c)),n.right.integrate(e,0),n.forward()}}return o},ls=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;ho(n,r);const l=uo(e,t,n,r),c=s.constructor===String?new pt(s):s instanceof P?new yt(s):new ne(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ye(t._searchMarker,n.index,c.getLength()),u=new U(C(o,$(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),ao(e,t,n,l)},Hr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;ho(n,r);const l=uo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===j));){if(!n.right.deleted)switch(n.right.content.constructor){case j:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Mt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new U(C(o,$(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new pt(c)),n.right.integrate(e,0),n.forward()}ao(e,t,n,l)},fo=(e,t,n,s,r)=>{let i=t;const o=Q();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===j){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===j){const{key:u,value:h}=a,f=s.get(u)??null;(o.get(u)!==a||f===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&f!==h&&(f===null?r.delete(u):r.set(u,f))),!c&&!t.deleted&&xe(r,a)}}t=t.right}return l},Na=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===j){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},$a=e=>{let t=0;return R(e.doc,n=>{let s=e._start,r=e._start,i=Q();const o=ds(i);for(;r;)r.deleted===!1&&(r.content.constructor===j?xe(o,r.content):(t+=fo(n,s,r,i,o),i=ds(o),s=r)),r=r.right}),t},Fa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&qi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===j&&o.constructor!==st&&t.add(o.parent)})}R(n,s=>{Se(e,e.deleteSet,r=>{if(r instanceof st||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===j?t.add(i):Na(s,r)});for(const r of t)$a(r)})},Jr=(e,t,n)=>{const s=n,r=ds(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case yt:case ne:case pt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];R(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(d={insert:a},r.size>0&&(d.attributes={},r.forEach((g,m)=>{g!==null&&(d.attributes[m]=g)}))),a="";break;case"retain":u>0&&(d={retain:u},Ll(c)||(d.attributes=Al({},c))),u=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case yt:case ne:this.adds(o)?this.deletes(o)||(f(),l="insert",a=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=1);break;case pt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=o.length);break;case j:{const{key:d,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=r.get(d)??null;Mt(m,g)?g!==null&&o.delete(s):(l==="retain"&&f(),Mt(g,i.get(d)??null)?delete c[d]:c[d]=g)}}else if(this.deletes(o)){i.set(d,g);const m=r.get(d)??null;Mt(m,g)||(l==="retain"&&f(),c[d]=m)}else if(!o.deleted){i.set(d,g);const m=c[d];m!==void 0&&(Mt(m,g)?m!==null&&o.delete(s):(l==="retain"&&f(),g===null?delete c[d]:c[d]=g))}o.deleted||(l==="insert"&&f(),xe(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ee extends P{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??G(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ee}clone(){const t=new Ee;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Ba(this,t,n);Yn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??G();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===pt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?R(this.doc,s=>{const r=new _s(null,this._start,0,new Map);for(let i=0;i0)&&ls(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Hr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Jr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??G();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let f=!1;i.forEach((g,m)=>{f=!0,h[m]=g});const d={insert:l};f&&(d.attributes=h),r.push(d),l=""}}const u=()=>{for(;c!==null;){if(ce(c,t)||n!==void 0&&ce(c,n))switch(c.content.constructor){case pt:{const h=i.get("ychange");t!==void 0&&!ce(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!ce(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case yt:case ne:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const f={};h.attributes=f,i.forEach((d,g)=>{f[g]=d})}r.push(h);break}case j:ce(c,t)&&(a(),xe(i,c.content));break}c=c.right}a()};return t||n?R(o,h=>{t&&Ss(h,t),n&&Ss(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ls(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!s);ls(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?R(s,r=>{Jr(r,pn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!1);o.right!==null&&Hr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return Zs(this,t)}getAttributes(){return lo(this)}_write(t){t.writeTypeRef(ih)}}const Va=e=>new Ee;class cs{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??G()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Ce||n.constructor===Qt)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Qt extends P{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Qt}clone(){const t=new Qt;return t.insert(0,this.toArray().map(n=>n instanceof P?n.clone():n)),t}get length(){return this.doc??G(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new cs(this,t)}querySelector(t){t=t.toUpperCase();const s=new cs(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Dt(new cs(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Yn(this,t,new Ja(this,n,t))}toString(){return no(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),ze(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?R(this.doc,s=>{io(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)R(this.doc,s=>{const r=t&&t instanceof P?t._item:t;Tn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw dt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?R(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return eo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return so(this,t)}slice(t=0,n=this.length){return to(this,t,n)}forEach(t){ze(this,t)}_write(t){t.writeTypeRef(lh)}}const ja=e=>new Qt;class Ce extends Qt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Ce(this.nodeName)}clone(){const t=new Ce(this.nodeName),n=this.getAttributes();return Tl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof P?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return Zs(this,t)}hasAttribute(t){return co(this,t)}getAttributes(t){return t?Oa(this,t):lo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return ze(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(oh),t.writeKey(this.nodeName)}}const Ha=e=>new Ce(e.readKey());class Ja extends Pn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Ln extends _e{constructor(t){super(),this.hookName=t}_copy(){return new Ln(this.hookName)}clone(){const t=new Ln(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(ch),t.writeKey(this.hookName)}}const Pa=e=>new Ln(e.readKey());class On extends Ee{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new On}clone(){const t=new On;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(ah)}}const Wa=e=>new On;class tr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ot()}mergeWith(t){return!1}write(t,n,s){throw ot()}integrate(t,n){throw ot()}}const Ya=0;class st extends tr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Gi(t.doc.store,this)}write(t,n){t.writeInfo(Ya),t.writeLen(this.length-n)}getMissing(t,n){return null}}class Ze{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ze(this.content)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const za=e=>new Ze(e.readBuf());class Ge{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ge(this.len)}splice(t){const n=new Ge(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){We(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Ga=e=>new Ge(e.readLen()),go=(e,t)=>new ee({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class tn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new tn(go(this.doc.guid,this.opts))}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const qa=e=>new tn(go(e.readString(),e.readAny()));class ne{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ne(this.embed)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Xa=e=>new ne(e.readJSON());class j{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new j(this.key,this.value)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Ka=e=>new j(e.readKey(),e.readJSON());class Rn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Rn(this.arr)}splice(t){const n=new Rn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const eh=e=>new pt(e.readString()),nh=[Ua,va,Va,Ha,ja,Pa,Wa],sh=0,rh=1,ih=2,oh=3,lh=4,ch=5,ah=6;class yt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new yt(this.type._copy())}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const hh=e=>new yt(nh[e.readTypeRef()](e)),Es=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ge(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof U);return{item:r,diff:s}},er=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Un=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new U(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Pr=(e,t)=>Ts(e,n=>Ke(n.deletions,t)),po=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return K(e,a);let u=t.parent._item,h=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||po(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=K(e,u.redone)}const d=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,f=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:K(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:K(e,w.redone);if(w!==null&&w.parent._item===u){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||Ke(s,h.right.id)||Pr(i.undoStack,h.right.id)||Pr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=K(e,h.redone);if(h&&h.right!==null)return null}else h=d._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=d._map.get(t.parentSub)||null)}const g=$(l,c),m=C(c,g),S=new U(m,h,h&&h.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=m,er(S,!0),S.integrate(e,0),S};class U extends tr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?kr:0}set marker(t){(this.info&es)>0!==t&&(this.info^=es)}get marker(){return(this.info&es)>0}get keep(){return(this.info&yr)>0}set keep(t){this.keep!==t&&(this.info^=yr)}get countable(){return(this.info&kr)>0}get deleted(){return(this.info&ts)>0}set deleted(t){this.deleted!==t&&(this.info^=ts)}markDeleted(){this.info|=ts}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=$(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=$(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===de&&this.id.client!==this.parent.client&&this.parent.clock>=$(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=vr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=K(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===st||this.right&&this.right.constructor===st)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===U?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===U&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===de){const s=ge(n,this.parent);s.constructor===st?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=vr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),he(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),We(t.deleteSet,this.id.client,this.id.clock,this.length),$r(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw et();this.content.gc(t),n?ga(t,this,new st(this.id,this.length)):this.content=new Ge(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Mn|(s===null?0:tt)|(r===null?0:Ct)|(i===null?0:Be);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Wi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===de?(t.writeParentInfo(!1),t.writeLeftID(l)):et();i!==null&&t.writeString(i)}this.content.write(t,n)}}const wo=(e,t)=>uh[t&Mn](e),uh=[()=>{et()},Ga,Qa,za,eh,Xa,Ka,hh,th,qa,()=>{et()}],fh=10;class rt extends tr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){et()}write(t,n){t.writeInfo(fh),b(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const mo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},yo="__ $YJS$ __";mo[yo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");mo[yo]=!0;const ko=new Map;class dh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Yl(n.newValue||"")}),El(this._onChange)}postMessage(t){si.setItem(this.room,Wl(Vl(t)))}close(){Cl(this._onChange)}}const gh=typeof BroadcastChannel>"u"?dh:BroadcastChannel,nr=e=>wt(ko,e,()=>{const t=Nt(),n=new gh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),ph=(e,t)=>(nr(e).subs.add(t),t),wh=(e,t)=>{const n=nr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),ko.delete(e)),s},ae=(e,t,n=null)=>{const s=nr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},So=0,sr=1,bo=2,Cs=(e,t)=>{b(e,So);const n=oa(t);N(e,n)},_o=(e,t,n)=>{b(e,sr),N(e,ji(t,n))},mh=(e,t,n)=>_o(t,n,Y(e)),Eo=(e,t,n,s)=>{try{Vi(t,Y(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},yh=(e,t)=>{b(e,bo),N(e,t)},kh=Eo,Sh=(e,t,n,s,r)=>{const i=_(e);switch(i){case So:mh(e,t,n);break;case sr:Eo(e,n,s,r);break;case bo:kh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},bh=0,_h=(e,t,n)=>{_(e)===bh&&n(t,vt(e))},as=3e4;class Co extends Jo{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=$t();this.getLocalState()!==null&&as/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&as<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&rr(this,s,"timeout")},lt(as/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:$t()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),ue(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const rr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Fe=(e,t,n=e.states)=>{const s=t.length,r=z();b(r,s);for(let i=0;i{const s=Bt(t),r=$t(),i=[],o=[],l=[],c=[],a=_(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Ch=e=>xl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),zt=0,Do=3,we=1,Dh=2,en=[];en[zt]=(e,t,n,s,r)=>{b(e,zt);const i=Sh(t,e,n.doc,n);s&&i===sr&&!n.synced&&(n.synced=!0)};en[Do]=(e,t,n,s,r)=>{b(e,we),N(e,Fe(n.awareness,Array.from(n.awareness.getStates().keys())))};en[we]=(e,t,n,s,r)=>{Eh(n.awareness,Y(t),n)};en[Dh]=(e,t,n,s,r)=>{_h(t,n.doc,(i,o)=>Ah(n,o))};const Wr=3e4,Ah=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Ao=(e,t,n)=>{const s=Bt(t),r=z(),i=_(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Ih=e=>!(e.code>=4400&&e.code<4500),Ds=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,rr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Io,Ls(Po(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Io=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=$t();const s=Ao(e,new Uint8Array(n.data),!0);Os(s)>1&&t.send(v(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Ds(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=$t(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=z();if(b(n,zt),Cs(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){const s=z();b(s,we),N(s,Fe(e.awareness,[e.doc.clientID])),t.send(v(s))}},e.emit("status",[{status:"connecting"}])}},hs=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&ae(e.bcChannel,t,e)};class Th extends xs{constructor(t,n,s,{connect:r=!0,awareness:i=new Co(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:f=Ih}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=en.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=z();b(d,zt),Cs(d,s),this.ws.send(v(d))}},a)),this._bcSubscriber=(d,g)=>{if(g!==this){const m=Ao(this,new Uint8Array(d),!1);Os(m)>1&&ae(this.bcChannel,v(m),this)}},this._updateHandler=(d,g)=>{if(g!==this){const m=z();b(m,zt),yh(m,d),hs(this,v(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:g,removed:m},S)=>{const w=d.concat(g).concat(m),D=z();b(D,we),N(D,Fe(i,w)),hs(this,v(D))},this._exitHandler=()=>{rr(this.awareness,[s.clientID],"app closed")},Ft&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Wr<$t()-this.wsLastMessageReceived&&Ds(this,this.ws,null)},Wr/10),r&&this.connect()}get url(){const t=Ch(this.params);return this.serverUrl+"/"+this.roomname+(t.length===0?"":"?"+t)}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,t&&(this.wsUnsuccessfulReconnects=0),this.emit("synced",[t]),this.emit("sync",[t]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Ft&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(ph(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const t=z();b(t,zt),Cs(t,this.doc),ae(this.bcChannel,v(t),this);const n=z();b(n,zt),_o(n,this.doc),ae(this.bcChannel,v(n),this);const s=z();b(s,Do),ae(this.bcChannel,v(s),this);const r=z();b(r,we),N(r,Fe(this.awareness,[this.doc.clientID])),ae(this.bcChannel,v(r),this)}disconnectBc(){const t=z();b(t,we),N(t,Fe(this.awareness,[this.doc.clientID],new Map)),hs(this,v(t)),this.bcconnected&&(wh(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Ds(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Io(this),this.connectBc())}}const Yr=Symbol("collab-http-remote");class xh{constructor(t,n,s,r,i){this.url=t,this.onStatus=n,this.onReady=s,this.onStalled=r,this.me=i,this.text=this.doc.getText("body"),this.awareness=new Co(this.doc),this.me&&this.awareness.setLocalStateField("user",{name:this.me.name,color:this.me.colour,colorLight:this.me.colour.replace(/\)$/," / 0.2)")})}url;onStatus;onReady;onStalled;me;doc=new ee;text;awareness;ws=null;closed=!1;reached=!1;stallTimer=null;remoteCursors(){const t=[];return this.awareness.getStates().forEach((n,s)=>{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=fa(ca(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Th(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Lh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=ji(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Yr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,I=new Int32Array(2*w+1);for(let x=-w;x<=w;x+=2){let L;w===0?L=0:x===-w||x!==w&&D[x-1+w-1]=r&&O>=i){u=w;break}}a.push(I)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let f=r,d=i;for(let w=u;w>0;w--){const D=a[w-1],I=f-d,x=I===-w||I!==w&&D[I-1+w-1]Vt&&d>X;)f--,d--,h.push(f,d);f=L,d=O}for(;f>0&&d>0;)f--,d--,h.push(f,d);const g=[];let m=0,S=0;for(let w=h.length-2;w>=0;w-=2){const D=h[w],I=h[w+1];(D>m||I>S)&&g.push({aS:n+m,aE:n+D,bS:n+S,bE:n+I}),m=D+1,S=I+1}return(mi.startsWith(o)&&(o===""||o.endsWith(` +`)||i[o.length]===` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?vh(e,t)<=0?e+t:t+e:null}function To(e,t,n,s){if(t===n)return t;if(t===e)return n;if(n===e)return t;const r=new Map,i=ut(e,s),o=ut(t,s),l=ut(n,s),c=ft(i,r),a=[...De(c,ft(o,r)).map(m=>({h:m,toks:o,side:0})),...De(c,ft(l,r)).map(m=>({h:m,toks:l,side:1}))];a.sort((m,S)=>m.h.aS-S.h.aS||m.h.aE-S.h.aE||m.side-S.side);const u=(m,S,w)=>m.slice(S,w).join(""),h=(m,S,w,D)=>{let I="",x=w;for(const L of m)L.side===S&&(I+=u(i,x,L.h.aS)+u(L.toks,L.h.bS,L.h.bE),x=L.h.aE);return I+u(i,x,D)};let f="",d=0,g=0;for(;gO.side)).size===1){f+=h(m,m[0].side,S,w);continue}const I=h(m,0,S,w),x=h(m,1,S,w);if(I===x){f+=I;continue}if(S===w){const O=Nh(I,x,s!==zr,i.length===0);if(O===null)return null;f+=O;continue}if(s===zr)return null;const L=To(u(i,S,w),I,x,s+1);if(L===null)return null;f+=L}return f+u(i,d,i.length)}const us=e=>e===""||e.endsWith(` +`)?e:e+` +`;function oe(e,t,n){const s=To(us(e),us(t),us(n),Xt);if(s===null)return{ok:!1};let r=t.endsWith(` +`);return r===e.endsWith(` +`)&&(r=n.endsWith(` +`)),s===""||r===s.endsWith(` +`)?{ok:!0,text:s}:{ok:!0,text:r?s+` +`:s.slice(0,-1)}}function Gr(e,t){if(e===t)return[];const n=[],s=new Map,r=ut(e,Xt),i=ut(t,Xt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?g.charCodeAt(w-1):0;I>=55296&&I<=56319&&w--;const x=D>0?g.charCodeAt(g.length-D):0;x>=56320&&x<=57343&&D--,S+=w,g=g.slice(w,g.length-D),m=m.slice(w,m.length-D),(g.length||m.length)&&s.push({index:S,deleteCount:g.length,insertText:m}),a=f,u=d}}function fs(e,t,n){const s=new Map,r=ft(ut(t,Xt),s),i=De(ft(ut(e,Xt),s),r),o=De(r,ft(ut(n,Xt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function wn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const qr=700,le=[2e3,4e3,8e3,15e3],Xr=2e3,Fh=4,Bh=32e3,Vh=32;function Gh(e){let t=e.seed,n=e.baseSha;const s=(p,k)=>{t=p,r=k,Ot(k);const y=It.lastIndexOf(p);y>=0?It.splice(0,y+1):It.length=0};let r=e.baseSha;const i=p=>{if(!p)return;const k=[];for(let y=p;y!==null&&k.length<4;y=y.prev)y.sent!==y.from&&!k.includes(y.sent)&&k.push(y.sent);return k.length?k:void 0},o=(p,k=kt)=>{const y=i(k);return r&&r===n&&t.length>Bh?{base:n,text:p,...y?{prior_sent:y}:{}}:{base:n,base_text:t,text:p,...y?{prior_sent:y}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,f=0,d=null,g=!1,m=!1,S=!1,w=null,D=null,I=0;const x=(p=Date.now())=>{const k=Math.max(p,I+1e3);return I=k,$o(e.path,e.who||"browser",new Date(k))},L=new Map;let O=0,Vt=!1,X=null,jt=0,zn=!1,kt=null,Ht=!1;const It=[],ir=p=>{It.at(-1)!==p&&(It.push(p),It.length>Vh&&It.shift())};let St=!1,Le=null,Jt=0;const Oe=()=>{St=!1,Le=null},Gn=p=>{Jt===p&&Oe()};let Z=0,it=0,nn=null,Pt=null,qn=!1,bt=null,Re=!1,Wt=null,nt=null;const M=p=>e.onState?.(p),sn=p=>e.apiBase+"upload/content?path="+encodeURIComponent(p),Tt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let rn=null,Xn=0;const Ue=()=>{clearTimeout(rn??void 0),rn=null},on=p=>{if(!(p instanceof at?p.status>=500||p.status===429:!0)||h||a)return;Ue();const y=le[Math.min(Xn,le.length-1)];Xn++,rn=setTimeout(()=>{rn=null,!h&&!a&&Me()},y)},or=()=>{Ue(),Xn=0},ln=()=>{Ue(),Wt&&clearTimeout(Wt),Wt=setTimeout(()=>{Me()},qr)},Yt=p=>{if(h)return d=p,!0;const k=F();if(k===p)return!0;const y=Gr(k,p);if(hr())return T.applySplices(y),!0;if(!e.soloApply)return!1;for(const A of y)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Me=()=>{if(a)return Promise.resolve();if(g)return m?Promise.resolve():Ne();if(Pt)return qn=!0,Pt;const p=(async()=>{try{await xo()}finally{Pt=null}})();return Pt=p,p},xo=async()=>{let p=0;for(;;){if(qn=!1,H||a||S)return;const k=F();if(k===t&&!Ht){M("clean");return}M("saving"),e.onWriting?.();const y=l||c?await Lo(k):await Ro(k);if(y==="stop")return;if(y==="rebased"){if(++p>Fh){await cn(F(),n??"");return}continue}if(!qn){M(F()===t&&!Ht?"clean":"dirty");return}}};let xt=!1;const Lo=async p=>{bt=p,Re=!1;let k;try{k=await un(sn(e.path),p,n,xt)}catch(y){return bt=null,y instanceof at&&y.status===422&&wn(y)?(xt=!1,ve(p),"stop"):y instanceof at&&y.status===409?await lr(t,!1)?"rebased":"stop":(M("error"),on(y),"stop")}return bt=null,xt=!1,or(),k.merged?await lr(p,!0)?"rebased":"stop":(Re||s(p,k.sha),e.onSaved?.(p),"done")},lr=async(p,k)=>{let y;try{y=await wr(mr(e.apiBase,e.path))}catch(B){return M("error"),F()!==t&&on(B),!1}if(y.kind!=="text")return M("error"),!1;const A=F(),E=oe(p,y.text,A);return!E.ok||!Yt(E.text)?(k&&s(y.text,y.sha),await cn(A,y.sha??""),!1):(s(y.text,y.sha),k&&e.onSaved?.(y.text),!0)},Oo=p=>{if(p.update&&T.applyRemoteUpdate(p.update),typeof p.text!="string"){kt=null;return}let k=null;for(let y=kt;y!==null;y=y.prev)if(y.sent!==y.from&&fs(y.from,y.sent,p.text)){k=y;break}if(kt=null,k){Ht=!0;const y=oe(k.sent,p.text,F());y.ok&&Yt(y.text)?(t=p.text,r=void 0,Ot(p.sha)):(t=k.sent,r=void 0)}},Ro=async p=>{bt=p,Re=!1;let k;const y=kt;try{kt={sent:p,from:t,prev:y},k=await Rt(Tt,{...o(p,y),...xt?{confirm_shrink:!0}:{}})}catch(E){if(bt=null,E instanceof at&&[400,401,403,404,405,409,413].includes(E.status)&&(kt=y),E instanceof at&&(E.status===404||E.status===405))return c=!0,"rebased";if(E instanceof at&&E.status===422&&wn(E))return xt=!1,ve(p),"stop";if(E instanceof at&&E.status===409&&!a){let B={};try{B=JSON.parse(E.body)}catch{}const ct=typeof B.text=="string"?B.text:null;if(ct!==null){const pr=oe(t,ct,F());if(pr.ok&&Yt(pr.text))return t=ct,r=void 0,Ot(B.sha),"rebased"}Vt=!0;const re=F(),gr=await cn(re,B.sha??"");return h?"stop":gr?(on(gr.err),"stop"):(Vt=!1,F()!==re?"rebased":"stop")}return M(a?"dirty":"error"),on(E),"stop"}if(bt=null,xt=!1,or(),k.update&&T.applyRemoteUpdate(k.update),kt=null,Ht=!1,a)return"stop";const A=oe(p,k.text,F());return A.ok&&Yt(A.text)&&(Re||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let H=null;const ve=p=>{H||h||!e.onShrinkRefused||(M("error"),H={was:fn(t),now:fn(p),confirm:async()=>{if(!h){if(a){M("saving"),e.onWriting?.();const k=Z,y=Jt;try{const A=await Rt(Tt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),Kn(k,y);const E=!St&&it>=Z;M(E?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&it{if(!h)try{const k=await wr(mr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Yt(k.text),H=null,a&&!u){if(await se(!1),h)return;M(it>=Z&&!St?"clean":"dirty");return}it=Z,f&&(f=0,e.onPending?.(0)),Oe(),M("clean")}catch{M("error")}finally{H=null}}},e.onShrinkRefused(H))};let Lt=null;const Uo=()=>{Lt&&clearTimeout(Lt),Lt=setTimeout(()=>{const p=F();Fo(fn(t),fn(p))&&ve(p)},qr)},cn=async(p,k,y=x())=>{const A=++O;L.set(y,p);try{return await un(sn(y),p),A===O&&!a&&(t=p,r=void 0,k&&(n=k),M("clean")),e.onConflictCopy?.(y),null}catch(E){return A===O&&!a&&M("error"),{err:E}}finally{L.get(y)===p&&L.delete(y)}},Kn=(p,k)=>{it=Math.max(it,p),Gn(k),!(h||u)&&(f=Z-it,e.onPending?.(f))},Mo=()=>{h||u||H||nt||(nt=setTimeout(()=>{nt=null,!u&&!h&&se(!1)},Xr))},se=p=>{if(clearTimeout(nt??void 0),nt=null,p){if(it>=Z)return Promise.resolve();const y=Z,A=Jt;return Rt(Tt,{update:T.encodeState(),base:n},!0).then(E=>{Ot(E.sha),Kn(y,A)})}if(nn)return nn;const k=(async()=>{try{for(;!u&&!h&&!H&&it{g=!1,w=null,D=null,jt=0,clearTimeout(X??void 0),X=null,Ht=!1,a=!0,ir(T.text.toString()),p?.(),zn&&(zn=!1,e.onReady(T))},Ne=async()=>{if(h||a||m||S)return;if(clearTimeout(X??void 0),X=null,Wt&&clearTimeout(Wt),Wt=null,Pt){S=!0;try{for(;Pt;)await Pt}finally{S=!1}if(h||a)return;if(!u){F()!==t&&ln();return}}if(kt!==null&&!c){let ct;S=!0;try{ct=await Rt(Tt,{peek:!0})}catch{if(h||a)return;const re=le[Math.min(jt,le.length-1)];jt++,X=setTimeout(()=>{X=null,Ne()},re);return}finally{S=!1}if(h||a)return;if(Oo(ct),!u){(F()!==t||Ht)&&ln();return}}const p=e.soloText?.();if(p===void 0||p===t)return Qn();const k=T.text.toString(),y=oe(t,k,p);if(y.ok)return Qn(()=>T.applySplices(Gr(k,y.text)));g=!0,(w===null||D!==p)&&(w=x(),D=p),m=!0;let A;try{A=await cn(p,n??"",w)}finally{m=!1}if(h)return;if(!A)return e.soloText?.()!==p?(w=null,D=null,Ne()):Qn(()=>{t=T.text.toString()});const E=A.err;if(E instanceof at&&!(E.status>=500||E.status===429))return;const B=le[Math.min(jt,le.length-1)];jt++,X=setTimeout(()=>{X=null,Ne()},B)},T=new xh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),p=>{u=p==="live",p==="solo"&&(l=!0),u&&(nt&&clearTimeout(nt),nt=null,Ue(),a||Ne(),it=Z,f&&(f=0,e.onPending?.(0))),e.onCollab?.(p)},()=>{a?e.onReady(T):zn=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),cr=(p,k)=>{const y=a?T.text.toString():null;if(y!==null&&ir(y),!T.isRemote(k?.origin)){if(M("dirty"),a){St=!0,Le=y,Jt+=1,u||(Z+=1,f=Z-it,e.onPending?.(f),clearTimeout(nt??void 0),nt=setTimeout(()=>{nt=null,!u&&!h&&se(!1)},Xr)),Uo();return}ln()}};T.text.observe(cr);const ar=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",ar),Oh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const F=()=>d!==null?d:hr()?T.text.toString():e.soloText?.()??"",hr=()=>a||l&&T.text.length>0,Ot=p=>{p&&(n=p)},vo=(p,k,y)=>{if(y?.held)return s(p,k),"same";if(p===t||p===bt)return Ot(k),"same";const A=F();if(p===A)return s(p,k),a&&(Oe(),M("clean")),"same";if(a){const B=t;return It.includes(p)||fs(B,p,A)?(s(p,k),St&&(Le===null||p===Le||fs(B,Le,p))&&(Oe(),M("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(p,k),Yt(p),Oe(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const E=oe(t,p,A);return E.ok?(bt!==null&&(Re=!0),s(p,k),Yt(E.text),E.text!==p?ln():bt===null&&M("clean"),E.text===A?"same":"merged"):"blocked"};let an=null;const No=()=>{if(!a)return Me();if(H||h)return Promise.resolve();if(!u)return f>0?se(!1):Promise.resolve();if(!St)return Promise.resolve();if(an)return an;const p=Jt;M("saving");const k=(async()=>{try{const y=await Rt(Tt,{update:T.encodeState()});if(h)return;y.update&&T.applyRemoteUpdate(y.update),s(y.text,y.sha),Gn(p),M(St?"dirty":"clean"),e.onSaved?.(t)}catch(y){if(h||y instanceof at&&y.status===422&&wn(y)&&(clearTimeout(Lt??void 0),Lt=null,ve(F()),H))return;M(St?"dirty":"clean")}finally{an=null}})();return an=k,k};let _t=null;const hn=p=>()=>{_t===p&&(_t=null)},ur=(p,k)=>{if(H)return;if(a){const A=!u&&f>0;if(!A&&!(u&&St))return;const E="room\0"+T.text.toString();if(_t===E)return;_t=E;const B=Jt;(A?se(!0):Rt(Tt,{update:T.encodeState()},!0).then(re=>Ot(re.sha))).then(()=>Gn(B),hn(E));return}if(g||Vt){const A="park\0"+p;if(_t===A)return;_t=A;let E=w!==null&&D===p?w:null;for(const[B,ct]of L)E===null&&ct===p&&(E=B);E??=x(),un(sn(E),p,void 0,!1,!0).catch(hn(A));return}if(!p||p===t)return;const y="text\0"+p;if(_t!==y){if((l||c)&&!k){Me();return}_t=y,l||c?un(sn(e.path),p,n,xt,!0).catch(hn(y)):Rt(Tt,o(p),!0).catch(hn(y))}},fr=()=>{h||ur(F(),!0)},dr=()=>{_t=null};return typeof window<"u"&&(window.addEventListener("pagehide",fr),window.addEventListener("pageshow",dr)),{collab:T,current:F,merge:vo,rebase:Ot,saveNow:No,askingShrink:()=>H!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",fr),window.removeEventListener("pageshow",dr)),clearTimeout(Wt??void 0),clearTimeout(Lt??void 0),Ue(),clearTimeout(X??void 0),X=null;const p=F();h=!0,d=p,H?e.onShrinkWithdrawn?.(H):ur(p,!1),clearTimeout(nt??void 0),T.awareness.off("change",ar),T.text.unobserve(cr),T.destroy()}}}export{ee as D,qr as S,zh as U,Wh as a,ca as b,fa as c,Gr as d,Yh as e,Ls as f,te as g,Hh as h,Et as i,oe as m,Gh as o,Ph as r,Jh as t}; diff --git a/internal/webapp/static/assets/sharedfile-nk3qnjVG.js b/internal/webapp/static/assets/sharedfile-nk3qnjVG.js deleted file mode 100644 index 05aa14d3..00000000 --- a/internal/webapp/static/assets/sharedfile-nk3qnjVG.js +++ /dev/null @@ -1,6 +0,0 @@ -import{h as Pt,i as ge,H as es,k as oi,l as pe,f as ns,e as ss,m as li}from"./index-Bnuge9vv.js";const V=()=>new Map,ln=e=>{const t=V();return e.forEach((n,s)=>{t.set(s,n)}),t},Z=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},hi=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},ai=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},ht=()=>new Set,Ke=e=>e[e.length-1],ui=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return rt((this._observers.get(t)||V()).values()).forEach(s=>s(...n))}destroy(){this._observers=V()}}class fi{constructor(){this._observers=V()}on(t,n){Z(this._observers,t,ht).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return rt((this._observers.get(t)||V()).values()).forEach(s=>s(...n))}destroy(){this._observers=V()}}const W=Math.floor,ke=Math.abs,Dn=(e,t)=>ee>t?e:t,gi=Math.pow,Rs=e=>e!==0?e<0:1/e<0,rs=1,is=2,Xe=4,qe=8,qt=32,st=64,H=128,$e=31,hn=63,wt=127,pi=2147483647,Ce=Number.MAX_SAFE_INTEGER,cs=Number.MIN_SAFE_INTEGER,wi=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&W(e)===e),Ms=String.fromCharCode,mi=e=>e.toLowerCase(),yi=/^\s*/g,ki=e=>e.replace(yi,""),bi=/([A-Z])/g,os=(e,t)=>ki(e.replace(bi,n=>`${t}${mi(n)}`)),Si=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQt.encode(e),Ci=Qt?_i:Si;let Kt=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Kt&&Kt.decode(new Uint8Array).length===1&&(Kt=null);const Di=(e,t)=>di(t,()=>e).join("");class oe{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const $=()=>new oe,En=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(En(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},an=U,w=(e,t)=>{for(;t>wt;)U(e,H|wt&t),t=W(t/128);U(e,wt&t)},An=(e,t)=>{const n=Rs(t);for(n&&(t=-t),U(e,(t>hn?H:0)|(n?st:0)|hn&t),t=W(t/64);t>0;)U(e,(t>wt?H:0)|wt&t),t=W(t/128)},un=new Uint8Array(3e4),Ai=un.length/3,Ii=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;w(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Dn(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(St(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},I=(e,t)=>{w(e,t.byteLength),ve(e,t)},In=(e,t)=>{Ei(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Li=(e,t)=>In(e,4).setFloat32(0,t,!1),Oi=(e,t)=>In(e,8).setFloat64(0,t,!1),xi=(e,t)=>In(e,8).setBigInt64(0,t,!1),ls=new DataView(new ArrayBuffer(4)),Ui=e=>(ls.setFloat32(0,e),ls.getFloat32(0)===e),Zt=(e,t)=>{switch(typeof t){case"string":U(e,119),mt(e,t);break;case"number":wi(t)&&ke(t)<=pi?(U(e,125),An(e,t)):Ui(t)?(U(e,124),Li(e,t)):(U(e,123),Oi(e,t));break;case"bigint":U(e,122),xi(e,t);break;case"object":if(t===null)U(e,126);else if(Nt(t)){U(e,117),w(e,t.length);for(let n=0;n0&&w(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const as=e=>{e.count>0&&(An(e.encoder,e.count===1?e.s:-e.s),e.count>1&&w(e.encoder,e.count-2))};class be{constructor(){this.encoder=new oe,this.s=0,this.count=0}write(t){this.s===t?this.count++:(as(this),this.count=1,this.s=t)}toUint8Array(){return as(this),A(this.encoder)}}const us=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);An(e.encoder,t),e.count>1&&w(e.encoder,e.count-2)}};class Qe{constructor(){this.encoder=new oe,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(us(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return us(this),A(this.encoder)}}class Ri{constructor(){this.sarr=[],this.s="",this.lensE=new be}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new oe;return this.sarr.push(this.s),this.s="",mt(t,this.sarr.join("")),ve(t,this.lensE.toUint8Array()),A(t)}}const X=e=>new Error(e),z=()=>{throw X("Method unimplemented")},J=()=>{throw X("Unexpected case")},Ns=X("Unexpected end of array"),$s=X("Integer out of Range");class Be{constructor(t){this.arr=t,this.pos=0}}const dt=e=>new Be(e),Mi=e=>e.pos!==e.arr.length,Ni=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},N=e=>Ni(e,y(e)),$t=e=>e.arr[e.pos++],y=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posCe)throw $s}throw Ns},Tn=e=>{let t=e.arr[e.pos++],n=t&hn,s=64;const r=(t&st)>0?-1:1;if((t&H)===0)return r*n;const i=e.arr.length;for(;e.posCe)throw $s}throw Ns},$i=e=>{let t=y(e);if(t===0)return"";{let n=String.fromCodePoint($t(e));if(--t<100)for(;t--;)n+=String.fromCodePoint($t(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},vi=e=>Kt.decode(N(e)),lt=Kt?vi:$i,Ln=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Bi=e=>Ln(e,4).getFloat32(0,!1),Fi=e=>Ln(e,8).getFloat64(0,!1),Vi=e=>Ln(e,8).getBigInt64(0,!1),ji=[e=>{},e=>null,Tn,Bi,Fi,Vi,e=>!1,e=>!0,lt,e=>{const t=y(e),n={};for(let s=0;s{const t=y(e),n=[];for(let s=0;sji[127-$t(e)](e);class ds extends Be{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Mi(this)?this.count=y(this)+1:this.count=-1),this.count--,this.s}}class Se extends Be{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Tn(this);const t=Rs(this.s);this.count=1,t&&(this.s=-this.s,this.count=y(this)+2)}return this.count--,this.s}}class Ze extends Be{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Tn(this),n=t&1;this.diff=W(t/2),this.count=1,n&&(this.count=y(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Hi{constructor(t){this.decoder=new Se(t),this.str=lt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ji=crypto.getRandomValues.bind(crypto),vs=()=>Ji(new Uint32Array(1))[0],Yi="10000000-1000-4000-8000"+-1e11,Gi=()=>Yi.replace(/[018]/g,e=>(e^vs()&15>>e/4).toString(16)),at=Date.now,fs=e=>new Promise(e);Promise.all.bind(Promise);const gs=e=>e===void 0?null:e;class zi{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let Bs=new zi,On=!0;try{typeof localStorage<"u"&&localStorage&&(Bs=localStorage,On=!1)}catch{}const Fs=Bs,Wi=e=>On||addEventListener("storage",e),Pi=e=>On||removeEventListener("storage",e),ee=Symbol("Equality"),Vs=(e,t)=>e===t||!!e?.[ee]?.(t)||!1,Ki=e=>typeof e=="object",Xi=Object.assign,qi=Object.keys,Qi=(e,t)=>{for(const n in e)t(e[n],n)},Zi=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},De=e=>qi(e).length,tc=e=>{for(const t in e)return!1;return!0},le=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},xn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ec=(e,t)=>e===t||De(e)===De(t)&&le(e,(n,s)=>(n!==void 0||xn(t,s))&&Vs(t[s],n)),nc=Object.freeze,js=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&js(e[t])}return nc(e)},Un=(e,t,n=0)=>{try{for(;ne,Lt=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ee]!=null)return e[ee](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var Hs={};const ut=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Js=typeof window<"u"&&typeof document<"u"&&!ut;let K;const ic=()=>{if(K===void 0)if(ut){K=V();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");K.set(`--${os(t,"-")}`,n),K.set(`-${os(t,"-")}`,n)}})):K=V();return K},dn=e=>ic().has(e),Ee=e=>gs(ut?Hs[e.toUpperCase().replaceAll("-","_")]:Fs.getItem(e)),Ys=e=>dn("--"+e)||Ee(e)!==null,cc=Ys("production"),oc=ut&&rc(Hs.FORCE_COLOR,["true","1","2"]),lc=oc||!dn("--no-colors")&&!Ys("no-color")&&(!ut||process.stdout.isTTY)&&(!ut||dn("--color")||Ee("COLORTERM")!==null||(Ee("TERM")||"").includes("color")),Gs=e=>new Uint8Array(e),hc=(e,t,n)=>new Uint8Array(e,t,n),ac=e=>new Uint8Array(e),uc=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),fc=e=>{const t=atob(e),n=Gs(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return hc(t.buffer,t.byteOffset,t.byteLength)},pc=Js?uc:dc,wc=Js?fc:gc,mc=e=>{const t=Gs(e.byteLength);return t.set(e),t};class yc{constructor(t,n){this.left=t,this.right=n}}const nt=(e,t)=>new yc(e,t),kc=(e,t)=>e.forEach(n=>t(n.left,n.right)),ps=e=>e.next()>=.5,tn=(e,t,n)=>W(e.next()*(n+1-t)+t),zs=(e,t,n)=>W(e.next()*(n+1-t)+t),Rn=(e,t,n)=>zs(e,t,n),bc=e=>Ms(Rn(e,97,122)),Sc=(e,t=0,n=20)=>{const s=Rn(e,t,n);let r="";for(let i=0;it[Rn(e,0,t.length-1)],_c=Symbol("0schema");class Cc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(Di(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const fn=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[ee]?Vs(e,t):Nt(e)?Sn(e,n=>_n(t,s=>fn(n,s))):Ki(e)?le(e,(n,s)=>fn(n,t[s])):!1;class B{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),fn(n,s)}equals(t){return this.constructor===t.constructor&&Lt(this.shape,t.shape)}[_c](){return!0}[ee](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){z()}get nullable(){return Jt(this,Je)}get optional(){return new Ks(this)}cast(t){return ws(t,this),t}expect(t){return ws(t,this),t}}class Mn extends B{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const L=(e,t=null)=>new Mn(e,t);L(Mn);class Nn extends B{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const M=e=>new Nn(e);L(Nn);class Fe extends B{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Ve=(...e)=>new Fe(e),Ws=L(Fe),Dc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ps=e=>{if(vt.check(e))return[Dc(e)];if(Ws.check(e))return e.shape.map(t=>t+"");if(rr.check(e))return["[+-]?\\d+.?\\d*"];if(ir.check(e))return[".*"];if(Ae.check(e))return e.shape.map(Ps).flat(1);J()};class Ec extends B{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ps).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}L(Ec);const Ac=Symbol("optional");class Ks extends B{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[Ac](){return!0}}const Ic=L(Ks);class Tc extends B{check(t,n){return n?.extend(null,"never",typeof t),!1}}L(Tc);class je extends B{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new je(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):le(this.shape,(s,r)=>{const i=this._isPartial&&!xn(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const Lc=e=>new je(e),Oc=L(je),xc=M(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Xs extends B{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&le(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const qs=(e,t)=>new Xs(e,t),Uc=L(Xs);class Qs extends B{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&le(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Rc=(...e)=>new Qs(e);L(Qs);class Zs extends B{constructor(t){super(),this.shape=t.length===1?t[0]:new $n(t)}check(t,n){const s=Nt(t)&&Sn(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const tr=(...e)=>new Zs(e),Mc=L(Zs),Nc=M(e=>Nt(e));class er extends B{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const $c=(e,t=null)=>new er(e,t);L(er);const vc=$c(B);class Bc extends B{constructor(t){super(),this.len=t.length-1,this.args=Rc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Fc=L(Bc),Vc=M(e=>typeof e=="function");class jc extends B{constructor(t){super(),this.shape=t}check(t,n){const s=Sn(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}L(jc,e=>e.shape.length>0);class $n extends B{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=_n(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Jt=(...e)=>e.findIndex(t=>Ae.check(t))>=0?Jt(...e.map(t=>ne(t)).map(t=>Ae.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new $n(e),Ae=L($n),nr=()=>!0,Ie=M(nr),Hc=L(Nn,e=>e.shape===nr),vn=M(e=>typeof e=="bigint"),Jc=M(e=>e===vn),sr=M(e=>typeof e=="symbol");M(e=>e===sr);const Ot=M(e=>typeof e=="number"),rr=M(e=>e===Ot),vt=M(e=>typeof e=="string"),ir=M(e=>e===vt),He=M(e=>typeof e=="boolean"),Yc=M(e=>e===He),cr=Ve(void 0);L(Fe,e=>e.shape.length===1&&e.shape[0]===void 0);Ve(void 0);const Je=Ve(null),Gc=L(Fe,e=>e.shape.length===1&&e.shape[0]===null);L(Uint8Array);L(Mn,e=>e.shape===Uint8Array);const zc=Jt(Ot,vt,Je,cr,vn,He,sr);(()=>{const e=tr(Ie),t=qs(vt,Ie),n=Jt(Ot,vt,Je,He,e,t);return e.shape=n,t.shape.values=n,n})();const ne=e=>{if(vc.check(e))return e;if(xc.check(e)){const t={};for(const n in e)t[n]=ne(e[n]);return Lc(t)}else{if(Nc.check(e))return Jt(...e.map(ne));if(zc.check(e))return Ve(e);if(Vc.check(e))return L(e)}J()},ws=cc?()=>{}:(e,t)=>{const n=new Cc;if(!t.check(e,n))throw X(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Wc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:ne(t),h:n}),this}else(t){return this.if(Ie,t)}done(){return(t,n)=>{for(let s=0;snew Wc(e),or=Pc(Ie).if(rr,(e,t)=>tn(t,cs,Ce)).if(ir,(e,t)=>Sc(t)).if(Yc,(e,t)=>ps(t)).if(Jc,(e,t)=>BigInt(tn(t,cs,Ce))).if(Ae,(e,t)=>Et(t,en(t,e.shape))).if(Oc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(Ic.check(r)){if(ps(t))continue;r=r.shape}n[s]=or(r,t)}return n}).if(Mc,(e,t)=>{const n=[],s=zs(t,0,42);for(let r=0;ren(t,e.shape)).if(Gc,(e,t)=>null).if(Fc,(e,t)=>{const n=Et(t,e.res);return()=>n}).if(Hc,(e,t)=>Et(t,en(t,[Ot,vt,Je,cr,vn,He,tr(Ot),qs(Jt("a","b","c"),Ot)]))).if(Uc,(e,t)=>{const n={},s=tn(t,0,3);for(let r=0;ror(ne(t),e),tt=typeof document<"u"?document:{},Kc=e=>tt.createElement(e),Xc=()=>tt.createDocumentFragment();M(e=>e.nodeType===io);const qc=e=>tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Qc=(e,t)=>(kc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Zc=e=>{const t=Xc();for(let n=0;n(lr(e,Zc(t)),e),lh=(e,t=[],n=[])=>to(Qc(Kc(e),t),n);M(e=>e.nodeType===no);const hh=qc;M(e=>e.nodeType===so);const eo=e=>hi(e,(t,n)=>`${n}:${t};`).join(""),lr=(e,t)=>e.appendChild(t),no=tt.ELEMENT_NODE,so=tt.TEXT_NODE;tt.CDATA_SECTION_NODE;tt.COMMENT_NODE;const ro=tt.DOCUMENT_NODE;tt.DOCUMENT_TYPE_NODE;const io=tt.DOCUMENT_FRAGMENT_NODE;M(e=>e.nodeType===ro);const it=Symbol,hr=it(),ar=it(),co=it(),oo=it(),lo=it(),ur=it(),ho=it(),Bn=it(),ao=it(),uo=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=V();let r=[],i=0;for(;i0||l.length>0?(t.push("%c"+c),n.push(l)):t.push(c)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...dr(e)),gr.forEach(t=>t.print(e))},fr=(...e)=>{console.warn(...dr(e)),e.unshift(Bn),gr.forEach(t=>t.print(e))},gr=ht(),pr=e=>({[Symbol.iterator](){return this},next:e}),wo=(e,t)=>pr(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),nn=(e,t)=>pr(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Ye{constructor(t,n){this.clock=t,this.len=n}}class Yt{constructor(){this.clients=new Map}}const Bt=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const c=i[i.length-1],o=c.id.clock+c.length;for(let l=0,a=s[l];l{let n=0,s=e.length-1;for(;n<=s;){const r=W((n+s)/2),i=e[r],c=i.clock;if(c<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&mo(n,t.clock)!==null},Fn=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Ye(r.clock,St(r.len,i.clock+i.len-r.clock)):(s{const t=new Yt;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let c=n+1;c{Z(e.clients,t,()=>[]).push(new Ye(n,s))},yo=()=>new Yt,ko=e=>{const t=yo();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Gt=(e,t)=>{w(e.restEncoder,t.clients.size),rt(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),w(e.restEncoder,n);const r=s.length;w(e.restEncoder,r);for(let i=0;i{const t=new Yt,n=y(e.restDecoder);for(let s=0;s0){const c=Z(t.clients,r,()=>[]);for(let o=0;o{const s=new Yt,r=y(e.restDecoder);for(let i=0;i0){const i=new yt;return w(i.restEncoder,0),Gt(i,s),i.toUint8Array()}return null},wr=vs;class _t extends Cn{constructor({guid:t=Gi(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:c=!1,shouldLoad:o=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=wr(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Ir,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=c,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=fs(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const l=()=>fs(a=>{const h=u=>{(u===void 0||u===!0)&&(this.off("sync",h),a())};this.on("sync",h)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const t=this._item;t!==null&&!this.shouldLoad&&D(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(rt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return D(this,t,n)}get(t,n=R){const s=Z(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==R&&r!==n)if(r===R){const i=new n;i._map=s._map,s._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=i}),i._start=s._start;for(let c=i._start;c!==null;c=c.right)c.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Rt)}getText(t=""){return this.get(t,jt)}getMap(t=""){return this.get(t,Vt)}getXmlElement(t=""){return this.get(t,Ht)}getXmlFragment(t=""){return this.get(t,kt)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,rt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new _t({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,D(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class mr{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return y(this.restDecoder)}readDsLen(){return y(this.restDecoder)}}class yr extends mr{readLeftID(){return k(y(this.restDecoder),y(this.restDecoder))}readRightID(){return k(y(this.restDecoder),y(this.restDecoder))}readClient(){return y(this.restDecoder)}readInfo(){return $t(this.restDecoder)}readString(){return lt(this.restDecoder)}readParentInfo(){return y(this.restDecoder)===1}readTypeRef(){return y(this.restDecoder)}readLen(){return y(this.restDecoder)}readAny(){return te(this.restDecoder)}readBuf(){return mc(N(this.restDecoder))}readJSON(){return JSON.parse(lt(this.restDecoder))}readKey(){return lt(this.restDecoder)}}class bo{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=y(this.restDecoder),this.dsCurrVal}readDsLen(){const t=y(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class Ft extends bo{constructor(t){super(t),this.keys=[],y(t),this.keyClockDecoder=new Ze(N(t)),this.clientDecoder=new Se(N(t)),this.leftClockDecoder=new Ze(N(t)),this.rightClockDecoder=new Ze(N(t)),this.infoDecoder=new ds(N(t),$t),this.stringDecoder=new Hi(N(t)),this.parentInfoDecoder=new ds(N(t),$t),this.typeRefDecoder=new Se(N(t)),this.lenDecoder=new Se(N(t))}readLeftID(){return new xt(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new xt(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return te(this.restDecoder)}readBuf(){return N(this.restDecoder)}readJSON(){return te(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=St(s,t[0].id.clock);const r=q(t,s);w(e.restEncoder,t.length-r),e.writeClient(n),w(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let c=r+1;c{const s=new Map;n.forEach((r,i)=>{T(t,i)>r&&s.set(i,r)}),Ge(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),w(e.restEncoder,s.size),rt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{So(e,t.clients.get(r),r,i)})},_o=(e,t)=>{const n=V(),s=y(e.restDecoder);for(let r=0;r{const s=[];let r=rt(n.keys()).sort((d,g)=>d-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let c=i();if(c===null)return null;const o=new Ir,l=new Map,a=(d,g)=>{const p=l.get(d);(p==null||p>g)&&l.set(d,g)};let h=c.refs[c.i++];const u=new Map,f=()=>{for(const d of s){const g=d.id.client,p=n.get(g);p?(p.i--,o.clients.set(g,p.refs.slice(p.i)),n.delete(g),p.i=0,p.refs=[]):o.clients.set(g,[d]),r=r.filter(S=>S!==g)}s.length=0};for(;;){if(h.constructor!==G){const g=Z(u,h.id.client,()=>T(t,h.id.client))-h.id.clock;if(g<0)s.push(h),a(h.id.client,h.id.clock-1),f();else{const p=h.getMissing(e,t);if(p!==null){s.push(h);const S=n.get(p)||{refs:[],i:0};if(S.refs.length===S.i)a(p,T(t,p)),f();else{h=S.refs[S.i++];continue}}else(g===0||g0)h=s.pop();else if(c!==null&&c.i0){const d=new yt;return jn(d,o,new Map),w(d.restEncoder,0),{missing:l,update:d.toUint8Array()}}return null},Do=(e,t)=>jn(e,t.doc.store,t.beforeState),Eo=(e,t,n,s=new Ft(e))=>D(t,r=>{r.local=!1;let i=!1;const c=r.doc,o=c.store,l=_o(s,c),a=Co(r,o,l),h=o.pendingStructs;if(h){for(const[f,d]of h.missing)if(dd)&&h.missing.set(f,d)}h.update=Le([h.update,a.update])}}else o.pendingStructs=a;const u=ms(s,r,o);if(o.pendingDs){const f=new Ft(dt(o.pendingDs));y(f.restDecoder);const d=ms(f,r,o);u&&d?o.pendingDs=Le([u,d]):o.pendingDs=u||d}else o.pendingDs=u;if(i){const f=o.pendingStructs.update;o.pendingStructs=null,Sr(r.doc,f)}},n,!1),Sr=(e,t,n,s=Ft)=>{const r=dt(t);Eo(r,e,n,new s(r))},Ao=(e,t,n)=>Sr(e,t,n,yr),Io=(e,t,n=new Map)=>{jn(e,t.store,n),Gt(e,ko(t.store))},To=(e,t=new Uint8Array([0]),n=new yt)=>{const s=_r(t);Io(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ko(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===ae)return Wo(r.map((i,c)=>c===0?i:qo(i)));if(n.constructor===yt)return Le(r)}return r[0]},Lo=(e,t)=>To(e,t,new ae),Oo=e=>{const t=new Map,n=y(e.restDecoder);for(let s=0;sOo(new mr(dt(e))),Cr=(e,t)=>(w(e.restEncoder,t.size),rt(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{w(e.restEncoder,n),w(e.restEncoder,s)}),e),xo=(e,t)=>Cr(e,Ge(t.store)),Uo=(e,t=new br)=>(e instanceof Map?Cr(t,e):xo(t,e),t.toUint8Array()),Ro=e=>Uo(e,new kr);class Mo{constructor(){this.l=[]}}const ys=()=>new Mo,ks=(e,t)=>e.l.push(t),bs=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Dr=(e,t,n)=>Un(e.l,[t,n]);class xt{constructor(t,n){this.client=t,this.clock=n}}const Tt=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,k=(e,t)=>new xt(e,t),Er=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw J()},Te=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Ar{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ah=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},No=e=>new Ar(e.type==null?null:k(e.type.client,e.type.clock),e.tname??null,e.item==null?null:k(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class $o{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const vo=(e,t,n=0)=>new $o(e,t,n),we=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Er(e):s=k(e._item.id.client,e._item.id.clock),new Ar(s,r,t,n)},uh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return we(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return we(e,k(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return we(e,s.lastId,n);s=s.right}return we(e,null,n)},Bo=(e,t)=>{const n=Ut(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Fo=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,c=e.tname,o=e.assoc;let l=null,a=0;if(r!==null){if(T(s,r.client)<=r.clock)return null;const h=n?yn(s,r):Bo(s,r),u=h.item;if(!(u instanceof E))return null;if(l=u.parent,l._item===null||!l._item.deleted){a=u.deleted||!u.countable?0:h.diff+(o>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(a+=f.length),f=f.left}}else{if(c!==null)l=t.get(c);else if(i!==null){if(T(s,i.client)<=i.clock)return null;const{item:h}=n?yn(s,i):{item:Ut(s,i)};if(h instanceof E&&h.content instanceof et)l=h.content.type;else return null}else throw J();o>=0?a=l._length:a=0}return vo(l,a,e.assoc)},dh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&Tt(e.item,t.item)&&Tt(e.type,t.type)&&e.assoc===t.assoc,At=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!he(t.ds,e.id),pn=(e,t)=>{const n=Z(e.meta,pn,ht),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Ir{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Ge=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},T=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Tr=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw J()}n.push(t)},q=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let c=W(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[c],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[q(n,t.clock)]},Ut=Vo,wn=(e,t,n)=>{const s=q(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[wn(e,n,t.clock)]},Ss=(e,t,n)=>{const s=t.clients.get(n.client),r=q(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Y&&s.splice(r+1,0,Ne(e,i,n.clock-i.id.clock+1)),i},jo=(e,t,n)=>{const s=e.clients.get(t.id.client);s[q(s,t.id.clock)]=n},Lr=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let c=wn(e,t,n),o;do o=t[c++],it.deleteSet.clients.size===0&&!ai(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Fn(t.deleteSet),Do(e,t),Gt(e,t.deleteSet),!0),Cs=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&Z(e.changed,t,ht).add(n)},_e=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof E&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Jo=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let c=r.length-1;c>=0;c--){const o=r[c],l=o.clock+o.len;for(let a=q(i,o.clock),h=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const c=n[i],o=Dn(r.length-1,1+q(r,c.clock+c.len-1));for(let l=o,a=r[l];l>0&&a.id.clock>=c.clock;a=r[l])l-=1+_e(r,l)}})},Or=(e,t)=>{if(to.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,l)})),o.push(()=>{n.changedParentTypes.forEach((l,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(l=l.filter(h=>h.target._item===null||!h.target._item.deleted),l.forEach(h=>{h.currentTarget=a,h._path=null}),l.sort((h,u)=>h.path.length-u.path.length),o.push(()=>{Dr(a._dEH,l,n)}))}),o.push(()=>s.emit("afterTransaction",[n,s])),o.push(()=>{n._needFormattingCleanup&&ul(n)})}),Un(o,[])}finally{s.gc&&Jo(i,r,s.gcFilter),Yo(i,r),n.afterState.forEach((h,u)=>{const f=n.beforeState.get(u)||0;if(f!==h){const d=r.clients.get(u),g=St(q(d,f),1);for(let p=d.length-1;p>=g;)p-=1+_e(d,p)}});for(let h=c.length-1;h>=0;h--){const{client:u,clock:f}=c[h].id,d=r.clients.get(u),g=q(d,f);g+11||g>0&&_e(d,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(po(Bn,hr,"[yjs] ",ar,ur,"Changed the client-id because another client seems to be using it."),s.clientID=wr()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const h=new ae;_s(h,n)&&s.emit("update",[h.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const h=new yt;_s(h,n)&&s.emit("updateV2",[h.toUint8Array(),n.origin,s,n])}const{subdocsAdded:o,subdocsLoaded:l,subdocsRemoved:a}=n;(o.size>0||a.size>0||l.size>0)&&(o.forEach(h=>{h.clientID=s.clientID,h.collectionid==null&&(h.collectionid=s.collectionid),s.subdocs.add(h)}),a.forEach(h=>s.subdocs.delete(h)),s.emit("subdocs",[{loaded:l,added:o,removed:a},s,n]),a.forEach(h=>h.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):Or(e,t+1)}}},D=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,c=null;e._transaction===null&&(i=!0,e._transaction=new Ho(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{c=t(e._transaction)}finally{if(i){const o=e._transaction===r[0];e._transaction=null,o&&Or(r,0)}}return c};class Go{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Ds=(e,t,n)=>{Bt(e,n.deletions,s=>{s instanceof E&&t.scope.some(r=>r===e.doc||Te(r,s))&&Kn(s,!1)})},Es=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;D(r,o=>{for(;t.length>0&&e.currStackItem===null;){const l=r.store,a=t.pop(),h=new Set,u=[];let f=!1;Bt(o,a.insertions,d=>{if(d instanceof E){if(d.redone!==null){let{item:g,diff:p}=yn(l,d.id);p>0&&(g=F(o,k(g.id.client,g.id.clock+p))),d=g}!d.deleted&&i.some(g=>g===o.doc||Te(g,d))&&u.push(d)}}),Bt(o,a.deletions,d=>{d instanceof E&&i.some(g=>g===o.doc||Te(g,d))&&!he(a.insertions,d.id)&&h.add(d)}),h.forEach(d=>{f=Pr(o,d,h,a.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const g=u[d];e.deleteFilter(g)&&(g.delete(o),f=!0)}e.currStackItem=f?a:null}o.changed.forEach((l,a)=>{l.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=o},e);const c=e.currStackItem;if(c!=null){const o=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:c,type:n,changedParentTypes:o,origin:e},e]),e.currStackItem=null}return c};class fh extends Cn{constructor(t,{captureTimeout:n=500,captureTransaction:s=l=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:c=!1,doc:o=Nt(t)?t[0].doc:t instanceof _t?t:t.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=c,this.captureTimeout=n,this.afterTransactionHandler=l=>{if(!this.captureTransaction(l)||!this.scope.some(S=>l.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(l.origin)&&(!l.origin||!this.trackedOrigins.has(l.origin.constructor)))return;const a=this.undoing,h=this.redoing,u=a?this.redoStack:this.undoStack;a?this.stopCapturing():h||this.clear(!1,!0);const f=new Yt;l.afterState.forEach((S,C)=>{const _=l.beforeState.get(C)||0,Wt=S-_;Wt>0&&se(f,C,_,Wt)});const d=at();let g=!1;if(this.lastChange>0&&d-this.lastChange0&&!a&&!h){const S=u[u.length-1];S.deletions=gn([S.deletions,l.deleteSet]),S.insertions=gn([S.insertions,f])}else u.push(new Go(l.deleteSet,f)),g=!0;!a&&!h&&(this.lastChange=d),Bt(l,l.deleteSet,S=>{S instanceof E&&this.scope.some(C=>C===l.doc||Te(C,S))&&Kn(S,!0)});const p=[{stackItem:u[u.length-1],origin:l.origin,type:a?"redo":"undo",changedParentTypes:l.changedParentTypes},this];g?this.emit("stack-item-added",p):this.emit("stack-item-updated",p)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=Nt(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof R?s.doc!==this.doc:s!==this.doc)&&fr("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Ds(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Ds(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Es(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Es(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*zo(e){const t=y(e.restDecoder);for(let n=0;nLe(e,yr,ae),Po=(e,t)=>{if(e.constructor===Y){const{client:n,clock:s}=e.id;return new Y(k(n,s+t),e.length-t)}else if(e.constructor===G){const{client:n,clock:s}=e.id;return new G(k(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new E(k(s,r+t),null,k(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Le=(e,t=Ft,n=yt)=>{if(e.length===1)return e[0];const s=e.map(h=>new t(dt(h)));let r=s.map(h=>new Hn(h,!0)),i=null;const c=new n,o=new Jn(c);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const g=f.curr.id.clock-d.curr.id.clock;return g===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===G?1:-1:g}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const h=r[0],u=h.curr.id.client;if(i!==null){let f=h.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=h.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)ct(o,i.struct,i.offset),i={struct:f,offset:0},h.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===G?i.struct.length-=g:f=Po(f,g)),i.struct.mergeWith(f)||(ct(o,i.struct,i.offset),i={struct:f,offset:0},h.next())}}else i={struct:h.curr,offset:0},h.next();for(let f=h.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==G;f=h.next())ct(o,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(ct(o,i.struct,i.offset),i=null),Yn(o);const l=s.map(h=>Vn(h)),a=gn(l);return Gt(c,a),c.toUint8Array()},Ko=(e,t,n=Ft,s=yt)=>{const r=_r(t),i=new s,c=new Jn(i),o=new n(dt(e)),l=new Hn(o,!1);for(;l.curr;){const h=l.curr,u=h.id.client,f=r.get(u)||0;if(l.curr.constructor===G){l.next();continue}if(h.id.clock+h.length>f)for(ct(c,h,St(f-h.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)ct(c,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=f;)l.next()}Yn(c);const a=Vn(o);return Gt(i,a),i.toUint8Array()},xr=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:A(e.encoder.restEncoder)}),e.encoder.restEncoder=$(),e.written=0)},ct=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&xr(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),w(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Yn=e=>{xr(e);const t=e.encoder.restEncoder;w(t,e.clientStructs.length);for(let n=0;n{const r=new n(dt(e)),i=new Hn(r,!1),c=new s,o=new Jn(c);for(let a=i.curr;a!==null;a=i.next())ct(o,t(a),0);Yn(o);const l=Vn(r);return Gt(c,l),c.toUint8Array()},qo=e=>Xo(e,sc,Ft,ae),As="You must not compute changes after the event-handler fired.";class ze{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Qo(this.currentTarget,this.target))}deletes(t){return he(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw X(As);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let c,o;if(this.adds(i)){let l=i.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(i))if(l!==null&&this.deletes(l))c="delete",o=Ke(l.content.getContent());else return;else l!==null&&this.deletes(l)?(c="update",o=Ke(l.content.getContent())):(c="add",o=void 0)}else if(this.deletes(i))c="delete",o=Ke(i.content.getContent());else return;t.set(r,{action:c,oldValue:o})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw X(As);const n=this.target,s=ht(),r=ht(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let o=null;const l=()=>{o&&i.push(o)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((o===null||o.delete===void 0)&&(l(),o={delete:0}),o.delete+=a.length,r.add(a)):this.adds(a)?((o===null||o.insert===void 0)&&(l(),o={insert:[]}),o.insert=o.insert.concat(a.content.getContent()),s.add(a)):((o===null||o.retain===void 0)&&(l(),o={retain:0}),o.retain+=a.length);o!==null&&o.retain===void 0&&l()}this._changes=t}return t}}const Qo=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},v=()=>{fr("Invalid access: Add Yjs type to a document before reading data.")},Ur=80;let Gn=0;class Zo{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Gn++}}const tl=e=>{e.timestamp=Gn++},Rr=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Gn++},el=(e,t,n)=>{if(e.length>=Ur){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,c)=>ke(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&ke(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=St(t,r.index+n))}},Pe=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;Z(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Dr(s._eH,n,t)};class R{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ys(),this._dEH=ys(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw z()}clone(){throw z()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){ks(this._eH,t)}observeDeep(t){ks(this._dEH,t)}unobserve(t){bs(this._eH,t)}unobserveDeep(t){bs(this._dEH,t)}toJSON(){}}const Mr=(e,t,n)=>{e.doc??v(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const c=i.content.getContent();if(c.length<=t)t-=c.length;else{for(let o=t;o0;o++)r.push(c[o]),s--;t=0}}i=i.right}return r},Nr=e=>{e.doc??v();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??v();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return ie(e,(s,r)=>{n.push(t(s,r,e))}),n},nl=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},vr=(e,t)=>{e.doc??v();const n=We(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,c=i.clientID,o=i.store,l=n===null?t._start:n.right;let a=[];const h=()=>{a.length>0&&(r=new E(k(c,T(o,c)),r,r&&r.lastId,l,l&&l.id,t,null,new bt(a)),r.integrate(e,0),a=[])};s.forEach(u=>{if(u===null)a.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(u);break;default:switch(h(),u.constructor){case Uint8Array:case ArrayBuffer:r=new E(k(c,T(o,c)),r,r&&r.lastId,l,l&&l.id,t,null,new ue(new Uint8Array(u))),r.integrate(e,0);break;case _t:r=new E(k(c,T(o,c)),r,r&&r.lastId,l,l&&l.id,t,null,new de(u)),r.integrate(e,0);break;default:if(u instanceof R)r=new E(k(c,T(o,c)),r,r&&r.lastId,l,l&&l.id,t,null,new et(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),h()},Br=()=>X("Length exceeded!"),Fr=(e,t,n,s)=>{if(n>t._length)throw Br();if(n===0)return t._searchMarker&&re(t._searchMarker,n,s.length),Oe(e,t,null,s);const r=n,i=We(t,n);let c=t._start;for(i!==null&&(c=i.p,n-=i.index,n===0&&(c=c.prev,n+=c&&c.countable&&!c.deleted?c.length:0));c!==null;c=c.right)if(!c.deleted&&c.countable){if(n<=c.length){n{let r=(t._searchMarker||[]).reduce((i,c)=>c.index>i.index?c:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Oe(e,t,r,n)},Vr=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,c=We(t,n);let o=t._start;for(c!==null&&(o=c.p,n-=c.index);o!==null&&n>0;o=o.right)!o.deleted&&o.countable&&(n0&&o!==null;)o.deleted||(s0)throw Br();t._searchMarker&&re(t._searchMarker,r,-i+s)},xe=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},zn=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,c=i.clientID;let o;if(s==null)o=new bt([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:o=new bt([s]);break;case Uint8Array:o=new ue(s);break;case _t:o=new de(s);break;default:if(s instanceof R)o=new et(s);else throw new Error("Unexpected content type")}new E(k(c,T(i.store,c)),r,r&&r.lastId,null,null,t,n,o).integrate(e,0)},Wn=(e,t)=>{e.doc??v();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},jr=e=>{const t={};return e.doc??v(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},Hr=(e,t)=>{e.doc??v();const n=e._map.get(t);return n!==void 0&&!n.deleted},rl=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&At(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},me=e=>(e.doc??v(),wo(e._map.entries(),t=>!t[1].deleted));class il extends ze{}class Rt extends R{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Rt;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Rt}clone(){const t=new Rt;return t.insert(0,this.toArray().map(n=>n instanceof R?n.clone():n)),t}get length(){return this.doc??v(),this._length}_callObserver(t,n){super._callObserver(t,n),Pe(this,t,new il(this,t))}insert(t,n){this.doc!==null?D(this.doc,s=>{Fr(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?D(this.doc,n=>{sl(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?D(this.doc,s=>{Vr(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return vr(this,t)}toArray(){return Nr(this)}slice(t=0,n=this.length){return Mr(this,t,n)}toJSON(){return this.map(t=>t instanceof R?t.toJSON():t)}map(t){return $r(this,t)}forEach(t){ie(this,t)}[Symbol.iterator](){return nl(this)}_write(t){t.writeTypeRef(Ol)}}const cl=e=>new Rt;class ol extends ze{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Vt extends R{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Vt}clone(){const t=new Vt;return this.forEach((n,s)=>{t.set(s,n instanceof R?n.clone():n)}),t}_callObserver(t,n){Pe(this,t,new ol(this,t,n))}toJSON(){this.doc??v();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof R?r.toJSON():r}}),t}get size(){return[...me(this)].length}keys(){return nn(me(this),t=>t[0])}values(){return nn(me(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return nn(me(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??v(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?D(this.doc,n=>{xe(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?D(this.doc,s=>{zn(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return Wn(this,t)}has(t){return Hr(this,t)}clear(){this.doc!==null?D(this.doc,t=>{this.forEach(function(n,s,r){xe(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(xl)}}const ll=e=>new Vt,ot=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&ec(e,t);class mn{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&J(),this.right.content.constructor===x?this.right.deleted||zt(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Is=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===x?t.right.deleted||zt(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?We(t,n):null;if(i){const c=new mn(i.p.left,i.p,i.index,r);return Is(e,c,n-i.index)}else{const c=new mn(null,t._start,0,r);return Is(e,c,n)}},Jr=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===x&&ot(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((c,o)=>{const l=n.left,a=n.right,h=new E(k(i,T(r.store,i)),l,l&&l.lastId,a,a&&a.id,t,null,new x(o,c));h.integrate(e,0),n.right=h,n.forward()})},zt=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Yr=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===x&&ot(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Gr=(e,t,n,s)=>{const r=e.doc,i=r.clientID,c=new Map;for(const o in s){const l=s[o],a=n.currentAttributes.get(o)??null;if(!ot(a,l)){c.set(o,a);const{left:h,right:u}=n;n.right=new E(k(i,T(r.store,i)),h,h&&h.lastId,u,u&&u.id,t,null,new x(o,l)),n.right.integrate(e,0),n.forward()}}return c},sn=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,c=i.clientID;Yr(n,r);const o=Gr(e,t,n,r),l=s.constructor===String?new Q(s):s instanceof R?new et(s):new Ct(s);let{left:a,right:h,index:u}=n;t._searchMarker&&re(t._searchMarker,n.index,l.getLength()),h=new E(k(c,T(i.store,c)),a,a&&a.lastId,h,h&&h.id,t,null,l),h.integrate(e,0),n.right=h,n.index=u,n.forward(),Jr(e,t,n,o)},Ts=(e,t,n,s,r)=>{const i=e.doc,c=i.clientID;Yr(n,r);const o=Gr(e,t,n,r);t:for(;n.right!==null&&(s>0||o.size>0&&(n.right.deleted||n.right.content.constructor===x));){if(!n.right.deleted)switch(n.right.content.constructor){case x:{const{key:l,value:a}=n.right.content,h=r[l];if(h!==void 0){if(ot(h,a))o.delete(l);else{if(s===0)break t;o.set(l,a)}n.right.delete(e)}else n.currentAttributes.set(l,a);break}default:s0){let l="";for(;s>0;s--)l+=` -`;n.right=new E(k(c,T(i.store,c)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Q(l)),n.right.integrate(e,0),n.forward()}Jr(e,t,n,o)},zr=(e,t,n,s,r)=>{let i=t;const c=V();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===x){const a=i.content;c.set(a.key,a)}i=i.right}let o=0,l=!1;for(;t!==i;){if(n===t&&(l=!0),!t.deleted){const a=t.content;if(a.constructor===x){const{key:h,value:u}=a,f=s.get(h)??null;(c.get(h)!==a||f===u)&&(t.delete(e),o++,!l&&(r.get(h)??null)===u&&f!==u&&(f===null?r.delete(h):r.set(h,f))),!l&&!t.deleted&&zt(r,a)}}t=t.right}return o},hl=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===x){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},al=e=>{let t=0;return D(e.doc,n=>{let s=e._start,r=e._start,i=V();const c=ln(i);for(;r;)r.deleted===!1&&(r.content.constructor===x?zt(c,r.content):(t+=zr(n,s,r,i,c),i=ln(c),s=r)),r=r.right}),t},ul=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&Lr(e,n.store.clients.get(s),i,r,c=>{!c.deleted&&c.content.constructor===x&&c.constructor!==Y&&t.add(c.parent)})}D(n,s=>{Bt(e,e.deleteSet,r=>{if(r instanceof Y||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===x?t.add(i):hl(s,r)});for(const r of t)al(r)})},Ls=(e,t,n)=>{const s=n,r=ln(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case et:case Ct:case Q:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];D(t,s=>{const r=new Map,i=new Map;let c=this.target._start,o=null;const l={};let a="",h=0,u=0;const f=()=>{if(o!==null){let d=null;switch(o){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof a=="object"||a.length>0)&&(d={insert:a},r.size>0&&(d.attributes={},r.forEach((g,p)=>{g!==null&&(d.attributes[p]=g)}))),a="";break;case"retain":h>0&&(d={retain:h},tc(l)||(d.attributes=Xi({},l))),h=0;break}d&&n.push(d),o=null}};for(;c!==null;){switch(c.content.constructor){case et:case Ct:this.adds(c)?this.deletes(c)||(f(),o="insert",a=c.content.getContent()[0],f()):this.deletes(c)?(o!=="delete"&&(f(),o="delete"),u+=1):c.deleted||(o!=="retain"&&(f(),o="retain"),h+=1);break;case Q:this.adds(c)?this.deletes(c)||(o!=="insert"&&(f(),o="insert"),a+=c.content.str):this.deletes(c)?(o!=="delete"&&(f(),o="delete"),u+=c.length):c.deleted||(o!=="retain"&&(f(),o="retain"),h+=c.length);break;case x:{const{key:d,value:g}=c.content;if(this.adds(c)){if(!this.deletes(c)){const p=r.get(d)??null;ot(p,g)?g!==null&&c.delete(s):(o==="retain"&&f(),ot(g,i.get(d)??null)?delete l[d]:l[d]=g)}}else if(this.deletes(c)){i.set(d,g);const p=r.get(d)??null;ot(p,g)||(o==="retain"&&f(),l[d]=p)}else if(!c.deleted){i.set(d,g);const p=l[d];p!==void 0&&(ot(p,g)?p!==null&&c.delete(s):(o==="retain"&&f(),g===null?delete l[d]:l[d]=g))}c.deleted||(o==="insert"&&f(),zt(r,c.content));break}}c=c.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class jt extends R{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??v(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new jt}clone(){const t=new jt;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new dl(this,t,n);Pe(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??v();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Q&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?D(this.doc,s=>{const r=new mn(null,this._start,0,new Map);for(let i=0;i0)&&sn(s,this,r,o,c.attributes||{})}else c.retain!==void 0?Ts(s,this,r,c.retain,c.attributes||{}):c.delete!==void 0&&Ls(s,r,c.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??v();const r=[],i=new Map,c=this.doc;let o="",l=this._start;function a(){if(o.length>0){const u={};let f=!1;i.forEach((g,p)=>{f=!0,u[p]=g});const d={insert:o};f&&(d.attributes=u),r.push(d),o=""}}const h=()=>{for(;l!==null;){if(At(l,t)||n!==void 0&&At(l,n))switch(l.content.constructor){case Q:{const u=i.get("ychange");t!==void 0&&!At(l,t)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(a(),i.set("ychange",s?s("removed",l.id):{type:"removed"})):n!==void 0&&!At(l,n)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(a(),i.set("ychange",s?s("added",l.id):{type:"added"})):u!==void 0&&(a(),i.delete("ychange")),o+=l.content.str;break}case et:case Ct:{a();const u={insert:l.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,g)=>{f[g]=d})}r.push(u);break}case x:At(l,t)&&(a(),zt(i,l.content));break}l=l.right}a()};return t||n?D(c,u=>{t&&pn(u,t),n&&pn(u,n),h()},"cleanup"):h(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?D(r,i=>{const c=ye(i,this,t,!s);s||(s={},c.currentAttributes.forEach((o,l)=>{s[l]=o})),sn(i,this,c,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?D(r,i=>{const c=ye(i,this,t,!s);sn(i,this,c,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?D(s,r=>{Ls(r,ye(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?D(r,i=>{const c=ye(i,this,t,!1);c.right!==null&&Ts(i,this,c,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?D(this.doc,n=>{xe(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?D(this.doc,s=>{zn(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return Wn(this,t)}getAttributes(){return jr(this)}_write(t){t.writeTypeRef(Ul)}}const fl=e=>new jt;class rn{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??v()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Ht||n.constructor===kt)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class kt extends R{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new kt}clone(){const t=new kt;return t.insert(0,this.toArray().map(n=>n instanceof R?n.clone():n)),t}get length(){return this.doc??v(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new rn(this,t)}querySelector(t){t=t.toUpperCase();const s=new rn(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),rt(new rn(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Pe(this,t,new wl(this,n,t))}toString(){return $r(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),ie(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?D(this.doc,s=>{Fr(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)D(this.doc,s=>{const r=t&&t instanceof R?t._item:t;Oe(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw X("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?D(this.doc,s=>{Vr(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return Nr(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return vr(this,t)}slice(t=0,n=this.length){return Mr(this,t,n)}forEach(t){ie(this,t)}_write(t){t.writeTypeRef(Ml)}}const gl=e=>new kt;class Ht extends kt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Ht(this.nodeName)}clone(){const t=new Ht(this.nodeName),n=this.getAttributes();return Qi(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof R?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const o in t)s.push(o);s.sort();const r=s.length;for(let o=0;o0?" "+n.join(" "):"";return`<${i}${c}>${super.toString()}`}removeAttribute(t){this.doc!==null?D(this.doc,n=>{xe(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?D(this.doc,s=>{zn(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return Wn(this,t)}hasAttribute(t){return Hr(this,t)}getAttributes(t){return t?rl(this,t):jr(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const c in i){const o=i[c];typeof o=="string"&&r.setAttribute(c,o)}return ie(this,c=>{r.appendChild(c.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(Rl),t.writeKey(this.nodeName)}}const pl=e=>new Ht(e.readKey());class wl extends ze{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Ue extends Vt{constructor(t){super(),this.hookName=t}_copy(){return new Ue(this.hookName)}clone(){const t=new Ue(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(Nl),t.writeKey(this.hookName)}}const ml=e=>new Ue(e.readKey());class Re extends jt{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Re}clone(){const t=new Re;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const c in t.attributes[r])i.push({key:c,value:t.attributes[r][c]});i.sort((c,o)=>c.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef($l)}}const yl=e=>new Re;class Pn{constructor(t,n){this.id=t,this.length=n}get deleted(){throw z()}mergeWith(t){return!1}write(t,n,s){throw z()}integrate(t,n){throw z()}}const kl=0;class Y extends Pn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Tr(t.doc.store,this)}write(t,n){t.writeInfo(kl),t.writeLen(this.length-n)}getMissing(t,n){return null}}class ue{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ue(this.content)}splice(t){throw z()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const bl=e=>new ue(e.readBuf());class ce{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ce(this.len)}splice(t){const n=new ce(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){se(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Sl=e=>new ce(e.readLen()),Wr=(e,t)=>new _t({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class de{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new de(Wr(this.doc.guid,this.opts))}splice(t){throw z()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const _l=e=>new de(Wr(e.readString(),e.readAny()));class Ct{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ct(this.embed)}splice(t){throw z()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Cl=e=>new Ct(e.readJSON());class x{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new x(this.key,this.value)}splice(t){throw z()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Dl=e=>new x(e.readKey(),e.readJSON());class Me{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Me(this.arr)}splice(t){const n=new Me(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Tl=e=>new Q(e.readString()),Ll=[cl,ll,fl,pl,gl,ml,yl],Ol=0,xl=1,Ul=2,Rl=3,Ml=4,Nl=5,$l=6;class et{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new et(this.type._copy())}splice(t){throw z()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const vl=e=>new et(Ll[e.readTypeRef()](e)),yn=(e,t)=>{let n=t,s=0,r;do s>0&&(n=k(n.client,n.clock+s)),r=Ut(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof E);return{item:r,diff:s}},Kn=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Ne=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new E(k(s,r+n),t,k(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=k(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Os=(e,t)=>_n(e,n=>he(n.deletions,t)),Pr=(e,t,n,s,r,i)=>{const c=e.doc,o=c.store,l=c.clientID,a=t.redone;if(a!==null)return F(e,a);let h=t.parent._item,u=null,f;if(h!==null&&h.deleted===!0){if(h.redone===null&&(!n.has(h)||Pr(e,h,n,s,r,i)===null))return null;for(;h.redone!==null;)h=F(e,h.redone)}const d=h===null?t.parent:h.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let C=u;for(;C!==null&&C.parent._item!==h;)C=C.redone===null?null:F(e,C.redone);if(C!==null&&C.parent._item===h){u=C;break}u=u.left}for(;f!==null;){let C=f;for(;C!==null&&C.parent._item!==h;)C=C.redone===null?null:F(e,C.redone);if(C!==null&&C.parent._item===h){f=C;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||he(s,u.right.id)||Os(i.undoStack,u.right.id)||Os(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=F(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==h&&(u=d._map.get(t.parentSub)||null)}const g=T(o,l),p=k(l,g),S=new E(p,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=p,Kn(S,!0),S.integrate(e,0),S};class E extends Pn{constructor(t,n,s,r,i,c,o,l){super(t,l.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=c,this.parentSub=o,this.redone=null,this.content=l,this.info=this.content.isCountable()?is:0}set marker(t){(this.info&qe)>0!==t&&(this.info^=qe)}get marker(){return(this.info&qe)>0}get keep(){return(this.info&rs)>0}set keep(t){this.keep!==t&&(this.info^=rs)}get countable(){return(this.info&is)>0}get deleted(){return(this.info&Xe)>0}set deleted(t){this.deleted!==t&&(this.info^=Xe)}markDeleted(){this.info|=Xe}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=T(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=T(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===xt&&this.id.client!==this.parent.client&&this.parent.clock>=T(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Ss(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=F(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Y||this.right&&this.right.constructor===Y)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===E?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===E&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===xt){const s=Ut(n,this.parent);s.constructor===Y?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Ss(t,t.doc.store,k(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,c=new Set;for(;r!==null&&r!==this.right;){if(c.add(r),i.add(r),Tt(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),se(t.deleteSet,this.id.client,this.id.clock,this.length),Cs(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw J();this.content.gc(t),n?jo(t,this,new Y(this.id,this.length)):this.content=new ce(this.length)}write(t,n){const s=n>0?k(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,c=this.content.getRef()&$e|(s===null?0:H)|(r===null?0:st)|(i===null?0:qt);if(t.writeInfo(c),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const o=this.parent;if(o._item!==void 0){const l=o._item;if(l===null){const a=Er(o);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(l.id)}else o.constructor===String?(t.writeParentInfo(!0),t.writeString(o)):o.constructor===xt?(t.writeParentInfo(!1),t.writeLeftID(o)):J();i!==null&&t.writeString(i)}this.content.write(t,n)}}const Kr=(e,t)=>Bl[t&$e](e),Bl=[()=>{J()},Sl,El,bl,Tl,Cl,Dl,vl,Il,_l,()=>{J()}],Fl=10;class G extends Pn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){J()}write(t,n){t.writeInfo(Fl),w(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Xr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},qr="__ $YJS$ __";Xr[qr]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Xr[qr]=!0;const Qr=new Map;class Vl{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:wc(n.newValue||"")}),Wi(this._onChange)}postMessage(t){Fs.setItem(this.room,pc(ac(t)))}close(){Pi(this._onChange)}}const jl=typeof BroadcastChannel>"u"?Vl:BroadcastChannel,Xn=e=>Z(Qr,e,()=>{const t=ht(),n=new jl(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Hl=(e,t)=>(Xn(e).subs.add(t),t),Jl=(e,t)=>{const n=Xn(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Qr.delete(e)),s},It=(e,t,n=null)=>{const s=Xn(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Zr=0,qn=1,ti=2,kn=(e,t)=>{w(e,Zr);const n=Ro(t);I(e,n)},ei=(e,t,n)=>{w(e,qn),I(e,Lo(t,n))},Yl=(e,t,n)=>ei(t,n,N(e)),ni=(e,t,n,s)=>{try{Ao(t,N(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Gl=(e,t)=>{w(e,ti),I(e,t)},zl=ni,Wl=(e,t,n,s,r)=>{const i=y(e);switch(i){case Zr:Yl(e,t,n);break;case qn:ni(e,n,s,r);break;case ti:zl(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Pl=0,Kl=(e,t,n)=>{y(e)===Pl&&n(t,lt(e))},cn=3e4;class si extends fi{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=at();this.getLocalState()!==null&&cn/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&cn<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Qn(this,s,"timeout")},W(cn/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:at()});const c=[],o=[],l=[],a=[];t===null?a.push(n):i==null?t!=null&&c.push(n):(o.push(n),Lt(i,t)||l.push(n)),(c.length>0||l.length>0||a.length>0)&&this.emit("change",[{added:c,updated:l,removed:a},"local"]),this.emit("update",[{added:c,updated:o,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const Qn=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Xt=(e,t,n=e.states)=>{const s=t.length,r=$();w(r,s);for(let i=0;i{const s=dt(t),r=at(),i=[],c=[],o=[],l=[],a=y(s);for(let h=0;h0||o.length>0||l.length>0)&&e.emit("change",[{added:i,updated:o,removed:l},n]),(i.length>0||c.length>0||l.length>0)&&e.emit("update",[{added:i,updated:c,removed:l},n])},ql=e=>Zi(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),pt=0,ri=3,Mt=1,Ql=2,fe=[];fe[pt]=(e,t,n,s,r)=>{w(e,pt);const i=Wl(t,e,n.doc,n);s&&i===qn&&!n.synced&&(n.synced=!0)};fe[ri]=(e,t,n,s,r)=>{w(e,Mt),I(e,Xt(n.awareness,Array.from(n.awareness.getStates().keys())))};fe[Mt]=(e,t,n,s,r)=>{Xl(n.awareness,N(t),n)};fe[Ql]=(e,t,n,s,r)=>{Kl(t,n.doc,(i,c)=>Zl(n,c))};const xs=3e4,Zl=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),ii=(e,t,n)=>{const s=dt(t),r=$(),i=y(s),c=e.messageHandlers[i];return c?c(r,s,e,n,i):console.error("Unable to compute message"),r},th=e=>!(e.code>=4400&&e.code<4500),bn=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,Qn(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(ci,Dn(gi(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},ci=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=at();const s=ii(e,new Uint8Array(n.data),!0);En(s)>1&&t.send(A(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{bn(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=at(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=$();if(w(n,pt),kn(n,e.doc),t.send(A(n)),e.awareness.getLocalState()!==null){const s=$();w(s,Mt),I(s,Xt(e.awareness,[e.doc.clientID])),t.send(A(s))}},e.emit("status",[{status:"connecting"}])}},on=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&It(e.bcChannel,t,e)};class eh extends Cn{constructor(t,n,s,{connect:r=!0,awareness:i=new si(s),params:c={},protocols:o=[],WebSocketPolyfill:l=WebSocket,resyncInterval:a=-1,maxBackoffTime:h=2500,disableBc:u=!1,shouldReconnect:f=th}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=h,this.shouldReconnect=f,this.params=c,this.protocols=o,this.roomname=n,this.doc=s,this._WS=l,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fe.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=$();w(d,pt),kn(d,s),this.ws.send(A(d))}},a)),this._bcSubscriber=(d,g)=>{if(g!==this){const p=ii(this,new Uint8Array(d),!1);En(p)>1&&It(this.bcChannel,A(p),this)}},this._updateHandler=(d,g)=>{if(g!==this){const p=$();w(p,pt),Gl(p,d),on(this,A(p))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:g,removed:p},S)=>{const C=d.concat(g).concat(p),_=$();w(_,Mt),I(_,Xt(i,C)),on(this,A(_))},this._exitHandler=()=>{Qn(this.awareness,[s.clientID],"app closed")},ut&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&xs{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Fo(No(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new eh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),setTimeout(()=>{this.closed||this.reached||(this.stop(),this.onUnavailable())},sh)}stop(){this.closed||(this.closed=!0,this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}isRemote(t){return this.ws!==null&&t===this.ws}peerCount(){return Math.max(0,this.awareness.getStates().size-1)}destroy(){this.closed=!0,this.ws?.destroy(),this.ws=null,this.awareness.destroy(),this.doc.destroy()}}const sh=8e3;function rh(e){return/\/p\/[^/]+\/$/.test(e)}function ih(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const Us=700;function gh(e){let t=e.seed,n=e.baseSha;const s=new Set;let r=null;const i=m=>e.onState?.(m),c=m=>e.apiBase+"upload/content?path="+encodeURIComponent(m),o=async m=>{if(!s.has(m)){if(m===t){i("clean");return}i("saving"),e.onWriting?.(),s.add(m);try{const b=await ge(c(e.path),m,n);t=m,b.sha&&(n=b.sha),i("clean"),e.onSaved?.(m)}catch(b){if(b instanceof es&&b.status===422&&ih(b)){a(m);return}if(b instanceof es&&b.status===409){if(s.delete(m),await f(m))return;await d(m,b);return}i("error")}finally{s.delete(m)}}};let l=null;const a=m=>{l||p||!e.onShrinkRefused||(i("error"),l={was:pe(t),now:pe(m),confirm:async()=>{if(p)return;const b=ft();i("saving"),e.onWriting?.();try{const j=await ge(c(e.path),b,n,!0);t=b,j.sha&&(n=j.sha),i("clean"),e.onSaved?.(b)}catch{i("error")}finally{l=null}},keep:async()=>{if(!p)try{const b=await ns(ss(e.apiBase,e.path));if(p||b.kind!=="text")return;const j=ft(),O=Pt(j,b.text);t=b.text,P(b.sha),O&&(_.text.length||g?_.doc.transact(()=>{_.text.delete(O.from,O.to-O.from),_.text.insert(O.from,O.insert)}):e.soloApply?.(O)),i("clean")}catch{i("error")}finally{l=null}}},e.onShrinkRefused(l))};let h=null;const u=()=>{h&&clearTimeout(h),h=setTimeout(()=>{const m=ft();oi(pe(t),pe(m))&&a(m)},Us)},f=async m=>{try{const b=await ns(ss(e.apiBase,e.path));if(b.kind!=="text"||!b.sha)return!1;const j=Pt(m,b.text);if(!j||j.from===j.to)return t=b.text,P(b.sha),i("clean"),!0;const O=Pt(b.text,m);if(O&&O.from!==O.to)return!1;P(b.sha);const Dt=await ge(c(e.path),m,n);return t=m,Dt.sha&&(n=Dt.sha),i("clean"),e.onSaved?.(m),!0}catch{return!1}},d=async(m,b)=>{let j="";try{j=JSON.parse(b.body).sha??""}catch{}const O=li(e.path,e.who||"browser",new Date);try{await ge(c(O),m),t=m,n=j,i("clean"),e.onConflictCopy?.(O)}catch{i("error")}};let g=!1,p=!1,S=!1,C=0;const _=new nh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),m=>{m==="live"&&(g=!0,C&&(C=0,e.onPending?.(0))),S=m==="live",e.onCollab?.(m)},()=>e.onReady(_),()=>e.onSolo(),e.me),Wt=(m,b)=>{_.isRemote(b?.origin)||(i("dirty"),g&&!S&&e.onPending?.(++C),g&&u(),!g&&(r&&clearTimeout(r),r=setTimeout(()=>o(_.text.toString()),Us)))};_.text.observe(Wt);const Zn=()=>e.onPeers?.(_.peerCount());_.awareness.on("change",Zn),rh(e.apiBase)?_.connect():queueMicrotask(()=>{p||(_.stop(),e.onSolo())});const ft=()=>_.text.length?_.text.toString():e.soloText?.()??"",P=m=>{m&&(n=m)};return{collab:_,current:ft,merge:(m,b,j)=>{if(j?.held)return t=m,P(b),"same";if(m===t||s.has(m))return P(b),"same";const O=ft();if(m===O)return t=m,P(b),g&&i("clean"),"same";const Dt=Pt(m,O),ts=!Dt||Dt.from===Dt.to;if(O!==t||_.peerCount()>0)return ts&&P(b),"blocked";const gt=Pt(O,m);return gt?!_.text.length&&!e.soloApply?"blocked":(t=m,P(b),_.text.length?_.doc.transact(()=>{_.text.delete(gt.from,gt.to-gt.from),_.text.insert(gt.from,gt.insert)}):e.soloApply(gt),"merged"):"same"},rebase:P,saveNow:()=>g?Promise.resolve():o(ft()),destroy(){r&&clearTimeout(r),h&&clearTimeout(h),p=!0;const m=ft();l?e.onShrinkWithdrawn?.(l):!g&&m&&m!==t&&o(m),_.awareness.off("change",Zn),_.text.unobserve(Wt),_.destroy()}}}export{Us as S,fh as U,uh as a,No as b,Fo as c,dh as d,St as e,lh as f,nt as g,Dn as m,gh as o,ah as r,hh as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index e2a2211a..5fca1cca 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + diff --git a/internal/webapp/upload.go b/internal/webapp/upload.go index ad8d22d8..25752167 100644 --- a/internal/webapp/upload.go +++ b/internal/webapp/upload.go @@ -21,6 +21,7 @@ import ( "github.com/runbear-io/beardrive/internal/config" "github.com/runbear-io/beardrive/internal/journal" "github.com/runbear-io/beardrive/internal/remote" + "github.com/runbear-io/beardrive/internal/textmerge" ) // Uploads run in two modes, chosen by the server per request so the client @@ -202,10 +203,16 @@ func (r *RemoteSource) commitIfBase(ctx context.Context, p, blob string, size in if !ok { return errBlobMissing } - return r.appendOpsIf(ctx, []journal.Op{{ + op := journal.Op{ Kind: journal.KindPut, Path: p, Blob: blob, Size: size, Mode: 0o644, User: who.Email, UserName: who.Name, Note: note, - }}, cb) + } + // The version this put edited from, when the writer named one: a device + // merging against this op finds its ancestor without guessing. + if cb != nil && cb.path == p && cb.sha != "" { + op.Base = cb.sha + } + return r.appendOpsIf(ctx, []journal.Op{op}, cb) } // commitBase is the version of one path a write was built on: what its @@ -698,6 +705,12 @@ func (s *Server) headFile(ctx context.Context, v *volume, p string) (FileInfo, b // Small files are exempt from the ratio, not from emptying. const ( confirmShrinkHeader = "X-Bdrive-Confirm-Shrink" + // noMergeHeader asks a conditional write to be refused on a stale base + // rather than merged: a co-editing room settles its own (ycollab.go). + noMergeHeader = "X-Bdrive-No-Merge" + // maxUploadMergeBytes bounds what a stale conditional write reads into + // memory to merge; the same bound a device merges under. + maxUploadMergeBytes = 4 << 20 shrinkRatioFloor = 256 ) @@ -747,12 +760,32 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R defer tmp.Close() project := r.PathValue("project") + org := s.orgOf(project) + if rs, ok := v.source.(*RemoteSource); ok { + s.reconcileGrants(r.Context(), project, rs.Backend) + } + base := strings.Trim(r.Header.Get("If-Match"), `"`) + if base != "" { + if head, ok := s.headBlob(r.Context(), v, p); ok && head != base && head != blob { + if handled, now := s.mergeStaleUpload(w, r, v, p, base, head, tmp, size); handled { + return + } else if now != "" { + head = now + } + writeJSONStatus(w, http.StatusConflict, map[string]any{ + "error": "this file changed since you last read it", + "sha": head, + "path": p, + }) + return + } + } + // billed is what this write actually adds: zero when the store already // holds this exact blob, which is every co-editor after the first saving // the same converged text. See billableBytes. billed := size if rs, ok := v.source.(*RemoteSource); ok { - s.reconcileGrants(r.Context(), project, rs.Backend) var billErr error billed, billErr = billableBytes(r.Context(), rs.Backend, "blobs/"+blob, size) if billErr != nil { @@ -760,8 +793,23 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R return } } - org := s.orgOf(project) if err := s.quota().CheckWrite(org, billed+s.reservedBytes(org)); err != nil { + if base != "" && billed > 0 { + v.invalidate() + if head, ok := s.headBlob(r.Context(), v, p); ok && head != base && head != blob { + if handled, now := s.mergeStaleUpload(w, r, v, p, base, head, tmp, size); handled { + return + } else if now != "" { + head = now + } + writeJSONStatus(w, http.StatusConflict, map[string]any{ + "error": "this file changed since you last read it", + "sha": head, + "path": p, + }) + return + } + } http.Error(w, err.Error(), http.StatusForbidden) return } @@ -814,19 +862,7 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R // Optional by design. A caller that sends no If-Match gets the old // behaviour, so older clients, the MCP tools and every other writer here // are untouched. - base := strings.Trim(r.Header.Get("If-Match"), `"`) if base != "" { - if head, ok := s.headBlob(r.Context(), v, p); ok && head != base { - // The current sha travels with the refusal, so the client can fetch - // what it missed without a second round trip to find out what to ask - // for. - writeJSONStatus(w, http.StatusConflict, map[string]any{ - "error": "this file changed since you last read it", - "sha": head, - "path": p, - }) - return - } if fi, ok := s.headFile(r.Context(), v, p); ok && sharpShrink(fi.Size, size) && r.Header.Get(confirmShrinkHeader) == "" { writeJSONStatus(w, http.StatusUnprocessableEntity, map[string]any{ @@ -855,8 +891,18 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R } var stale *staleWriteError if errors.As(err, &stale) { + // The write that beat this one landed between the check above and the + // append (another hub process): merged the same way, when it can be. + head := stale.head + if base != "" && head != "" { + if handled, now := s.mergeStaleUpload(w, r, v, p, base, head, tmp, size); handled { + return + } else if now != "" { + head = now + } + } writeJSONStatus(w, http.StatusConflict, map[string]any{ - "error": stale.Error(), "sha": stale.head, "path": p, + "error": stale.Error(), "sha": head, "path": p, }) return } @@ -889,6 +935,213 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head}) } +// validMergedText reports whether a clean three-way text merge of path is +// still a well-formed file of its kind. Two edits that each keep a .json +// document valid can merge into one that is not (two keys added at one +// point, with no comma between them); a merge the format refuses is a +// conflict, never a commit. Mirrors the device-side check in +// internal/syncer/merge.go. +func validMergedText(path string, merged []byte) bool { + switch strings.ToLower(filepath.Ext(path)) { + case ".json": + return json.Valid(merged) + case ".jsonl": + for _, line := range bytes.Split(merged, []byte{'\n'}) { + if line = bytes.TrimSpace(line); len(line) > 0 && !json.Valid(line) { + return false + } + } + } + return true +} + +// mergeStaleUpload settles a conditional write whose base lost a race: the +// base, the head that replaced it and the incoming bytes are merged three +// ways (textmerge), and the merge is written held to that head. handled says +// a response was written; otherwise the caller refuses with a 409 naming now +// (the newest head seen, "" if unchanged). +// +// Only text, only under maxUploadMergeBytes, only when the base can be read +// back, and never for a co-editing room's own write (noMergeHeader). A head +// that moves again while the merge is appended is merged again, up to three +// times. The merged write reaches an open room like any outside write: +// a clean room follows it, a dirty one reconciles at its next snapshot. +func (s *Server) mergeStaleUpload(w http.ResponseWriter, r *http.Request, v *volume, p, base, head string, tmp *os.File, size int64) (handled bool, now string) { + rs, ok := v.source.(*RemoteSource) + if !ok || r.Header.Get(noMergeHeader) != "" || size > maxUploadMergeBytes { + return false, "" + } + ctx := r.Context() + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return false, "" + } + incoming, err := io.ReadAll(io.LimitReader(tmp, maxUploadMergeBytes+1)) + if err != nil || len(incoming) > maxUploadMergeBytes || !textmerge.IsText(incoming) { + return false, "" + } + read := func(sha string) ([]byte, bool) { + rc, err := rs.OpenBlob(ctx, sha) + if err != nil { + return nil, false + } + defer rc.Close() + b, err := io.ReadAll(io.LimitReader(rc, maxUploadMergeBytes+1)) + if err != nil || len(b) > maxUploadMergeBytes { + return nil, false + } + return b, true + } + baseBytes, ok := read(base) + if !ok { + return false, "" + } + // A retry of a write that already landed — the response was lost, and + // somebody else has written on top of it since — carries a body the + // path's history already holds after its base. Merging it again would + // insert its lines a second time; it is already in the file's lineage. + // Only while the head still carries every line that write made, though: + // once a later edit removed or rewrote them (X -> A -> B), resubmitting + // A on X is a fresh edit to merge, and answering B unchanged would drop it. + project := projectID(r) + org := s.orgOf(project) + if rs.landedAfter(ctx, p, base, head, sha256Hex(incoming), s.requestUser(r).Email) { + if headBytes, ok := read(head); ok && textmerge.RetainsChanges(baseBytes, incoming, headBytes) { + if err := s.quota().CheckWrite(org, s.reservedBytes(org)); err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return true, head + } + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "merged": true, "unchanged": true}) + return true, head + } + } + who := s.requestUser(r) + for range 3 { + headBytes, ok := read(head) + if !ok { + return false, head + } + merged, ok := textmerge.Merge(baseBytes, headBytes, incoming) + if !ok || len(merged) > maxUploadMergeBytes || !validMergedText(p, merged) { + return false, head + } + sum := sha256.Sum256(merged) + blob := hex.EncodeToString(sum[:]) + if blob == head { + if err := s.quota().CheckWrite(org, s.reservedBytes(org)); err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return true, head + } + // The head already holds everything this write adds. + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "merged": true, "unchanged": true}) + return true, head + } + // The shrink guard holds the merge to the head it lands on. + if sharpShrink(int64(len(headBytes)), int64(len(merged))) && r.Header.Get(confirmShrinkHeader) == "" { + return false, head + } + n := int64(len(merged)) + billed, err := billableBytes(ctx, rs.Backend, "blobs/"+blob, n) + if err != nil { + storageErr(w, http.StatusBadGateway, "could not check the stored object", err) + return true, head + } + if err := s.quota().CheckWrite(org, billed+s.reservedBytes(org)); err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return true, head + } + // Blob before journal, always. + if err := rs.Backend.Put(ctx, "blobs/"+blob, bytes.NewReader(merged), n); err != nil { + http.Error(w, fmt.Sprintf("store: push blob: %v", err), http.StatusBadGateway) + return true, head + } + err = rs.commitIfBase(ctx, p, blob, n, who, "merged concurrent edits", &commitBase{path: p, sha: head, blob: blob}) + var stale *staleWriteError + if errors.As(err, &stale) { + if stale.head == "" { + return false, head // deleted meanwhile: nothing to merge onto + } + head = stale.head + continue + } + if err != nil { + http.Error(w, fmt.Sprintf("store: %v", err), http.StatusBadGateway) + return true, head + } + if billed > 0 { + s.quota().RecordUsage(org, billed) + } + v.invalidate() + s.dataWrote(ctx, project) + s.captureChange(r, "browser", 1, 0) + s.publishChange(r, "browser", []string{p}, 1, 0) + // Not inline: a dirty room settles by writing through this door, + // whose path lock the caller still holds. + go s.notifyRoomExternalWrite(project, []string{p}) + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": blob, "merged": true}) + return true, blob + } + return false, head +} + +// landedAfter reports whether the write being retried — blob, built on base, +// by user — already landed and what replaced it since was written on top of +// it. It walks the head's ancestry backwards along each put's Base link and +// stops at the NEWEST occurrence of base: only a put of blob made on that +// base by the same user, strictly between it and the head, is the retried +// write. Anything older is a different lineage — X -> A -> X -> B holds a +// put of A after a put of X, but a stale write of A against the second X is +// a fresh edit to merge, not a retry. +func (r *RemoteSource) landedAfter(ctx context.Context, path, base, head, blob, user string) bool { + if blob == base || blob == head || base == "" || head == "" { + return false + } + idx, err := r.historyIndex(ctx) + if err != nil { + return false + } + var ops []journal.Op // this path's ops, oldest first (journal.Less) + for _, so := range idx.all { + if so.Op.Path == path { + ops = append(ops, so.Op) + } + } + if len(ops) == 0 { + return false + } + // The winning op is the newest; it must be the head being merged onto. + at := len(ops) - 1 + cur := ops[at] + if cur.Kind != journal.KindPut || cur.Blob != head { + return false + } + for range len(ops) { + if at != len(ops)-1 && cur.Blob == blob && cur.Base == base && cur.User == user { + return true + } + if cur.Base == "" || cur.Base == base { + return false + } + // Step to the newest earlier put that produced cur's base. + next := -1 + for i := at - 1; i >= 0; i-- { + if ops[i].Kind == journal.KindPut && ops[i].Blob == cur.Base { + next = i + break + } + } + if next < 0 { + return false + } + at, cur = next, ops[next] + } + return false +} + +func sha256Hex(b []byte) string { + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} + // handleUploadCommit journals a direct upload after the blob is in the store. func (s *Server) handleUploadCommit(v *volume, w http.ResponseWriter, r *http.Request) { up := s.gateUpload(v, w) diff --git a/internal/webapp/upload_landed_test.go b/internal/webapp/upload_landed_test.go new file mode 100644 index 00000000..52a30308 --- /dev/null +++ b/internal/webapp/upload_landed_test.go @@ -0,0 +1,149 @@ +package webapp + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func putSHA(t *testing.T, h http.Handler, url, body, ifMatch string) string { + t.Helper() + rec := putContent(t, h, url, body, ifMatch) + if rec.Code/100 != 2 { + t.Fatalf("PUT %q (If-Match %q): %d %s", body, ifMatch, rec.Code, rec.Body.String()) + } + var out struct{ SHA string } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.SHA == "" { + t.Fatalf("PUT %q: no sha in %s", body, rec.Body.String()) + } + return out.SHA +} + +/* +The history X -> A -> X -> B holds a put of A after a put of X, but a stale +write of A built on the SECOND X is not a retry of the first: it never landed +on that X. It must be merged with B, not answered with B unchanged. +*/ +func TestUploadStaleWriteOnRevertedBaseMergesInsteadOfRetry(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + u := "/api/p/" + p.ID + "/upload/content?path=abab.md" + x := "a\nb\nc\nd\ne\n" + a := "a\nA\nc\nd\ne\n" + b := "a\nb\nc\nd\nB\n" + + x1 := putSHA(t, h, u, x, "") + a1 := putSHA(t, h, u, a, x1) + x2 := putSHA(t, h, u, x, a1) + if x2 != x1 { + t.Fatalf("same bytes, different sha: %s vs %s", x1, x2) + } + putSHA(t, h, u, b, x2) + + rec := putContent(t, h, u, a, x2) + if rec.Code/100 != 2 { + t.Fatalf("stale PUT A: %d %s", rec.Code, rec.Body.String()) + } + var out struct { + Merged bool + Unchanged bool + } + json.Unmarshal(rec.Body.Bytes(), &out) + if out.Unchanged { + t.Fatalf("stale write of A on the reverted X was treated as a landed retry: %s", rec.Body.String()) + } + got := get(t, h, "/api/p/"+p.ID+"/file?path=abab.md").Body.String() + if want := "a\nA\nc\nd\nB\n"; got != want { + t.Fatalf("file = %q, want A merged with B %q", got, want) + } +} + +/* +T5: Alice's write lands on V0, Bob's lands on top of it (merged), then +Alice's client retries her exact request after a lost response. The retry is +recognised on the head's Base chain and her line appears exactly once. +*/ +func TestUploadRetryOfLandedWriteIsIdempotent(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + u := "/api/p/" + p.ID + "/upload/content?path=t5.md" + base := "# List\n\n- item 1\n" + alice := "# List\n\n- item 1\n- alice\n" + bob := "# List\n\n- item 1\n- bob\n" + + v0 := putSHA(t, h, u, base, "") + putSHA(t, h, u, alice, v0) + if rec := putContent(t, h, u, bob, v0); rec.Code/100 != 2 && rec.Code != http.StatusConflict { + t.Fatalf("bob: %d %s", rec.Code, rec.Body.String()) + } + rec := putContent(t, h, u, alice, v0) + if rec.Code/100 != 2 { + t.Fatalf("alice retry: %d %s", rec.Code, rec.Body.String()) + } + got := get(t, h, "/api/p/"+p.ID+"/file?path=t5.md").Body.String() + if n := strings.Count(got, "- alice\n"); n != 1 { + t.Fatalf("alice appears %d times in %q", n, got) + } +} + +/* +X -> A -> B where B removed A's line: a resubmission of A built on X is on +A's lineage, but the head no longer carries A's edit. Answering B unchanged +would drop the user's write; it must be merged again (or refused). +*/ +func TestUploadResubmitAfterHeadRemovedItIsNotDiscarded(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + u := "/api/p/" + p.ID + "/upload/content?path=xab.md" + x := "a\nc\n" + a := "a\nA\nc\n" + b := "a\nc\nB\n" + + x1 := putSHA(t, h, u, x, "") + a1 := putSHA(t, h, u, a, x1) + b1 := putSHA(t, h, u, b, a1) + + rec := putContent(t, h, u, a, x1) + if rec.Code == http.StatusConflict { + return // refused, never silently discarded + } + if rec.Code/100 != 2 { + t.Fatalf("resubmit A: %d %s", rec.Code, rec.Body.String()) + } + var out struct { + SHA string + Unchanged bool + } + json.Unmarshal(rec.Body.Bytes(), &out) + if out.Unchanged || out.SHA == b1 { + t.Fatalf("resubmitted A was answered with B unchanged: %s", rec.Body.String()) + } + got := get(t, h, "/api/p/"+p.ID+"/file?path=xab.md").Body.String() + if want := "a\nA\nc\nB\n"; got != want { + t.Fatalf("file = %q, want A merged onto B %q", got, want) + } +} + +/* +Two edits that each keep config.json valid — one adds "a", the other "b", +both at the same point of an empty object — merge line-wise into a document +with no comma between the keys. The hub must refuse that merge (409) rather +than commit JSON no reader can parse, matching the device-side merge. +*/ +func TestUploadMergeRejectsInvalidCombinedJSON(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + u := "/api/p/" + p.ID + "/upload/content?path=config.json" + base := putSHA(t, h, u, "{\n}\n", "") + putSHA(t, h, u, "{\n\"a\": 1\n}\n", base) + + rec := putContent(t, h, u, "{\n\"b\": 2\n}\n", base) + if rec.Code != http.StatusConflict { + t.Fatalf("stale PUT whose merge is invalid JSON: %d %s, want 409", rec.Code, rec.Body.String()) + } + got := get(t, h, "/api/p/"+p.ID+"/file?path=config.json").Body.String() + if !json.Valid([]byte(got)) || !strings.Contains(got, `"a": 1`) || strings.Contains(got, `"b"`) { + t.Fatalf("file = %q, want the landed {\"a\": 1} left untouched", got) + } +} diff --git a/internal/webapp/ycollab.go b/internal/webapp/ycollab.go index 35e59512..0e3c6114 100644 --- a/internal/webapp/ycollab.go +++ b/internal/webapp/ycollab.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/sha256" + "encoding/base64" "encoding/hex" "encoding/json" "errors" @@ -15,8 +16,8 @@ import ( "strings" "sync" "time" - "unicode/utf16" + "github.com/reearth/ygo/cluster" "github.com/reearth/ygo/crdt" ygows "github.com/reearth/ygo/provider/websocket" "github.com/runbear-io/beardrive/internal/remote" @@ -85,6 +86,11 @@ func (s *Server) collabHookContext() context.Context { func (s *Server) ydocs() *ygows.Server { s.yOnce.Do(func() { srv := ygows.NewServer() + // A room outlives its last peer by collabRoomIdleTimeout: a reload, a + // laptop lid or a proxy dropping an idle socket comes back to the + // same warm document instead of a reseed from storage, and the + // unload (the final snapshot) runs only once the room is truly idle. + srv.RoomIdleTimeout = collabRoomIdleTimeout // Seeding, remembering and snapshotting, in the three places ygo // offers: the document is built from the file before anyone attaches, // kept addressable while the room lives, and written back when the @@ -127,7 +133,10 @@ func (s *Server) ydocs() *ygows.Server { return nil } srv.OnLastPeer = func(_ context.Context, room string) { - s.finalSnapshot(s.collabHookContext(), room) + // The last peer leaving writes the document promptly, but the + // room stays resident (RoomIdleTimeout) so this is not final: + // OnUnloadDocument owns the final snapshot. + s.snapshot(s.collabHookContext(), room, false) } srv.OnUnloadDocument = func(_ context.Context, room string) { ctx := s.collabHookContext() @@ -210,10 +219,447 @@ func (s *Server) handleYCollab(v *volume, w http.ResponseWriter, r *http.Request http.NotFound(w, r) return } - r.SetPathValue("room", projectID(r)+"/"+path) + room := projectID(r) + "/" + path + r.SetPathValue("room", room) + // Held for the whole connection: an HTTP sync closing a room it opened + // must not delete it from under this socket's join (enter). + defer s.rooms().enter(room)() s.ydocs().ServeHTTP(w, r) } +// collabRoomIdleTimeout is how long an empty room stays resident before ygo +// unloads it. A var so a test need not wait it out. +var collabRoomIdleTimeout = 2 * time.Minute + +// ycollabSyncOrigin marks the updates /ycollab/sync applies to a room. The +// relay forwards every origin but its own, so a pushed update still reaches +// other processes; local peers get it by broadcast. +var ycollabSyncOrigin = &struct{ name string }{"ycollab/sync"} + +// maxYCollabSyncBody bounds a /ycollab/sync request: a base64 update up to +// maxHistoryBytes plus a text and a base text up to maxSeedBytes each. +const maxYCollabSyncBody = maxHistoryBytes*4/3 + 3*maxSeedBytes + 4096 + +type ycollabSyncReq struct { + Update string `json:"update,omitempty"` + Base string `json:"base,omitempty"` + BaseText *string `json:"base_text,omitempty"` + Text *string `json:"text,omitempty"` + ConfirmShrink bool `json:"confirm_shrink,omitempty"` + // Peek reads the room without writing anything: its sha, text and + // state as a Yjs update. A client whose earlier sync failed after the + // room may already have applied it learns from this what landed. + Peek bool `json:"peek,omitempty"` + PriorSent []string `json:"prior_sent,omitempty"` +} + +/* +handleYCollabSync puts one client's state into a file's live room over plain +HTTP — the path a browser takes when its socket is down, or to confirm a +shrink the room would otherwise refuse. + + update is a Yjs V1 update from a synced document: applied as is, so a + returning browser's typing merges by item identity like any peer's. + Without one, text is three-way merged against the room's current text + (base_text, or the blob named by base, as the ancestor) and the merge is + spliced in hunk by hunk. A same-line clash is a 409 carrying the sha the + room stands on. + +The room then snapshots through the ordinary upload door, so every write rule +still applies; the answer is the sha the room now stands on and its text. A +room this request had to open is closed again once written. +*/ +func (s *Server) handleYCollabSync(v *volume, w http.ResponseWriter, r *http.Request) { + _ = v + path, err := cleanUploadPath(r.URL.Query().Get("path")) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if !s.writablePath(w, r, path) { + return + } + var req ycollabSyncReq + if err := json.NewDecoder(io.LimitReader(r.Body, maxYCollabSyncBody)).Decode(&req); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + var update []byte + if req.Update != "" { + if update, err = base64.StdEncoding.DecodeString(req.Update); err != nil { + http.Error(w, "update is not base64", http.StatusBadRequest) + return + } + if len(update) > maxHistoryBytes { + http.Error(w, "update too large to co-edit", http.StatusRequestEntityTooLarge) + return + } + } + if req.Text != nil && len(*req.Text) >= maxSeedBytes { + http.Error(w, "file too large to co-edit", http.StatusRequestEntityTooLarge) + return + } + ctx := r.Context() + project := projectID(r) + room := project + "/" + path + baseText := "" + if len(update) == 0 && req.Text != nil { + switch { + case req.BaseText != nil && (*req.BaseText != "" || req.Base == "" || req.Base == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"): + // Present, even empty when the file really was blank (no base, + // or the empty SHA-256). An empty base_text beside a non-empty + // blob's sha is a truncated read and falls through to blobText + // so the shrink guard sees the file's real size instead of 409. + baseText = *req.BaseText + case req.Base != "": + got, ok := s.blobText(ctx, project, req.Base) + if !ok || len(got) > maxSeedBytes { + writeJSONStatus(w, http.StatusConflict, map[string]any{ + "error": "the base version cannot be read", "sha": s.rooms().base(room), "path": path, + }) + return + } + baseText = got + } + } + + /* A room this request had to open — or an idle one it touched, which + ygo will no longer reap (Apply clears the idle stamp) — is closed again + on the way out, unless a socket is in it or joining it by then. */ + leave := s.rooms().enter(room) + closeRoom := func() { _ = s.ydocs().CloseRoom(room, false) } // unload: final snapshot, lease released + release := func() { + leave() + s.rooms().closeIfUnused(room, closeRoom) + } + + if req.Peek && len(update) == 0 && req.Text == nil && !req.ConfirmShrink { + /* Read-only: no splice, no snapshot, no syncDurable. A peek answers + even while storage refuses writes, because it promises nothing + about storage — only what the live room holds right now. */ + var peekUpdate []byte + var peekText string + /* A room already held may carry a write that just failed — an + unconfirmed shrink above all, which a close's final snapshot + would park as a conflict copy. Only a room this peek opened is + closed now; a held one gets the failed write's idle window. */ + _, _, wasHeld := s.rooms().get(room) + done := release + if wasHeld { + done = func() { + leave() + time.AfterFunc(collabRoomIdleTimeout, func() { s.rooms().closeIfUnused(room, closeRoom) }) + } + } + err := s.ydocs().Apply(ctx, room, func(doc *crdt.Doc, _ func(func(*crdt.Transaction))) { + peekUpdate, peekText = doc.EncodeStateAsUpdate(), doc.GetText("body").ToString() + }) + if err != nil && !errors.Is(err, ygows.ErrNoChanges) { + if errors.Is(err, errRoomElsewhere) { + leave() + writeJSONStatus(w, http.StatusServiceUnavailable, map[string]any{"error": err.Error(), "retry": true}) + return + } + done() + http.Error(w, fmt.Sprintf("co-editing: %v", err), http.StatusBadGateway) + return + } + sha := s.rooms().base(room) + done() + resp := map[string]any{"ok": true, "path": path, "sha": sha, "text": peekText} + if len(peekUpdate) > 0 { + resp["update"] = base64.StdEncoding.EncodeToString(peekUpdate) + } + writeJSON(w, resp) + return + } + + var ( + conflict, merged, tooLarge, pendingBusy bool + cur string + applyErr error + // wantUpdate and wantText are the room's document with this request + // in it, captured inside Apply: the version that must be on storage + // before the answer may say ok. Read after Apply returns, a keystroke + // landing in between would be folded into what this request promises. + wantUpdate []byte + wantText string + captured bool + ) + err = s.ydocs().Apply(ctx, room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + cur = txt.ToString() + defer func() { + if applyErr == nil && !conflict && !tooLarge && !pendingBusy { + wantUpdate, wantText, captured = doc.EncodeStateAsUpdate(), txt.ToString(), true + } + }() + switch { + case len(update) > 0: + /* Measured on a scratch copy first: a live room that took an + update past maxSeedBytes could neither be snapshotted whole nor + seeded again, and an applied update cannot be taken back. */ + if doc.PendingStats().Items > 0 { + pendingBusy = true + return + } + probe := crdt.New() + if applyErr = probe.ApplyUpdate(doc.EncodeStateAsUpdate()); applyErr != nil { + return + } + if applyErr = crdt.ApplyUpdateV1(probe, update, nil); applyErr != nil { + return + } + if probe.PendingStats().Items > 0 { + applyErr = errors.New("update has unintegrated pending items") + return + } + if len(probe.GetText("body").ToString()) >= maxSeedBytes { + tooLarge = true + return + } + applyErr = crdt.ApplyUpdateV1(doc, update, ycollabSyncOrigin) + case req.Text != nil: + want := *req.Text + anc := baseText + for _, sent := range req.PriorSent { + if len(sent) < maxSeedBytes && sent != anc && textmerge.RetainsChanges([]byte(anc), []byte(sent), []byte(cur)) { + anc = sent + break + } + } + if cur != anc && cur != want { + out, ok := textmerge.Merge([]byte(anc), []byte(cur), []byte(want)) + if !ok || !validMergedText(path, out) { + conflict = true + return + } + want, merged = string(out), true + } + if len(want) >= maxSeedBytes { + tooLarge = true + return + } + spliceVia(transact, txt, cur, want) + } + }) + closeIfOpened := release + if err != nil && !errors.Is(err, ygows.ErrNoChanges) { + if errors.Is(err, errRoomElsewhere) { + leave() + writeJSONStatus(w, http.StatusServiceUnavailable, map[string]any{"error": err.Error(), "retry": true}) + return + } + closeIfOpened() + http.Error(w, fmt.Sprintf("co-editing: %v", err), http.StatusBadGateway) + return + } + if applyErr != nil { + closeIfOpened() + http.Error(w, "update does not apply: "+applyErr.Error(), http.StatusBadRequest) + return + } + if pendingBusy { + closeIfOpened() + writeJSONStatus(w, http.StatusServiceUnavailable, map[string]any{"error": "room has unintegrated updates; retry", "retry": true}) + return + } + if len(update) > 0 && !tooLarge { + // Applied outside Apply's capture, so the room's own peers on this + // process are told here; the relay already has it. + _ = s.ydocs().BroadcastUpdate(ctx, room, update) + } + if conflict || tooLarge { + closeIfOpened() + code, msg := http.StatusConflict, "the same lines changed in the live document" + if tooLarge { + code, msg = http.StatusRequestEntityTooLarge, "the merge is too large to co-edit" + if len(update) > 0 { + msg = "the update makes the file too large to co-edit" + } + } + writeJSONStatus(w, code, map[string]any{"error": msg, "sha": s.rooms().base(room), "text": cur, "path": path}) + return + } + s.rooms().writer(room, s.requestUser(r)) + text, synced := wantText, wantUpdate // the room's state with this request in it + if !captured { + // Apply had nothing to run (no changes): what the room holds now. + if doc, _, held := s.rooms().get(room); held { + synced = doc.EncodeStateAsUpdate() + text, _ = replayed(synced) + } + } + if req.ConfirmShrink { + s.rooms().confirmShrink(room, text) + } + sha := "" + if s.apiMux != nil { + // ok means durable, and durable is proven on storage, never inferred + // from the room: a snapshot that met an outside write merges it into + // the live document (reconcile) and leaves writing the merge to the + // next pause — or, with a keystroke landing mid-reconcile, moves + // nothing at all (moveDoc), and the request's edit lives only in + // memory. Until storage holds it the browser keeps its edits. + var fail *snapFailure + sha, fail = s.syncDurable(ctx, room, text, synced) + if fail != nil { + /* The room holds the text and the file does not: quota (403), an + unconfirmed sharp shrink (422) or storage (502). Saying ok here + would have the browser drop its dirty state for a write that + never happened, so it gets the door's own refusal and keeps + it — retrying, or asking about the shrink. The room is not + closed now: its final snapshot would park the unconfirmed + shrink as a conflict copy before the editor could confirm it. + It stays for the idle window (the failed write's own retries + run meanwhile) and is closed then if nobody came back. */ + leave() + time.AfterFunc(collabRoomIdleTimeout, func() { s.rooms().closeIfUnused(room, closeRoom) }) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(fail.code) + _, _ = w.Write(fail.body) + return + } + } + if sha == "" { + sha = s.rooms().base(room) + } + if doc, _, held := s.rooms().get(room); held { + text, _ = replayed(doc.EncodeStateAsUpdate()) + } + release() + resp := map[string]any{"ok": true, "path": path, "sha": sha, "text": text, "merged": merged} + if len(synced) > 0 { + /* The room's state with this request in it, as a Yjs update: a + client staging a checkpoint over HTTP while it joins the socket + applies it to learn the exact item IDs the room created for its + text, so the socket's own copy of them merges as a no-op instead + of the client re-inserting the same lines a second time. */ + resp["update"] = base64.StdEncoding.EncodeToString(synced) + } + writeJSON(w, resp) +} + +// ycollabSyncDurableWait bounds how long /ycollab/sync on a process that does +// not hold a room's lease waits for the holder to write the synced text: the +// relay delivers it at once and the holder writes snapshotIdle later — but +// only once the room pauses. While several editors type continuously on the +// holder, every keystroke re-arms the idle timer, so the holder's write can +// slip all the way to snapshotMax. This wait must therefore exceed +// snapshotMax, or a non-holder answers a spurious 503 for an edit the holder +// was always going to write. A var so a test need not wait it out. +var ycollabSyncDurableWait = 8 * time.Second + +/* +awaitDurable waits for the file to hold a sync this process applied but +another process writes: the stored file says text, or the document state +stored with it knows synced. It answers the sha that holds it, or a failure +for the browser to keep its edits by. + + No relay: the holder never hears this process's update, so nothing will + write it — refused at once. + + elsewhere is false for this process's own room after syncDurable's + immediate snapshots left the edit off storage: the same wait, without + the relay requirement. + + A holder that cannot write (quota, an unconfirmed shrink, storage) looks + the same from here as a slow one, so running out of time is a 503, never + an ok for text nothing durable holds. A lease that expires meanwhile is + this process's to take: each second it snapshots again, and a write it + makes itself, or a refusal it gets, ends the wait. +*/ +func (s *Server) awaitDurable(ctx context.Context, room, text string, synced []byte, elsewhere bool) (string, *snapFailure) { + if elsewhere && s.collabRelay == nil { + return "", unwrittenSync("another process writes this file and cannot receive this edit") + } + wait := ycollabSyncDurableWait + if dl, ok := ctx.Deadline(); ok { + wait = min(wait, time.Until(dl)) + } + deadline := time.Now().Add(wait) + nextSnap := time.Now().Add(time.Second) + tick := time.NewTicker(100 * time.Millisecond) + defer tick.Stop() + for { + if sha, ok := s.syncIsDurableOnStorage(ctx, room, text, synced); ok { + return sha, nil + } + now := time.Now() + if now.After(deadline) { + return "", unwrittenSync("the edit is not written yet") + } + if now.After(nextSnap) { + nextSnap = now.Add(time.Second) + if fail := s.snapshot(ctx, room, false); fail != nil && !fail.elsewhere { + return "", fail + } + } + select { + case <-ctx.Done(): + return "", unwrittenSync("the edit is not written yet") + case <-tick.C: + } + } +} + +// unwrittenSync is the 503 a /ycollab/sync answers for an edit storage does +// not hold yet: the browser keeps its edits and retries. +func unwrittenSync(msg string) *snapFailure { + body, _ := json.Marshal(map[string]any{"error": msg, "retry": true}) + return &snapFailure{code: http.StatusServiceUnavailable, body: body} +} + +// syncDurable writes a /ycollab/sync's edit and answers the sha storage holds +// it under, or the failure the browser keeps its edits by. A few snapshots +// back to back settle what one leaves for the next pause (a reconciled merge, +// a move a keystroke refused); past those it waits, snapshotting each second, +// up to ycollabSyncDurableWait. Another process holding the lease waits for +// that process's write the same way. +func (s *Server) syncDurable(ctx context.Context, room, text string, synced []byte) (string, *snapFailure) { + for range 3 { + fail := s.snapshot(ctx, room, false) + if fail != nil { + if fail.elsewhere { + return s.awaitDurable(ctx, room, text, synced, true) + } + return "", fail + } + if sha, ok := s.syncIsDurableOnStorage(ctx, room, text, synced); ok { + return sha, nil + } + } + return s.awaitDurable(ctx, room, text, synced, false) +} + +// syncIsDurableOnStorage is the positive proof a sync's ok rests on: storage, +// not the room, holds the edit — the current file says text, the document +// state stored with the current file knows every item and deletion of +// synced, or text sits in a conflict copy this room wrote beside the file. +// Anything else, including an edit only the live document holds, is not +// durable. +func (s *Server) syncIsDurableOnStorage(ctx context.Context, room, text string, synced []byte) (string, bool) { + project, path, _ := strings.Cut(room, "/") + body, sha, _, found, err := s.freshRoomFile(ctx, room, s.roomHead(ctx, project, path)) + if err != nil { + return "", false + } + if found { + if string(body) == text { + return sha, true + } + if synced != nil { + if h := s.roomHistory(ctx, project, sha); h != nil && knows(h, synced) { + return sha, true + } + } + } + if s.rooms().parkedDurably(room, text) { + return s.rooms().base(room), true + } + return "", false +} + // seedDoc is what makes the seed CLAIM unnecessary. // // The relay could not seed: it never parsed a frame, so it had no way to turn @@ -228,7 +674,9 @@ func (s *Server) seedDoc(ctx context.Context, room string, doc *crdt.Doc) error if err := ctx.Err(); err != nil { return err } - body, sha, found, err := s.roomBytes(ctx, room) + project, path, _ := strings.Cut(room, "/") + head := s.roomHeadRecord(ctx, project, path) + body, sha, win, found, err := s.freshRoomFile(ctx, room, head.SHA) if err != nil { // Refused, so the editor retries. Opened empty, its first snapshot // would write that emptiness over a file nobody could read. @@ -240,7 +688,6 @@ func (s *Server) seedDoc(ctx context.Context, room string, doc *crdt.Doc) error if len(body) >= maxSeedBytes { return fmt.Errorf("%s is too large to co-edit", room) // a truncated seed would be written back over the rest } - project, path, _ := strings.Cut(room, "/") // The base is set for an empty file too: it is what keeps every write // this room makes conditional. s.rooms().rebase(room, sha) @@ -279,8 +726,23 @@ func (s *Server) seedDoc(ctx context.Context, room string, doc *crdt.Doc) error nothing. Only a hub that never saw this file being edited starts from the bytes. */ var newest []byte - if head := s.roomHead(ctx, project, path); head != "" && head != sha { - newest = s.roomHistory(ctx, project, head) + if head.SHA != "" && head.SHA != sha { + newest = s.roomHistory(ctx, project, head.SHA) + if newest != nil && head.Win != "" && win != "" && win < head.Win { + /* The journal fence. The head names a version that comes AFTER + the one this process's fold resolves to, in replay order — the + fold is stale (another process wrote, and even a forced + refresh has not caught up). Splicing the head back to these + older bytes would tombstone the newer edits, and the relay + would carry those deletions to every process holding the room. + So the room is built from the head as it stands; its next + write is held to that version. */ + if headText, ok := replayed(newest); ok && len(headText) < maxSeedBytes && doc.ApplyUpdate(newest) == nil { + s.rooms().rebase(room, head.SHA) + return nil + } + return fmt.Errorf("%s: this process's view of the file is older than the stored document", room) + } } if newest == nil { if state := s.roomHistory(ctx, project, sha); state != nil && replayInto(doc, state, text) { @@ -355,19 +817,48 @@ func (s *Server) claimRoomHistory(ctx context.Context, project, path, sha string return state } -// knows reports whether a stored state holds every item of another — the -// only comparison a CRDT offers: two states that spell the same text are not -// the same document. +// knows reports whether a stored state holds every item AND every deletion +// of another — the only comparison a CRDT offers: two states that spell the +// same text are not the same document. +// +// It merges other into a scratch copy of state and asks whether anything +// changed. DiffUpdateV1(other, sv) == empty cannot answer that: a V1 update +// always carries its whole delete set, so any history holding one deletion +// read as "missing something" even against itself. func knows(state, other []byte) bool { if other == nil { return true } - have, ok := docFrom(state) + probe, ok := docFrom(state) if !ok { return false } - missing, err := crdt.DiffUpdateV1(other, have.StateVector()) - return err == nil && bytes.Equal(missing, emptyUpdate) + before := probe.EncodeStateAsUpdate() + svBefore := probe.StateVector() + txtBefore := probe.GetText("body").ToString() + if err := probe.ApplyUpdate(other); err != nil { + return false + } + if !sameVector(svBefore, probe.StateVector()) || probe.GetText("body").ToString() != txtBefore { + return false + } + // No item was added, so the delete set is all that can still differ — + // and it is all a diff against the full state vector encodes. + dsBefore, err1 := crdt.DiffUpdateV1(before, svBefore) + dsAfter, err2 := crdt.DiffUpdateV1(probe.EncodeStateAsUpdate(), svBefore) + return err1 == nil && err2 == nil && bytes.Equal(dsBefore, dsAfter) +} + +func sameVector(a, b crdt.StateVector) bool { + if len(a) != len(b) { + return false + } + for c, n := range a { + if m, ok := b[c]; !ok || m != n { + return false + } + } + return true } func docFrom(state []byte) (*crdt.Doc, bool) { @@ -397,9 +888,11 @@ func replayInto(doc *crdt.Doc, state []byte, want string) bool { return doc.ApplyUpdate(state) == nil } -// splice turns txt from one text into another with a single edit: the common -// prefix and suffix are kept, the middle replaced. Offsets are UTF-16 units, -// which is what Yjs counts in. +// splice turns txt from one text into another with the minimal set of +// edits: a line diff, each changed span trimmed to the characters that +// differ (textmerge.DiffHunks). Everything unchanged between two edits stays +// the same CRDT items, so a browser's typing inside it is never deleted with +// it. Offsets are UTF-16 units, which is what Yjs counts in. func splice(doc *crdt.Doc, txt *crdt.YText, from, to string) { spliceVia(func(fn func(*crdt.Transaction)) { doc.Transact(fn) }, txt, from, to) } @@ -407,27 +900,20 @@ func splice(doc *crdt.Doc, txt *crdt.YText, from, to string) { // spliceVia is splice through a caller's transaction runner — ygo's Apply // hands one out, and only edits made through it reach the room's peers. func spliceVia(transact func(func(*crdt.Transaction)), txt *crdt.YText, from, to string) { - a, b := []rune(from), []rune(to) - p := 0 - for p < len(a) && p < len(b) && a[p] == b[p] { - p++ - } - n := 0 - for n < len(a)-p && n < len(b)-p && a[len(a)-1-n] == b[len(b)-1-n] { - n++ - } - at := len(utf16.Encode(a[:p])) - del := len(utf16.Encode(a[p : len(a)-n])) - ins := string(b[p : len(b)-n]) - if del == 0 && ins == "" { + hunks := textmerge.DiffHunks(from, to) + if len(hunks) == 0 { return } transact(func(txn *crdt.Transaction) { - if del > 0 { - txt.Delete(txn, at, del) - } - if ins != "" { - txt.Insert(txn, at, ins, nil) + // Last to first, so each hunk's offsets into `from` still hold. + for i := len(hunks) - 1; i >= 0; i-- { + h := hunks[i] + if h.End > h.Start { + txt.Delete(txn, h.Start, h.End-h.Start) + } + if h.Insert != "" { + txt.Insert(txn, h.Start, h.Insert, nil) + } } }) } @@ -605,18 +1091,62 @@ func (s *Server) storeRoomHistory(ctx context.Context, project, path, sha string // room for it builds from, on any process (seedDoc). func headKey(path string) string { return "ydoc/head/" + path } +// roomHeadRec is what ydoc/head/ holds: the blob of the newest stored +// state and, when it was known, the replay-order key (winKey, hex) of the +// journal op that produced that blob. win is the fence a stale fold is held +// to: hex preserves winKey's byte order, so comparing two of them compares +// the ops the way journal.Less does. A head written by an older hub is a +// bare sha, read with win "". +type roomHeadRec struct { + SHA string `json:"sha"` + Win string `json:"win,omitempty"` +} + +func parseRoomHead(b []byte) roomHeadRec { + b = bytes.TrimSpace(b) + if len(b) == 0 { + return roomHeadRec{} + } + if b[0] != '{' { + return roomHeadRec{SHA: string(b)} + } + var rec roomHeadRec + if json.Unmarshal(b, &rec) != nil { + return roomHeadRec{} + } + rec.SHA = strings.TrimSpace(rec.SHA) + return rec +} + +// maxHeadBytes bounds a head record: a sha and a winKey, whose length grows +// with the device id and the path. +const maxHeadBytes = 16 << 10 + func (s *Server) roomHead(ctx context.Context, project, path string) string { + return s.roomHeadRecord(ctx, project, path).SHA +} + +func (s *Server) roomHeadRecord(ctx context.Context, project, path string) roomHeadRec { be, ok := s.projectBackend(project) if !ok { - return "" + return roomHeadRec{} } rc, err := be.Get(ctx, headKey(path)) if err != nil { - return "" + return roomHeadRec{} } defer rc.Close() - sha, _ := io.ReadAll(io.LimitReader(rc, 128)) - return strings.TrimSpace(string(sha)) + b, _ := io.ReadAll(io.LimitReader(rc, maxHeadBytes)) + return parseRoomHead(b) +} + +// fileWin is the hex winKey of the op that produced fi, or "" when the fold +// did not record one. +func fileWin(fi FileInfo, path string) string { + if fi.DeviceID == "" && fi.Lamport == 0 && fi.Seq == 0 { + return "" + } + return hex.EncodeToString(winKey(fi.winOp(path))) } func (s *Server) storeRoomHead(ctx context.Context, project, path, sha string, state []byte) { @@ -627,6 +1157,39 @@ func (s *Server) storeRoomHead(ctx context.Context, project, path, sha string, s if !ok { return } + // The op that wrote sha, when this process's fold resolves the path to + // it — every caller stores a state right after writing or reading it. + win := "" + if _, fi, found, err := s.roomFileInfo(ctx, project+"/"+path); err == nil && found && fi.Blob == sha { + win = fileWin(fi, path) + } + rec, _ := json.Marshal(roomHeadRec{SHA: sha, Win: win}) + // newer reports whether rec may replace prev, or that nothing is to do. + newer := func(prev roomHeadRec) (write bool) { + if prev.SHA == sha { + return win != "" && prev.Win != win // learning the fence for the same head + } + if prev.Win != "" && win != "" { + // Both ends of the comparison are journal positions: the head + // never moves back in replay order, whatever the states say. + return win > prev.Win + } + if prev.SHA != "" && len(state) > 0 { + if prevState := s.roomHistory(ctx, project, prev.SHA); prevState != nil { + stateHasPrev := knows(state, prevState) + prevHasState := knows(prevState, state) + if prevHasState && !stateHasPrev { + return false + } + if !stateHasPrev || prevHasState { + if _, curSHA, found, ferr := s.roomBytes(ctx, project+"/"+path); ferr == nil && found && curSHA == prev.SHA { + return false + } + } + } + } + return true + } if cp, ok := be.(remote.ConditionalPutter); ok { const maxHeadAttempts = 8 for range maxHeadAttempts { @@ -635,25 +1198,10 @@ func (s *Server) storeRoomHead(ctx context.Context, project, path, sha string, s log.Printf("bdrive: reading room head %s/%s: %v", project, path, err) return } - prevSHA := strings.TrimSpace(string(existing)) - if prevSHA == sha { + if !newer(parseRoomHead(existing)) { return } - if prevSHA != "" && len(state) > 0 { - if prevState := s.roomHistory(ctx, project, prevSHA); prevState != nil { - stateHasPrev := knows(state, prevState) - prevHasState := knows(prevState, state) - if prevHasState && !stateHasPrev { - return - } - if !stateHasPrev || prevHasState { - if _, curSHA, found, ferr := s.roomBytes(ctx, project+"/"+path); ferr == nil && found && curSHA == prevSHA { - return - } - } - } - } - _, err = cp.PutIf(ctx, headKey(path), strings.NewReader(sha), int64(len(sha)), version) + _, err = cp.PutIf(ctx, headKey(path), bytes.NewReader(rec), int64(len(rec)), version) if err == nil { return } @@ -665,7 +1213,10 @@ func (s *Server) storeRoomHead(ctx context.Context, project, path, sha string, s log.Printf("bdrive: storing room head %s/%s: concurrent head contention", project, path) return } - if err := be.Put(ctx, headKey(path), strings.NewReader(sha), int64(len(sha))); err != nil { + if prev := s.roomHeadRecord(ctx, project, path); !newer(prev) { + return + } + if err := be.Put(ctx, headKey(path), bytes.NewReader(rec), int64(len(rec))); err != nil { log.Printf("bdrive: storing room head %s/%s: %v", project, path, err) } } @@ -687,41 +1238,79 @@ func (s *Server) projectBackend(project string) (remote.Backend, bool) { // the file is not there; a file that is there but cannot be read right now is // an error, never an empty file. func (s *Server) roomBytes(ctx context.Context, room string) (body []byte, sha string, found bool, err error) { + body, fi, found, err := s.roomFile(ctx, room) + return body, fi.Blob, found, err +} + +// roomFileInfo resolves a room's path in the fold that includes every write +// already accepted (volume.current). +func (s *Server) roomFileInfo(ctx context.Context, room string) (*volume, FileInfo, bool, error) { project, path, ok := strings.Cut(room, "/") if !ok || !projectIDRe.MatchString(project) { - return nil, "", false, nil + return nil, FileInfo{}, false, nil } if s.Projects != nil { if _, known := s.Projects.Get(project); !known { - return nil, "", false, nil + return nil, FileInfo{}, false, nil } } _, v, err := s.projectVolume(project) if err != nil { - return nil, "", false, err + return nil, FileInfo{}, false, err } // A room is built from what the file IS, not from a snapshot a background // rebuild has not caught up on yet. snap, err := v.current(ctx) if err != nil { - return nil, "", false, err + return nil, FileInfo{}, false, err } fi, ok := snap.files[path] if !ok { - return nil, "", false, nil + return v, FileInfo{}, false, nil + } + return v, fi, true, nil +} + +// roomFile is roomBytes with the whole FileInfo, provenance included. +func (s *Server) roomFile(ctx context.Context, room string) ([]byte, FileInfo, bool, error) { + v, fi, found, err := s.roomFileInfo(ctx, room) + if err != nil || !found { + return nil, FileInfo{}, false, err } + _, path, _ := strings.Cut(room, "/") rc, err := v.source.Open(ctx, path, fi) if err != nil { - return nil, "", false, err + return nil, FileInfo{}, false, err } defer rc.Close() // One byte past the bound, so a caller can tell a whole file from a // prefix: anything longer than maxSeedBytes is only the start of one. - body, err = io.ReadAll(io.LimitReader(rc, maxSeedBytes+1)) + body, err := io.ReadAll(io.LimitReader(rc, maxSeedBytes+1)) if err != nil { - return nil, "", false, err + return nil, FileInfo{}, false, err + } + return body, fi, true, nil +} + +// freshRoomFile is roomFile for a seed, with the op that produced the file +// (win, see roomHeadRec). volume.current covers the writes THIS process +// accepted; another process's are seen only once the cached fold expires. +// A head naming a different blob says somebody wrote since, so the fold is +// rebuilt from the journals before the seed trusts it. +func (s *Server) freshRoomFile(ctx context.Context, room, headSHA string) (body []byte, sha, win string, found bool, err error) { + body, fi, found, err := s.roomFile(ctx, room) + if err == nil && headSHA != "" && (!found || fi.Blob != headSHA) { + project, _, _ := strings.Cut(room, "/") + if _, v, verr := s.projectVolume(project); verr == nil { + v.invalidate() + body, fi, found, err = s.roomFile(ctx, room) + } + } + if err != nil || !found { + return nil, "", "", found, err } - return body, fi.Blob, true, nil + _, path, _ := strings.Cut(room, "/") + return body, fi.Blob, fileWin(fi, path), true, nil } // snapshotRoom writes the document back to the file. @@ -738,11 +1327,11 @@ func (s *Server) roomBytes(ctx context.Context, room string) (body []byte, sha s // and the change frame are then the same code every other write goes through; // a second path into the file would be a second set of rules to keep in // agreement. -func (s *Server) snapshotRoom(ctx context.Context, room string) { s.snapshot(ctx, room, false) } +func (s *Server) snapshotRoom(ctx context.Context, room string) { _ = s.snapshot(ctx, room, false) } // finalSnapshot is the write made as the room empties: nobody is left to see // the document, so a version the file refuses is parked beside it instead. -func (s *Server) finalSnapshot(ctx context.Context, room string) { s.snapshot(ctx, room, true) } +func (s *Server) finalSnapshot(ctx context.Context, room string) { _ = s.snapshot(ctx, room, true) } // snapshotSeam, when set by a test, runs inside a snapshot once it has read // the document and before it reads the file. @@ -753,15 +1342,32 @@ var snapshotSeam func(room string) // this two could write and file history in either order: the slower one would // name an older version as the room's head and base after a newer one, and the // next room would be built from it. -func (s *Server) snapshot(ctx context.Context, room string, final bool) { +func (s *Server) snapshot(ctx context.Context, room string, final bool) *snapFailure { unlock := s.rooms().lockSnapshots(room) defer unlock() - s.snapshotLocked(ctx, room, final) + return s.snapshotLocked(ctx, room, final) +} + +// snapFailure is a snapshot that left the room's text unwritten because the +// file could not be read or the upload door refused it — quota (403), an +// unconfirmed sharp shrink (422), storage (502). code and body are what the +// door answered, so a caller relaying it (/ycollab/sync) hands the browser +// the same refusal a direct save would have got. Nil for everything else, +// including a refusal the room settled itself (reconcile) and a room another +// process writes. +type snapFailure struct { + code int + body []byte + // elsewhere: another process holds the room's lease, so this one wrote + // nothing and cannot say whether the file holds the text. Not a refusal + // — the caller has to look at storage for the holder's write + // (awaitDurable). + elsewhere bool } // snapshotLocked is snapshot for a caller already holding the room's // snapshot lock. -func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { +func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) (failed *snapFailure) { if ctx.Err() != nil { return } @@ -803,7 +1409,7 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { if final && strings.TrimSpace(text) != "" { s.finishLater(ctx, room, who, text, base, state) } - return + return storageFailure(err) } if have && curSha == s.rooms().yieldedTo(room) { // Already parked beside this version, which the room cannot hold. @@ -853,9 +1459,15 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { // time to, so this process's browsers see the save land. bg := s.collabContext() if ctx.Err() == nil && bg.Err() == nil { + // Looked before and the file still does not say this: the + // writer is late or wedged, and until somebody writes it the + // relay's retained window is all a later process can replay. + if s.rooms().waited(room) { + s.republishRoom(ctx, room, state) + } s.rooms().awaitWriter(room, func() { s.snapshotRoom(bg, room) }) } - return + return &snapFailure{elsewhere: true} } if s.apiMux == nil { return @@ -880,6 +1492,7 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { s.storeRoomHistory(ctx, project, path, sha, state) s.rooms().rebase(room, sha) } + s.rooms().settled(room) case http.StatusConflict: // Somebody OUTSIDE the room wrote the file — an agent, the CLI, a // device — since the hub last did. Everyone inside the room shares @@ -891,6 +1504,9 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { if final && strings.TrimSpace(text) != "" { s.finishLater(ctx, room, who, text, base, state) } + if err != nil { + return storageFailure(err) + } return } // A base this source cannot read back still parks rather than merges. @@ -905,6 +1521,9 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { nothing in it the file does not already hold. */ if !final || s.rooms().isParked(room, text) { log.Printf("bdrive: not snapshotting %s: the room's text would empty or sharply shrink it", path) + if !final { + failed = &snapFailure{code: w.code, body: w.body.Bytes()} + } return } if fileHolds(string(cur), text) || s.copyHolds(ctx, project, path, text) { @@ -918,7 +1537,52 @@ func (s *Server) snapshotLocked(ctx context.Context, room string, final bool) { copy := conflictPath(path, who, time.Now()) s.parkCopy(ctx, who, project, path, copy, text) return + default: + // The door or the storage behind it failed. While editors remain, + // look again with backoff: otherwise the room's text waits for the + // next keystroke, or for nobody if the typing has stopped. A final + // snapshot's text is owned by the unload path. + log.Printf("bdrive: snapshotting %s: upload answered %d", path, w.code) + if final { + return + } + code := w.code + if code < 400 { + code = http.StatusBadGateway // a write that never answered is a failed write + } + failed = &snapFailure{code: code, body: w.body.Bytes()} + if bg := s.collabContext(); ctx.Err() == nil && bg.Err() == nil { + // Nothing durable holds this text but this process's document + // and the relay's retained window — which trims by age. Each + // failed attempt re-publishes the whole state, so a process + // opening the room later still replays it however long the + // outage lasts. + s.republishRoom(ctx, room, state) + s.rooms().retryLater(room, func() { s.snapshotRoom(bg, room) }) + } } + return +} + +// republishRoom hands a room's whole state to the relay again. Applying it is +// a no-op for every process that already has it, so it is safe to repeat; its +// point is the relay's RETAINED window, which is the only place a process +// opening the room later can learn edits no snapshot has written yet. Without +// a relay there is no other process to tell. +func (s *Server) republishRoom(ctx context.Context, room string, state []byte) { + if s.collabRelay == nil || len(state) == 0 { + return + } + if err := s.collabRelay.Publish(ctx, cluster.Outbound{Room: room, Kind: cluster.KindSync, Data: state}); err != nil { + log.Printf("bdrive: re-publishing %s to the relay: %v", room, err) + } +} + +// storageFailure is the snapFailure for a file this process could not read +// back before writing: a 502, as the upload door answers a storage error. +func storageFailure(err error) *snapFailure { + body, _ := json.Marshal(map[string]any{"error": "reading the file: " + err.Error()}) + return &snapFailure{code: http.StatusBadGateway, body: body} } /* @@ -938,47 +1602,9 @@ wrote: an agent appending to the notes, a device syncing, the CLI. */ func (s *Server) reconcile(ctx context.Context, room string, who User, text, baseText string, haveBase bool, theirs, theirSha string, final bool) { project, path, _ := strings.Cut(room, "/") - // roomBytes and blobText stop just past maxSeedBytes. A prefix taken for the - // whole file would be merged and written back over its tail, so a file - // that large is only ever parked beside. - whole := len(theirs) < maxSeedBytes && len(baseText) < maxSeedBytes - // Only text is merged or appended: a binary outside write mixed with the - // room's lines would be a file that is neither. - whole = whole && textmerge.IsText([]byte(theirs)) && textmerge.IsText([]byte(baseText)) && textmerge.IsText([]byte(text)) - var merged []byte - canMerge := false - if whole && haveBase { - merged, canMerge = textmerge.Merge([]byte(baseText), []byte(text), []byte(theirs)) - } - target, ok := "", false - switch { - case !whole: - // parked below - case canMerge && len(merged) < maxSeedBytes: - // Two sides under the bound can insert past it together, and a - // merge no room could open again is parked rather than written. - target, ok = string(merged), true - case appendedBoth(baseText, haveBase, theirs, text): - // Both sides only added to the end: an agent appending to a daily - // note while somebody types at its foot. The line merge has no order - // for two insertions at one point; this room is the file's only - // writer, so it picks one: theirs, then what the room added, each - // exactly as written, repeated lines and blank lines included. Too - // big to write, it is parked: the checks below match lines and would - // take a repeated line or a blank one as already in the file. - if both := joinAppends(theirs, strings.TrimPrefix(text, baseText)); len(both) < maxSeedBytes { - target, ok = both, true - } - case fileHolds(theirs, text) || s.copyHolds(ctx, project, path, text): - target, ok = theirs, true - case haveBase && strings.TrimSpace(baseText) == "": - // Both sides wrote into an empty file — a template arriving while - // somebody already typed. There is no ancestor to order them by, and - // neither is a revision of the other: keep both, theirs first. - if both := appendNew(theirs, text); len(both) < maxSeedBytes { - target, ok = both, true - } - } + target, ok, whole := reconcileTarget(path, text, baseText, haveBase, theirs, func(t string) bool { + return fileHolds(theirs, t) || s.copyHolds(ctx, project, path, t) + }) park := func() { // parkCopy owns the text from here and retries a failing store, so // the room can move onto their version without it being the only @@ -1021,11 +1647,79 @@ func (s *Server) reconcile(ctx context.Context, room string, who User, text, bas s.moveDoc(ctx, room, text, target, theirSha, true, true) return } - if s.moveDoc(ctx, room, text, target, theirSha, target == theirs, false) && target == text { + /* Not against text alone. This read text before the storage round trips + that found their write, and with several editors typing, somebody + always typed in between: a move refused on any keystroke never lands + while the meeting goes on, and their write stays out of the room. So + the document as it stands, inside the same Apply that splices it, is + merged against their version again — microseconds, no I/O, nobody can + type in between. A copy already parked is not consulted here: that is + storage, and a live text it alone would hold waits for the next pause. */ + recompute := func(cur string) (string, bool, bool) { + to, ok, _ := reconcileTarget(path, cur, baseText, haveBase, theirs, func(t string) bool { return fileHolds(theirs, t) }) + return to, to == theirs, ok + } + from, landed, moved := s.moveDocLive(ctx, room, text, target, theirSha, target == theirs, recompute) + if moved && landed == from { + // The document did not change, so nothing re-arms its timer: what it + // holds is still unwritten. s.snapshotLocked(ctx, room, false) } } +// reconcileTarget is reconcile's decision, with no storage in it but holds: +// the text the room should move to when the file says theirs, the room says +// text and both came from baseText — or !ok, when only parking keeps text. +// whole is false for a side too large or not text, which is never merged. +func reconcileTarget(path, text, baseText string, haveBase bool, theirs string, holds func(text string) bool) (target string, ok, whole bool) { + // roomBytes and blobText stop just past maxSeedBytes. A prefix taken for the + // whole file would be merged and written back over its tail, so a file + // that large is only ever parked beside. + whole = len(theirs) < maxSeedBytes && len(baseText) < maxSeedBytes + // Only text is merged or appended: a binary outside write mixed with the + // room's lines would be a file that is neither. + whole = whole && textmerge.IsText([]byte(theirs)) && textmerge.IsText([]byte(baseText)) && textmerge.IsText([]byte(text)) + appended := whole && appendedBoth(baseText, haveBase, theirs, text) + var merged []byte + canMerge := false + if whole && haveBase && !appended { + merged, canMerge = textmerge.Merge([]byte(baseText), []byte(text), []byte(theirs)) + canMerge = canMerge && validMergedText(path, merged) + } + switch { + case !whole: + // parked by the caller + case appended: + // Both sides only added to the end: an agent appending to a daily + // note while somebody types at its foot. The line merge orders two + // insertions at one point by content; this room is the file's only + // writer, so it keeps them as they happened: theirs, then what the + // room added, each exactly as written, repeated lines and blank lines + // included. Too big to write, it is parked — never handed to the + // line merge or the checks below, which match lines and would take a + // repeated line or a blank one as already in the file. + if both := joinAppends(theirs, strings.TrimPrefix(text, baseText)); len(both) < maxSeedBytes { + return both, true, whole + } + case canMerge: + // Two sides under the bound can insert past it together, and a + // merge no room could open again is parked rather than written. + if len(merged) < maxSeedBytes { + return string(merged), true, whole + } + case holds(text): + return theirs, true, whole + case haveBase && strings.TrimSpace(baseText) == "": + // Both sides wrote into an empty file — a template arriving while + // somebody already typed. There is no ancestor to order them by, and + // neither is a revision of the other: keep both, theirs first. + if both := appendNew(theirs, text); len(both) < maxSeedBytes { + return both, true, whole + } + } + return "", false, whole +} + // moveDoc brings a room's document from text to to, as one edit, and rebases // the room onto sha, reporting whether it did. A document typed into since it // read text is left alone with its base: that typing is in neither version, @@ -1041,29 +1735,118 @@ func (s *Server) reconcile(ctx context.Context, room string, who User, text, bas // replays the same items, and a returning browser that typed some of them // merges once instead of beside a second copy spliced in from the bytes. func (s *Server) moveDoc(ctx context.Context, room, text, to, sha string, filed, final bool) bool { + if !final { + _, _, moved := s.moveDocLive(ctx, room, text, to, sha, filed, nil) + return moved + } var state []byte moved := false - if final { - if doc, _, held := s.rooms().get(room); held { - txt := doc.GetText("body") - if txt.ToString() == text { - spliceVia(func(fn func(*crdt.Transaction)) { doc.Transact(fn) }, txt, text, to) - state, moved = doc.EncodeStateAsUpdate(), true - } - } - } else { - _ = s.ydocs().Apply(ctx, room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { - txt := doc.GetText("body") - if txt.ToString() != text { - return - } - spliceVia(transact, txt, text, to) + if doc, _, held := s.rooms().get(room); held { + txt := doc.GetText("body") + if txt.ToString() == text { + spliceVia(func(fn func(*crdt.Transaction)) { doc.Transact(fn) }, txt, text, to) state, moved = doc.EncodeStateAsUpdate(), true - }) + } } - if !moved { - return false + if moved { + s.settleMove(ctx, room, to, sha, filed, state) + } + return moved +} + +// moveDocOrigin marks the delta a move applies to a live room. Like +// ycollabSyncOrigin, the relay forwards it and local peers get it by +// broadcast. +var moveDocOrigin = &struct{ name string }{"ycollab/move"} + +// moveDocLive is moveDoc on a live room, which a keystroke can reach at any +// moment: ygo's Apply holds the document's lock only inside transact, and +// reading the text takes that lock too, so no text read can be pinned to the +// splice that follows it. The move is therefore never made in character +// offsets on the live document. It is made on a private copy of one atomic +// snapshot of it, and only the resulting update — items anchored to the +// snapshot's items by ID, a delete set by ID — is applied to the room, where +// it integrates around anything typed meanwhile instead of landing a few +// characters off. +// +// The snapshot spelling something other than text means it was typed into. +// Without recompute it is left alone (park: typing nobody parked must never +// be overwritten). With it, recompute answers from the snapshot the text to +// move to, whether that is exactly what sha holds, and whether there is a +// move at all. from is the snapshot's text and landed the text moved to. +func (s *Server) moveDocLive(ctx context.Context, room, text, to, sha string, filed bool, recompute func(cur string) (to string, filed, ok bool)) (from, landed string, moved bool) { + yd := s.ydocs() + doc := yd.GetDoc(room) + if doc == nil { + // Not resident: open it as Apply always has, then work on it. + if err := yd.Apply(ctx, room, func(*crdt.Doc, func(func(*crdt.Transaction))) {}); err != nil && !errors.Is(err, ygows.ErrNoChanges) { + return "", "", false + } + if doc = yd.GetDoc(room); doc == nil { + return "", "", false + } } + snap := doc.EncodeStateAsUpdate() + scratch := crdt.New() + if err := crdt.ApplyUpdateV1(scratch, snap, nil); err != nil || scratch.PendingStats().Items > 0 { + return "", "", false // an update still missing its causes: the next pause + } + txt := scratch.GetText("body") + cur := txt.ToString() + if cur != text { + if recompute == nil { + return "", "", false + } + liveTo, liveFiled, ok := recompute(cur) + if !ok { + return "", "", false // a true conflict: the next pause settles it + } + to, filed = liveTo, liveFiled + } + state := snap + if cur != to { + var deltas [][]byte + unsub := scratch.OnUpdate(func(u []byte, _ any) { deltas = append(deltas, append([]byte(nil), u...)) }) + spliceVia(func(fn func(*crdt.Transaction)) { scratch.Transact(fn) }, txt, cur, to) + unsub() + if len(deltas) == 0 { + return "", "", false + } + delta := deltas[0] + if len(deltas) > 1 { + merged, err := crdt.MergeUpdatesV1(deltas...) + if err != nil { + return "", "", false + } + delta = merged + } + // Applied to the hub's document — which feeds the relay, persistence + // and this room's snapshot timer — then broadcast to this process's + // sockets, which an update applied outside Apply does not reach. + if err := crdt.ApplyUpdateV1(doc, delta, moveDocOrigin); err != nil { + return "", "", false + } + _ = yd.BroadcastUpdate(ctx, room, delta) + state = doc.EncodeStateAsUpdate() + } + /* state may hold a keystroke that landed between snap and the apply. + It is not re-checked, rolled back or held off the rebase: an update + anchored to items merges with it exactly as two peers' keystrokes + merge — its inserts are never in the move's delete set, its deletes + can only name items both already had — so neither edit is lost, even + on one line. The document then holds everything sha holds, so rebasing + onto sha is what makes the next pause write move and keystroke + together on top of it. Left on the old base, that pause would meet sha + again, reconcile text that already carries their write, and park + copies of what the file holds. settleMove files state under sha only + when it spells exactly to. */ + s.settleMove(ctx, room, to, sha, filed, state) + return cur, to, true +} + +// settleMove rebases a room whose document moved to to, storing the moved +// state under sha when to is exactly what sha holds. +func (s *Server) settleMove(ctx context.Context, room, to, sha string, filed bool, state []byte) { if filed { if spelled, ok := replayed(state); ok && spelled == to { project, path, _ := strings.Cut(room, "/") @@ -1071,7 +1854,6 @@ func (s *Server) moveDoc(ctx context.Context, room, text, to, sha string, filed, } } s.rooms().rebase(room, sha) - return true } // appendedBoth reports whether theirs and text each extend base, which ends a @@ -1213,6 +1995,7 @@ func (s *Server) parkCopy(ctx context.Context, who User, project, path, copy, te cw := s.putAs(ctx, who, project, copy, text, "") if cw.code == http.StatusOK { log.Printf("bdrive: %s: the room's text could not be written to it; parked beside it as %s", path, copy) + s.rooms().parkedOnStorage(project+"/"+path, text) return true } log.Printf("bdrive: %s: could not park the room's refused text (%d bytes) as %s (%d); retrying", path, len(text), copy, cw.code) @@ -1380,7 +2163,16 @@ func (s *Server) putAs(ctx context.Context, who User, project, path, text, base } if base != "" { req.Header.Set("If-Match", base) + // An editor in the room confirmed this exact text shrinking the + // file (/ycollab/sync confirm_shrink). + if s.rooms().shrinkConfirmed(project+"/"+path, text) { + req.Header.Set(confirmShrinkHeader, "1") + } } + // The room settles a refusal itself, against its live document + // (reconcile); the door merging on its behalf would file the room's + // state under a blob that spells something else. + req.Header.Set(noMergeHeader, "1") // The human, never the hub: an op authored by "the server" is a // regression in History even when the server is holding the pen. req = withUser(req, who) @@ -1444,10 +2236,20 @@ type roomRegistry struct { // parked is the text a room last set aside as a conflict copy, so the // two final snapshots (last peer, unload) park it once. parked map[string]string + // stored is the text of the conflict copy a room last got onto storage: + // what lets /ycollab/sync call an edit set aside there durable. + stored map[string]string // yielded is a file version this room parked beside and will not write // over: one too large to hold or merge, so the room's text cannot be // settled against it and every later write would erase it. yielded map[string]string + // joins counts who is using each room right now — a socket for its whole + // connection, a /ycollab/sync for its whole request — and closing holds + // the rooms closeIfUnused is closing, each closed once its close returns; + // both under joinMu, which is never held across a close (enter). + joinMu sync.Mutex + joins map[string]int + closing map[string]chan struct{} // leases is what this process holds for each room, under its own lock // because taking one is a storage round-trip (lease.go). leaseMu sync.Mutex @@ -1456,6 +2258,12 @@ type roomRegistry struct { // waits counts how many times a room on a process that does not write // it has looked for the writer's write since the last edit. waits map[string]int + // retries counts a room's snapshot attempts the upload door failed, for + // backoff (retryLater). + retries map[string]int + // shrinkOK is the sha256 of a text an editor confirmed may sharply shrink + // the file (confirm_shrink on /ycollab/sync). + shrinkOK map[string]string // snapLocks serializes each room's snapshots (lockSnapshots). snapLocks map[string]*roomSnapLock } @@ -1503,8 +2311,8 @@ func (s *Server) rooms() *roomRegistry { s.roomReg = &roomRegistry{ docs: map[string]*crdt.Doc{}, gens: map[string]uint64{}, users: map[string]User{}, bases: map[string]string{}, pending: map[string]*roomFlush{}, unsubs: map[string]func(){}, - parked: map[string]string{}, yielded: map[string]string{}, leases: map[string]*roomLease{}, renewals: map[string]chan struct{}{}, - waits: map[string]int{}, + parked: map[string]string{}, stored: map[string]string{}, yielded: map[string]string{}, leases: map[string]*roomLease{}, renewals: map[string]chan struct{}{}, + waits: map[string]int{}, retries: map[string]int{}, shrinkOK: map[string]string{}, } }) return s.roomReg @@ -1550,6 +2358,26 @@ func (r *roomRegistry) park(room, text string) { r.parked[room] = text } +// parkedOnStorage records that room's text is written as a conflict copy, +// for a room still open: a copy finished after the room is gone has no +// sync left to answer. +func (r *roomRegistry) parkedOnStorage(room, text string) { + r.mu.Lock() + defer r.mu.Unlock() + if _, open := r.docs[room]; open { + r.stored[room] = text + } +} + +// parkedDurably reports whether text is what the room last wrote as a +// conflict copy. +func (r *roomRegistry) parkedDurably(room, text string) bool { + r.mu.Lock() + defer r.mu.Unlock() + prev, ok := r.stored[room] + return ok && prev == text +} + func (r *roomRegistry) yield(room, sha string) { r.mu.Lock() defer r.mu.Unlock() @@ -1581,8 +2409,9 @@ The hub is the only writer while a room is live. So nobody in the room writes. The hub holds the document, sees every update, and writes ONCE per pause: two seconds after the last change, or - ten seconds after the first if the typing never pauses — the numbers - Hocuspocus settled on for onStoreDocument, for the same reasons. One + six seconds after the first if the typing never pauses — Hocuspocus's + onStoreDocument shape, with a deadline short enough that a non-holder's + /ycollab/sync (ycollabSyncDurableWait) always outlasts it. One writer means an If-Match refusal can only ever come from someone outside the room, which is exactly the case it should be reserved for. @@ -1592,9 +2421,12 @@ The hub is the only writer while a room is live. */ // Vars, not consts: a test that waits ten real seconds to see a deadline fire // is a test nobody runs. Production never sets them. +// snapshotMax keeps a continuously edited room at no more than one write per +// six seconds (≈0.167/s, six times under GCS's one-write-per-second limit on +// a single object) and must stay below ycollabSyncDurableWait. var ( snapshotIdle = 2 * time.Second - snapshotMax = 10 * time.Second + snapshotMax = 6 * time.Second ) func (s *Server) watchRoom(room string, doc *crdt.Doc) { @@ -1656,12 +2488,102 @@ func (r *roomRegistry) arm(room string, p *roomFlush, wait time.Duration, flush // refused quota) must not keep a timer alive forever. const maxWriterWaits = 10 +// writerWaitLimit is maxWriterWaits, or enough looks to outlast a lease whose +// holder died: once it expires the next look takes it (holdLease) and this +// process writes the room itself. +func writerWaitLimit() int { + n := maxWriterWaits + if snapshotIdle > 0 { + n = max(n, int(leaseTTL/snapshotIdle)+2) + } + return n +} + +// waited reports whether a room has already looked once for another +// process's write since its last edit (awaitWriter). +func (r *roomRegistry) waited(room string) bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.waits[room] > 0 +} + +// enter marks room as in use until leave is called. +// +// A room /ycollab/sync opened is closed again once written, and that close +// must never take a room out from under a socket that is joining it. +// +// ygo cannot do this for us: RoomIdleTimeout reaps only a room a peer LEFT +// (handleDisconnect stamps idleSince), and Apply clears that stamp — so a +// room only ever touched over HTTP, or an idle one an HTTP sync touched, +// would stay resident, leased and never finally written for the life of the +// process. And CloseRoom(force=false) checks for registered peers only: a +// socket between ServeHTTP's room lookup and its registration is not one +// yet, and the close deletes the room it is about to join. +// +// So every user of a room — a socket for the whole of its ServeHTTP, a sync +// request for the whole of its handler — holds a count under joinMu, and +// the close runs only when that count is zero. The close itself is a final +// snapshot, a storage round-trip, so it runs with joinMu released: the room +// is marked closing instead, and only an enter of THAT room waits for it — +// every other room keeps entering and leaving. A socket that arrives during +// the close waits for it, then opens a fresh room seeded from the file the +// close just wrote. +func (r *roomRegistry) enter(room string) (leave func()) { + r.joinMu.Lock() + for { + ch, busy := r.closing[room] + if !busy { + break + } + r.joinMu.Unlock() + <-ch + r.joinMu.Lock() + } + if r.joins == nil { + r.joins = map[string]int{} + } + r.joins[room]++ + r.joinMu.Unlock() + return func() { + r.joinMu.Lock() + if r.joins[room]--; r.joins[room] <= 0 { + delete(r.joins, room) + } + r.joinMu.Unlock() + } +} + +// closeIfUnused runs shut while nobody is in the room, holding off every +// enter of that room — and only that room — until it returns. A close +// already running for the room is left to finish alone. +func (r *roomRegistry) closeIfUnused(room string, shut func()) { + r.joinMu.Lock() + if r.joins[room] > 0 || r.closing[room] != nil { + r.joinMu.Unlock() + return + } + if r.closing == nil { + r.closing = map[string]chan struct{}{} + } + ch := make(chan struct{}) + r.closing[room] = ch + delete(r.joins, room) + r.joinMu.Unlock() + defer func() { + r.joinMu.Lock() + delete(r.closing, room) + close(ch) + r.joinMu.Unlock() + }() + shut() +} + // awaitWriter looks at the file again after another process has had time to // write it, so that this process's browsers see the save land. func (r *roomRegistry) awaitWriter(room string, flush func()) { r.mu.Lock() defer r.mu.Unlock() - if r.pending[room] != nil || r.waits[room] >= maxWriterWaits { + if r.pending[room] != nil || r.waits[room] >= writerWaitLimit() { return } r.waits[room]++ @@ -1670,11 +2592,66 @@ func (r *roomRegistry) awaitWriter(room string, flush func()) { r.arm(room, p, snapshotIdle, flush) } +// snapshotRetryMax caps the backoff between snapshots the upload door +// failed. A var so a test need not wait out real backoff. +var snapshotRetryMax = 30 * time.Second + +// retryLater arms another snapshot after a failed one, doubling the wait up +// to snapshotRetryMax. There is no attempt limit: while the room is live +// and unwritten its text exists nowhere durable, so giving up would leave it +// to the relay's age-trimmed window. The chain ends by itself — a write that +// lands (or a file that already says this) settles the room, and a closed +// room's flush finds no room and arms nothing. An edit arming its own +// snapshot meanwhile supersedes it. +func (r *roomRegistry) retryLater(room string, flush func()) { + r.mu.Lock() + defer r.mu.Unlock() + if r.retries == nil { + r.retries = map[string]int{} + } + if r.pending[room] != nil { + return + } + n := r.retries[room] + r.retries[room] = n + 1 + wait := snapshotIdle << min(n, 6) // shift bounded: never overflows + if wait <= 0 || wait > snapshotRetryMax { + wait = snapshotRetryMax + } + p := &roomFlush{deadline: time.Now().Add(wait)} + r.pending[room] = p + r.arm(room, p, wait, flush) +} + +// confirmShrink records that an editor confirmed text may sharply shrink +// the file; the room's write of exactly that text then says so. +func (r *roomRegistry) confirmShrink(room, text string) { + sum := sha256.Sum256([]byte(text)) + r.mu.Lock() + defer r.mu.Unlock() + if r.shrinkOK == nil { + r.shrinkOK = map[string]string{} + } + r.shrinkOK[room] = hex.EncodeToString(sum[:]) +} + +func (r *roomRegistry) shrinkConfirmed(room, text string) bool { + r.mu.Lock() + want, ok := r.shrinkOK[room] + r.mu.Unlock() + if !ok { + return false + } + sum := sha256.Sum256([]byte(text)) + return hex.EncodeToString(sum[:]) == want +} + // settled is the file saying what the room says: nothing left to wait for. func (r *roomRegistry) settled(room string) { r.mu.Lock() defer r.mu.Unlock() delete(r.waits, room) + delete(r.retries, room) } // settle waits until no armed or running snapshot is left. Drop the rooms @@ -1738,9 +2715,12 @@ func (r *roomRegistry) dropLocked(room string) { delete(r.renewals, room) } delete(r.waits, room) + delete(r.retries, room) + delete(r.shrinkOK, room) delete(r.docs, room) delete(r.users, room) delete(r.parked, room) + delete(r.stored, room) delete(r.yielded, room) // bases outlives the room on purpose: it is how the NEXT room for this // file finds the history to rebuild from when somebody wrote the file @@ -1776,8 +2756,7 @@ func (s *Server) contains(ctx context.Context, doc *crdt.Doc, project, sha strin if state == nil { return false } - missing, err := crdt.DiffUpdateV1(state, doc.StateVector()) - return err == nil && bytes.Equal(missing, emptyUpdate) + return knows(doc.EncodeStateAsUpdate(), state) } // emptyUpdate is what DiffUpdateV1 answers when nothing is missing. diff --git a/internal/webapp/ycollab_sync_test.go b/internal/webapp/ycollab_sync_test.go new file mode 100644 index 00000000..36666afd --- /dev/null +++ b/internal/webapp/ycollab_sync_test.go @@ -0,0 +1,1427 @@ +package webapp + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/reearth/ygo/cluster" + "github.com/reearth/ygo/crdt" + ygoclient "github.com/reearth/ygo/provider/client" + + "github.com/runbear-io/beardrive/internal/remote" + "github.com/runbear-io/beardrive/internal/textmerge" +) + +func syncAs(t *testing.T, h http.Handler, id, path string, body map[string]any) *httptest.ResponseRecorder { + t.Helper() + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", "/api/p/"+id+"/ycollab/sync?path="+path, bytes.NewReader(data)) + req = withUser(req, User{Email: "editor@example.com", Name: "An Editor"}) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func roomText(s *Server, room string) string { + if d := s.ydocs().GetDoc(room); d != nil { + return d.GetText("body").ToString() + } + return "" +} + +func conflictTexts(t *testing.T, s *Server, id, path string) map[string]string { + t.Helper() + _, v, _ := s.projectVolume(id) + snap, err := v.current(context.Background()) + if err != nil { + t.Fatal(err) + } + out := map[string]string{} + for p := range snap.files { + if strings.HasPrefix(p, path+".bdrive-conflict-") { + out[p] = get(t, s.Handler(), "/api/p/"+id+"/file?path="+p).Body.String() + } + } + return out +} + +func waitUntil(d time.Duration, cond func() bool) bool { + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if cond() { + return true + } + time.Sleep(25 * time.Millisecond) + } + return cond() +} + +// A sync whose snapshot the upload door refuses must say so. Answering ok +// would have the browser drop its dirty state for a write that never landed; +// relaying the door's 422 is what makes it ask the user, and the confirmed +// retry then lands. +func TestYCollabSyncRelaysTheDoorsRefusal(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) // before newHub's settle: a resident room keeps its lease renewing + big := strings.Repeat("a line somebody wrote\n", 100) + sha := shaOf(big) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, big, "") + + rec := syncAs(t, h, p.ID, path, map[string]any{"base": sha, "base_text": big, "text": "tiny\n"}) + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("unconfirmed shrink: %d %s, want 422", rec.Code, rec.Body) + } + var refusal struct { + Shrink bool `json:"shrink"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &refusal); err != nil { + t.Fatal(err) + } + if !refusal.Shrink { + t.Fatalf("the refusal does not say shrink: %s", rec.Body) + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); f != big { + t.Fatalf("the file changed under a refused write: %q", f) + } + // Not closed on a refusal: a final snapshot now would park the + // unconfirmed text as a conflict copy before anyone could confirm it. + if _, _, ok := srv.rooms().get(room); !ok { + t.Fatal("the refused room was closed") + } + + rec = syncAs(t, h, p.ID, path, map[string]any{"base": sha, "base_text": big, "text": "tiny\n", "confirm_shrink": true}) + if rec.Code != http.StatusOK { + t.Fatalf("confirmed shrink: %d %s", rec.Code, rec.Body) + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); f != "tiny\n" { + t.Fatalf("file = %q after the confirmed shrink", f) + } + if slices.Contains(srv.ydocs().Rooms(), room) { + t.Fatal("a room only this sync used is still resident after it was written") + } + if n := len(conflictTexts(t, srv, p.ID, path)); n != 0 { + t.Fatalf("%d conflict copies, want 0", n) + } +} + +// A truncated read that handed the editor "" alongside a non-empty file's ETag +// must hit the 422 shrink guard (asking the user) rather than 409-parking "x". +func TestYCollabSyncTruncatedEmptyBaseTextHitsShrinkGuard(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "daily.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) + big := "## Snow\n" + strings.Repeat("- shipped the thing\n", 60) + sha := shaOf(big) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, big, "") + + rec := syncAs(t, h, p.ID, path, map[string]any{"base": sha, "base_text": "", "text": "x"}) + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("truncated empty base_text: %d %s, want 422 shrink refusal", rec.Code, rec.Body) + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); f != big { + t.Fatalf("file changed under truncated-read shrink refusal: %q", f) + } +} + +// A room a sync opened is closed on the way out — but never from under a +// socket that is in it or joining it (handleYCollab holds the room for its +// whole connection). +func TestYCollabSyncLeavesAJoinedRoomOpen(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, "one\n", "") + + leave := srv.rooms().enter(room) // a socket mid-join + rec := syncAs(t, h, p.ID, path, map[string]any{"base": shaOf("one\n"), "base_text": "one\n", "text": "one\ntwo\n"}) + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body) + } + if !slices.Contains(srv.ydocs().Rooms(), room) { + t.Fatal("the sync closed a room a socket was joining") + } + leave() + + rec = syncAs(t, h, p.ID, path, map[string]any{"base": shaOf("one\ntwo\n"), "base_text": "one\ntwo\n", "text": "one\ntwo\nthree\n"}) + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body) + } + if slices.Contains(srv.ydocs().Rooms(), room) { + t.Fatal("an unused room stayed resident after the sync") + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); f != "one\ntwo\nthree\n" { + t.Fatalf("file = %q", f) + } +} + +// base_text present but empty is an ancestor that was a blank file — never +// "absent, read the blob named by base instead". +func TestYCollabSyncEmptyBaseTextIsTheAncestor(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, "a\n", "") + + // Against the blob ("a\n" == the room) this would overwrite to "hello\n"; + // against "" both sides added, so the room's "a\n" must survive. + merged, ok := textmerge.Merge(nil, []byte("a\n"), []byte("hello\n")) + rec := syncAs(t, h, p.ID, path, map[string]any{"base": shaOf("a\n"), "base_text": "", "text": "hello\n"}) + file := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String() + if !ok { + if rec.Code != http.StatusConflict { + t.Fatalf("sync: %d %s, want 409 (merged against \"\")", rec.Code, rec.Body) + } + if file != "a\n" { + t.Fatalf("file = %q after a refused merge", file) + } + return + } + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body) + } + if file != string(merged) || file == "hello\n" { + t.Fatalf("file = %q, want %q (merged against \"\", not the base blob)", file, merged) + } +} + +// retryBlobs fails blob writes while fail says so, keeping compare-and-swap. +type retryBlobs struct { + remote.Backend + cond remote.ConditionalPutter + fail func() bool +} + +func (b *retryBlobs) Put(ctx context.Context, key string, r io.Reader, size int64) error { + if strings.Contains(key, "blobs/") && b.fail() { + return errors.New("storage unavailable") + } + return b.Backend.Put(ctx, key, r, size) +} + +func (b *retryBlobs) GetVersioned(ctx context.Context, key string) (io.ReadCloser, remote.Version, error) { + return b.cond.GetVersioned(ctx, key) +} + +func (b *retryBlobs) PutIf(ctx context.Context, key string, r io.Reader, size int64, expect remote.Version) (remote.Version, error) { + if strings.Contains(key, "blobs/") && b.fail() { + return remote.VersionAbsent, errors.New("storage unavailable") + } + return b.cond.PutIf(ctx, key, r, size, expect) +} + +// countingRelay counts the whole-state republishes a failing room makes. +type countingRelay struct { + cluster.Relay + syncs atomic.Int32 +} + +func (c *countingRelay) Publish(ctx context.Context, out cluster.Outbound) error { + if out.Kind == cluster.KindSync { + c.syncs.Add(1) + } + return c.Relay.Publish(ctx, out) +} + +// A room whose writes keep failing keeps trying — at a capped interval and +// republishing its state each time — for as long as it lives unwritten: +// past the eight attempts that used to be the end of it. +func TestYCollabRoomRetriesPastEightFailuresUntilStorageRecovers(t *testing.T) { + fastRoom(t, 5*time.Millisecond, 50*time.Millisecond) + oldMax := snapshotRetryMax + snapshotRetryMax = 20 * time.Millisecond + t.Cleanup(func() { snapshotRetryMax = oldMax }) + var attempts, broken atomic.Int32 + snapshotSeam = func(string) { attempts.Add(1) } + t.Cleanup(func() { snapshotSeam = nil }) + var flaky *retryBlobs + srv, p, _ := newHub(t, true, func(be remote.Backend) remote.Backend { + flaky = &retryBlobs{Backend: be, cond: be.(remote.ConditionalPutter), fail: func() bool { return false }} + return flaky + }) + relay := &countingRelay{Relay: cluster.NewMemRelay()} + if err := srv.useCollabRelay(relay); err != nil { + t.Fatal(err) + } + h := srv.Handler() + path := "notes.md" + url := "/api/p/" + p.ID + "/file?path=" + path + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, "base\n", "") + // Attempts 1–9 fail; storage recovers on attempt 10. + flaky.fail = func() bool { + if attempts.Load() < 10 { + broken.Add(1) + return true + } + return false + } + doc := openRoom(t, srv, p.ID+"/"+path) + typeInto(doc, "typed\n") + if !waitFile(t, h, url, "base\ntyped\n", 5*time.Second) { + t.Fatalf("never written: %d attempts, file %q", attempts.Load(), get(t, h, url).Body.String()) + } + if n := attempts.Load(); n < 10 { + t.Fatalf("written after %d attempts, want ≥10", n) + } + if broken.Load() < 9 { + t.Fatalf("%d failed writes, want ≥9", broken.Load()) + } + if n := relay.syncs.Load(); n < 9 { + t.Fatalf("republished %d times across 9 failures", n) + } + // Written: the chain ends. + time.Sleep(100 * time.Millisecond) + before := attempts.Load() + time.Sleep(200 * time.Millisecond) + if after := attempts.Load(); after != before { + t.Fatalf("still snapshotting after the write landed: %d → %d", before, after) + } +} + +// A sync landing on a process that does not hold the room's lease is ok only +// once the holder's write of it is on storage — and never when the holder +// cannot write it. +func TestYCollabSyncNonHolderWaitsForDurableWriteAndRefusesWhenHolderBlocked(t *testing.T) { + fastRoom(t, 50*time.Millisecond, 500*time.Millisecond) + oldWait := ycollabSyncDurableWait + ycollabSyncDurableWait = 1500 * time.Millisecond + t.Cleanup(func() { ycollabSyncDurableWait = oldWait }) + a, b, p := newHubPair(t) + relay := cluster.NewMemRelay() + for _, s := range []*Server{a, b} { + if err := s.useCollabRelay(relay); err != nil { + t.Fatal(err) + } + } + ha, hb := a.Handler(), b.Handler() + path := "notes.md" + room := p.ID + "/" + path + url := "/api/p/" + p.ID + "/file?path=" + path + putContent(t, ha, "/api/p/"+p.ID+"/upload/content?path="+path, "base\n", "") + a.rooms().writer(room, coEditor) + // A live peer on A: A writes the room and takes the lease. + if err := a.ydocs().Apply(context.Background(), room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + transact(func(txn *crdt.Transaction) { txt.Insert(txn, txt.Len(), "from A\n", nil) }) + }); err != nil { + t.Fatal(err) + } + if !waitFile(t, ha, url, "base\nfrom A\n", 5*time.Second) { + t.Fatal("A never wrote its edit") + } + if b.holdLease(context.Background(), room) { + t.Fatal("B took the lease A holds") + } + + t.Run("holder writes", func(t *testing.T) { + want := "base\nfrom A\nfrom B\n" + rec := syncAs(t, hb, p.ID, path, map[string]any{"base": shaOf("base\nfrom A\n"), "base_text": "base\nfrom A\n", "text": want}) + if rec.Code != http.StatusOK { + t.Fatalf("sync via B: %d %s", rec.Code, rec.Body) + } + var out struct { + SHA string `json:"sha"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if out.SHA != shaOf(want) { + t.Fatalf("B answered sha %s, want the durable %s", out.SHA, shaOf(want)) + } + if f := get(t, ha, url).Body.String(); f != want { + t.Fatalf("ok answered but the file says %q", f) + } + }) + + t.Run("holder blocked", func(t *testing.T) { + a.Quota = fullQuota{} + t.Cleanup(func() { a.Quota = nil }) + before := get(t, ha, url).Body.String() + rec := syncAs(t, hb, p.ID, path, map[string]any{"base": shaOf(before), "base_text": before, "text": before + "unwritten\n"}) + if rec.Code < 300 { + t.Fatalf("sync via B acknowledged a write A cannot make: %d %s", rec.Code, rec.Body) + } + if rec.Code != http.StatusServiceUnavailable && rec.Code != http.StatusForbidden && + rec.Code != http.StatusUnprocessableEntity && rec.Code != http.StatusBadGateway { + t.Fatalf("sync via B: %d %s", rec.Code, rec.Body) + } + if f := get(t, ha, url).Body.String(); f != before { + t.Fatalf("file = %q under a refused write", f) + } + }) + + for _, s := range []*Server{a, b} { + s.Close(context.Background()) + s.rooms().settle() + } +} + +// Without a relay the holder never hears this process's update: refused at +// once, never acknowledged. +func TestYCollabSyncNonHolderWithoutRelayRefuses(t *testing.T) { + a, _, p := newHubPair(t) + room := p.ID + "/notes.md" + if _, fail := a.awaitDurable(context.Background(), room, "x\n", nil, true); fail == nil || fail.code != http.StatusServiceUnavailable { + t.Fatalf("awaitDurable without a relay = %+v, want 503", fail) + } +} + +// An outside write racing a sync is merged into the live document by +// reconcile, which leaves writing the merge to the room's next pause. The +// sync's ok means durable, so it answers only once the merge is on storage — +// and refuses when that write fails. +func TestYCollabSyncOkOnlyOnceTheReconciledMergeIsWritten(t *testing.T) { + base := "l1\nl2\nl3\nl4\nl5\n" + room := "L1 from the room\nl2\nl3\nl4\nl5\n" + outside := "l1\nl2\nl3\nl4\nL5 from outside\n" + merged := "L1 from the room\nl2\nl3\nl4\nL5 from outside\n" + + run := func(t *testing.T, failAfterReconcile bool) { + fastRoom(t, time.Hour, time.Hour) + var flaky *retryBlobs + var broken atomic.Bool + srv, p, _ := newHub(t, true, func(be remote.Backend) remote.Backend { + flaky = &retryBlobs{Backend: be, cond: be.(remote.ConditionalPutter), fail: broken.Load} + return flaky + }) + h := srv.Handler() + path := "notes.md" + up := "/api/p/" + p.ID + "/upload/content?path=" + path + file := "/api/p/" + p.ID + "/file?path=" + path + t.Cleanup(func() { srv.dropRoom(p.ID + "/" + path) }) + putContent(t, h, up, base, "") + + var calls atomic.Int32 + snapshotSeam = func(string) { + switch calls.Add(1) { + case 1: // an agent writes the file while the sync snapshots + if rec := putContent(t, h, up, outside, shaOf(base)); rec.Code != http.StatusOK { + t.Errorf("outside write: %d %s", rec.Code, rec.Body) + } + case 2: + broken.Store(failAfterReconcile) + } + } + t.Cleanup(func() { snapshotSeam = nil; broken.Store(false) }) + + rec := syncAs(t, h, p.ID, path, map[string]any{"base": shaOf(base), "base_text": base, "text": room}) + got := get(t, h, file).Body.String() + if failAfterReconcile { + if rec.Code/100 == 2 { + t.Fatalf("sync answered %d with the merge unwritten (file %q)", rec.Code, got) + } + if got == merged { + t.Fatalf("the merge was written through a failing store") + } + return + } + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body) + } + if got != merged { + t.Fatalf("sync answered ok while the file holds %q, want the merge %q", got, merged) + } + var out struct{ SHA, Text string } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if out.SHA != shaOf(merged) || out.Text != merged { + t.Fatalf("answered sha %s text %q, want the merge's", out.SHA, out.Text) + } + } + t.Run("written", func(t *testing.T) { run(t, false) }) + t.Run("storage fails", func(t *testing.T) { run(t, true) }) +} + +// A sync that fails on storage may already have put its text into the live +// room. A peek tells the browser what the room holds — text and Yjs state — +// without writing, so it answers 200 while blob writes still fail. +func TestYCollabSyncPeekReadsTheRoomWhileStorageFails(t *testing.T) { + fastRoom(t, time.Hour, time.Hour) + var broken atomic.Bool + srv, p, _ := newHub(t, true, func(be remote.Backend) remote.Backend { + return &retryBlobs{Backend: be, cond: be.(remote.ConditionalPutter), fail: broken.Load} + }) + h := srv.Handler() + path := "notes.md" + file := "/api/p/" + p.ID + "/file?path=" + path + t.Cleanup(func() { srv.dropRoom(p.ID + "/" + path); broken.Store(false) }) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, "log\n", "") + + broken.Store(true) + rec := syncAs(t, h, p.ID, path, map[string]any{"base": shaOf("log\n"), "base_text": "log\n", "text": "log\nx\n"}) + if rec.Code != http.StatusBadGateway { + t.Fatalf("sync through a failing store: %d %s, want 502", rec.Code, rec.Body) + } + if f := get(t, h, file).Body.String(); f != "log\n" { + t.Fatalf("file = %q under a failing store", f) + } + + rec = syncAs(t, h, p.ID, path, map[string]any{"peek": true}) + if rec.Code != http.StatusOK { + t.Fatalf("peek: %d %s", rec.Code, rec.Body) + } + var out struct { + OK bool `json:"ok"` + SHA string `json:"sha"` + Text string `json:"text"` + Update string `json:"update"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !out.OK || out.Text != "log\nx\n" { + t.Fatalf("peek = %+v, want the room's text with the failed sync in it", out) + } + if out.SHA != shaOf("log\n") { + t.Fatalf("peek sha = %s, want the room's unchanged base %s", out.SHA, shaOf("log\n")) + } + raw, err := base64.StdEncoding.DecodeString(out.Update) + if err != nil { + t.Fatal(err) + } + doc := crdt.New() + if err := crdt.ApplyUpdateV1(doc, raw, nil); err != nil { + t.Fatal(err) + } + if got := doc.GetText("body").ToString(); got != "log\nx\n" { + t.Fatalf("peek update holds %q", got) + } + if f := get(t, h, file).Body.String(); f != "log\n" { + t.Fatalf("a peek wrote the file: %q", f) + } + if _, _, held := srv.rooms().get(p.ID + "/" + path); !held { + t.Fatal("a peek closed the room holding a failed write") + } +} + +// A keystroke landing while reconcile merges an outside write used to make +// moveDoc refuse the move; it now re-merges the document as it stands, inside +// the Apply that moves it, so the keystroke and the outside write both land in +// the room. The sync's ok must still rest on storage holding the edit, never +// on the room looking settled — so a store that fails after the reconcile is +// a refusal, and one that works answers the sha that holds it. +func TestYCollabSyncDurableDespiteMoveDocRefusal(t *testing.T) { + base := "l1\nl2\nl3\nl4\nl5\n" + room := "L1 from the room\nl2\nl3\nl4\nl5\n" + outside := "l1\nl2\nl3\nl4\nL5 from outside\n" + final := "L1 from the room\nl2\nl3 typed mid-reconcile\nl4\nL5 from outside\n" + + run := func(t *testing.T, failAfterReconcile bool) { + fastRoom(t, time.Hour, time.Hour) + oldWait := ycollabSyncDurableWait + ycollabSyncDurableWait = 300 * time.Millisecond + t.Cleanup(func() { ycollabSyncDurableWait = oldWait }) + var broken atomic.Bool + srv, p, _ := newHub(t, true, func(be remote.Backend) remote.Backend { + return &retryBlobs{Backend: be, cond: be.(remote.ConditionalPutter), fail: broken.Load} + }) + h := srv.Handler() + path := "notes.md" + roomID := p.ID + "/" + path + up := "/api/p/" + p.ID + "/upload/content?path=" + path + file := "/api/p/" + p.ID + "/file?path=" + path + t.Cleanup(func() { srv.dropRoom(roomID) }) + putContent(t, h, up, base, "") + + var calls atomic.Int32 + snapshotSeam = func(string) { + switch calls.Add(1) { + case 1: + // An agent writes the file, and a co-editor types, after this + // snapshot read the document: reconcile merged against text + // the document no longer spells, and has to merge again. + if rec := putContent(t, h, up, outside, shaOf(base)); rec.Code != http.StatusOK { + t.Errorf("outside write: %d %s", rec.Code, rec.Body) + } + if err := srv.ydocs().Apply(context.Background(), roomID, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + cur := txt.ToString() + spliceVia(transact, txt, cur, strings.Replace(cur, "l3\n", "l3 typed mid-reconcile\n", 1)) + }); err != nil { + t.Errorf("concurrent keystroke: %v", err) + } + case 2: + broken.Store(failAfterReconcile) + } + } + t.Cleanup(func() { snapshotSeam = nil; broken.Store(false) }) + + rec := syncAs(t, h, p.ID, path, map[string]any{"base": shaOf(base), "base_text": base, "text": room}) + got := get(t, h, file).Body.String() + if failAfterReconcile { + if rec.Code/100 == 2 { + t.Fatalf("sync answered %d with the edit only in memory (file %q)", rec.Code, got) + } + if strings.Contains(got, "L1 from the room") { + t.Fatalf("the edit was written through a failing store: %q", got) + } + return + } + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body) + } + if got != final { + t.Fatalf("sync answered ok while the file holds %q, want %q", got, final) + } + var out struct{ SHA string } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if out.SHA != shaOf(final) { + t.Fatalf("answered sha %s, want the durable %s", out.SHA, shaOf(final)) + } + // one snapshot reconciles (keystroke and outside write together), the + // next writes the merge: one snapshot could not have held it + if n := calls.Load(); n < 2 { + t.Fatalf("%d snapshots: the mid-reconcile keystroke was not exercised", n) + } + } + t.Run("written", func(t *testing.T) { run(t, false) }) + t.Run("storage fails", func(t *testing.T) { run(t, true) }) +} + +// A keystroke landing after moveDocLive read the room and before its move +// lands must survive the move, and the move must land where it was meant to. +// ygo's Apply holds the document's lock only inside transact, so a move made +// in character offsets of the text read before it would be shifted by that +// keystroke — here, by eleven characters, deleting "CONCURRENT " text or the +// wrong line. The move is an update anchored to items, so it is not. +func TestMoveDocLiveConcurrentKeystrokeDuringRecompute(t *testing.T) { + fastRoom(t, time.Hour, time.Hour) + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + const base = "l1\nl2\nl3\n" + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, base, "") + t.Cleanup(func() { srv.dropRoom(room) }) + insertAt := func(i int, s string) error { + return srv.ydocs().Apply(context.Background(), room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + if i < 0 { + i = txt.Len() + } + transact(func(txn *crdt.Transaction) { txt.Insert(txn, i, s, nil) }) + }) + } + // Typed after the snapshot read base: the move has to be recomputed. + if err := insertAt(-1, "- early\n"); err != nil { + t.Fatal(err) + } + if got := roomText(srv, room); got != base+"- early\n" { + t.Fatalf("room = %q", got) + } + + var recomputed string + recompute := func(cur string) (string, bool, bool) { + recomputed = cur + // Another peer types at the very start while the move is between + // reading the room and landing in it. + done := make(chan error, 1) + go func() { done <- insertAt(0, "CONCURRENT ") }() + if err := <-done; err != nil { + t.Errorf("concurrent keystroke: %v", err) + } + return strings.Replace(cur, "l3\n", "L3 reconciled\n", 1), false, true + } + theirs := shaOf("theirs") + from, landed, moved := srv.moveDocLive(context.Background(), room, base, strings.Replace(base, "l3\n", "L3 reconciled\n", 1), theirs, false, recompute) + if !moved { + t.Fatal("the move was refused") + } + if recomputed != base+"- early\n" || from != recomputed { + t.Fatalf("recomputed from %q (from %q), want the room as it stood", recomputed, from) + } + if landed != "l1\nl2\nL3 reconciled\n- early\n" { + t.Fatalf("landed = %q", landed) + } + const want = "CONCURRENT l1\nl2\nL3 reconciled\n- early\n" + if got := roomText(srv, room); got != want { + t.Fatalf("room after the move = %q, want %q: the move landed at shifted offsets", got, want) + } + if got := srv.rooms().base(room); got != theirs { + t.Fatalf("room base = %s, want the sha it moved onto", got) + } +} + +// A peer typing into the very line the move replaces, between the move +// reading the room and landing in it, merges with the move the way two +// peers' keystrokes merge: the move's delete set names only the line's old +// items, so the peer's characters survive beside the new line, and the +// outside version's line is in too. Nothing is lost, so the room rebases onto +// the version it moved to — its next pause writes both on top of it — rather +// than staying on a base it no longer stands on and parking a copy of text +// the file already holds. +func TestMoveDocLiveSameLineConcurrentKeystrokeKeepsBothEdits(t *testing.T) { + fastRoom(t, time.Hour, time.Hour) + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + const base = "l1\nl2\nl3\n" + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, base, "") + t.Cleanup(func() { srv.dropRoom(room) }) + edit := func(fn func(txt *crdt.YText, txn *crdt.Transaction, cur string)) error { + return srv.ydocs().Apply(context.Background(), room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + cur := txt.ToString() + transact(func(txn *crdt.Transaction) { fn(txt, txn, cur) }) + }) + } + if err := edit(func(txt *crdt.YText, txn *crdt.Transaction, cur string) { txt.Insert(txn, len(cur), "- early\n", nil) }); err != nil { + t.Fatal(err) + } + + const outside = "l1\nl2\nL3 from outside\n" + recompute := func(cur string) (string, bool, bool) { + done := make(chan error, 1) + go func() { + done <- edit(func(txt *crdt.YText, txn *crdt.Transaction, cur string) { + txt.Insert(txn, strings.Index(cur, "l3")+len("l3"), " from peer", nil) + }) + }() + if err := <-done; err != nil { + t.Errorf("concurrent keystroke: %v", err) + } + return strings.Replace(cur, "l3\n", "L3 from outside\n", 1), false, true + } + theirs := shaOf(outside) + _, landed, moved := srv.moveDocLive(context.Background(), room, base, outside, theirs, true, recompute) + if !moved || landed != "l1\nl2\nL3 from outside\n- early\n" { + t.Fatalf("moved %v to %q", moved, landed) + } + got := roomText(srv, room) + for _, want := range []string{"l1\nl2\n", "L3 from outside", " from peer", "- early\n"} { + if strings.Count(got, want) != 1 { + t.Fatalf("room = %q: want %q in it exactly once", got, want) + } + } + if strings.Contains(got, "l3") { + t.Fatalf("room = %q: the replaced line came back", got) + } + if b := srv.rooms().base(room); b != theirs { + t.Fatalf("room base = %s, want %s: the document holds their version", b, theirs) + } +} + +// An update whose result is past maxSeedBytes is refused before the live room +// takes it: an applied update cannot be taken back, and a room that large +// could be neither snapshotted whole nor seeded again. +func TestYCollabSyncRejectsUpdateExceedingMaxSeedBytes(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, "a\n", "") + + big := crdt.New() + typeInto(big, strings.Repeat("x", maxSeedBytes)) + update := big.EncodeStateAsUpdate() + if len(update) > maxHistoryBytes { + t.Fatalf("update is %d bytes: refused by the wire bound, not the text bound", len(update)) + } + leave := srv.rooms().enter(room) // keeps the room resident to look at afterwards + defer leave() + rec := syncAs(t, h, p.ID, path, map[string]any{"update": base64.StdEncoding.EncodeToString(update)}) + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("sync: %d %s, want 413", rec.Code, rec.Body) + } + var refusal struct { + Text string `json:"text"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &refusal); err != nil { + t.Fatal(err) + } + if refusal.Text != "a\n" { + t.Fatalf("refusal text = %q, want the room's unchanged \"a\\n\"", refusal.Text) + } + doc, _, held := srv.rooms().get(room) + if !held { + t.Fatal("the room is not resident") + } + if body := doc.GetText("body").ToString(); body != "a\n" { + t.Fatalf("the live room took the refused update: %d bytes of body", len(body)) + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); f != "a\n" { + t.Fatalf("file = %d bytes after a refused update", len(f)) + } +} + +// slowBlobs holds, once armed, every blob write carrying marker until release +// is closed — a storage write that hangs. +type slowBlobs struct { + remote.Backend + cond remote.ConditionalPutter + marker []byte + armed atomic.Bool + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (b *slowBlobs) hold(key string, r io.Reader) (io.Reader, error) { + if !b.armed.Load() || !strings.Contains(key, "blobs/") { + return r, nil + } + data, err := io.ReadAll(r) + if err != nil { + return nil, err + } + if bytes.Contains(data, b.marker) { + b.once.Do(func() { close(b.entered) }) + <-b.release + } + return bytes.NewReader(data), nil +} + +func (b *slowBlobs) Put(ctx context.Context, key string, r io.Reader, size int64) error { + r, err := b.hold(key, r) + if err != nil { + return err + } + return b.Backend.Put(ctx, key, r, size) +} + +func (b *slowBlobs) GetVersioned(ctx context.Context, key string) (io.ReadCloser, remote.Version, error) { + return b.cond.GetVersioned(ctx, key) +} + +func (b *slowBlobs) PutIf(ctx context.Context, key string, r io.Reader, size int64, expect remote.Version) (remote.Version, error) { + r, err := b.hold(key, r) + if err != nil { + return remote.VersionAbsent, err + } + return b.cond.PutIf(ctx, key, r, size, expect) +} + +// A room's close is a final snapshot, a storage round-trip. While it hangs, +// only an enter of THAT room waits: every other room still joins, leaves and +// syncs. +func TestYCollabCloseRoomDoesNotBlockOtherRooms(t *testing.T) { + fastRoom(t, time.Hour, time.Hour) // only the close writes room A + slow := &slowBlobs{marker: []byte("held-on-storage"), entered: make(chan struct{}), release: make(chan struct{})} + srv, p, _ := newHub(t, true, func(be remote.Backend) remote.Backend { + slow.Backend, slow.cond = be, be.(remote.ConditionalPutter) + return slow + }) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(slow.release) }) } + h := srv.Handler() + roomA, roomB := p.ID+"/a.md", p.ID+"/b.md" + t.Cleanup(func() { srv.dropRoom(roomA); srv.dropRoom(roomB) }) + t.Cleanup(unblock) // runs first: nothing is left hanging on storage + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path=a.md", "a\n", "") + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path=b.md", "b\n", "") + + // Room A, edited with nobody in it: its close owes a final snapshot. + if err := srv.ydocs().Apply(context.Background(), roomA, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + transact(func(txn *crdt.Transaction) { txt.Insert(txn, txt.Len(), "held-on-storage\n", nil) }) + }); err != nil { + t.Fatal(err) + } + // A snapshot with no recorded writer is skipped; name the editor so the + // close really owes room A's final write. + srv.rooms().writer(roomA, User{Email: "alice@example.com", Name: "Alice"}) + slow.armed.Store(true) + closed := make(chan struct{}) + go func() { + defer close(closed) + srv.rooms().closeIfUnused(roomA, func() { _ = srv.ydocs().CloseRoom(roomA, false) }) + }() + select { + case <-slow.entered: + case <-time.After(5 * time.Second): + t.Fatal("room A's close never reached its final write") + } + + within := func(what string, f func()) { + t.Helper() + done := make(chan struct{}) + go func() { defer close(done); f() }() + select { + case <-done: + case <-time.After(3 * time.Second): + unblock() + <-done + t.Fatalf("%s waited on room A's close", what) + } + } + within("an enter and leave of room B", func() { srv.rooms().enter(roomB)() }) + data, err := json.Marshal(map[string]any{"base": shaOf("b\n"), "base_text": "b\n", "text": "b\nmore\n"}) + if err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + within("a sync of room B", func() { + req := httptest.NewRequest("POST", "/api/p/"+p.ID+"/ycollab/sync?path=b.md", bytes.NewReader(data)) + h.ServeHTTP(rec, withUser(req, User{Email: "editor@example.com", Name: "An Editor"})) + }) + if rec.Code != http.StatusOK { + t.Fatalf("sync of room B: %d %s", rec.Code, rec.Body) + } + if f := get(t, h, "/api/p/"+p.ID+"/file?path=b.md").Body.String(); f != "b\nmore\n" { + t.Fatalf("b.md = %q", f) + } + + // Room A itself is held: an enter waits for its close, then gets in. + joined := make(chan struct{}) + go func() { + leave := srv.rooms().enter(roomA) + close(joined) + leave() + }() + select { + case <-joined: + t.Fatal("an enter of room A ran during its close") + case <-time.After(50 * time.Millisecond): + } + unblock() + for what, ch := range map[string]chan struct{}{"room A's close": closed, "the enter of room A": joined} { + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("%s never finished once storage answered", what) + } + } + if !waitFile(t, h, "/api/p/"+p.ID+"/file?path=a.md", "a\nheld-on-storage\n", 2*time.Second) { + t.Fatalf("a.md = %q after its close", get(t, h, "/api/p/"+p.ID+"/file?path=a.md").Body.String()) + } +} + +// meetingAuth is a provider for a hub whose every member is a known teammate: +// a request names who it is with a bearer token, so each editor's websocket, +// sync and read reaches the hub as that person — the room's writer is a real +// account, as it is in production, never the anonymous User{} a hub without +// auth hands out (which the snapshot refuses to attribute, so the room would +// never write nor take its lease). An in-process request already carrying a +// user (syncAs's withUser) keeps it. +type meetingAuth struct{ users map[string]User } + +func (a *meetingAuth) CLILoginPath() string { return "/auth/cli" } +func (a *meetingAuth) Register(*http.ServeMux) {} +func (a *meetingAuth) UseDeviceBinder(DeviceBinder) {} +func (a *meetingAuth) Accounts() []User { + out := make([]User, 0, len(a.users)) + for _, u := range a.users { + out = append(out, u) + } + return out +} + +func (a *meetingAuth) Authenticate(r *http.Request) (User, bool) { + if u, ok := userFrom(r.Context()); ok { + return u, true + } + u, ok := a.users[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] + return u, ok +} + +func meetingToken(u User) string { return "meeting-" + u.Email } + +func meetingHeader(u User) http.Header { + return http.Header{"Authorization": {"Bearer " + meetingToken(u)}} +} + +// meetingDo is one HTTP request to a hub, made as u. +func meetingDo(t *testing.T, h http.Handler, u User, method, url string, body io.Reader, hdr http.Header) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, url, body) + for k, v := range meetingHeader(u) { + req.Header[k] = v + } + for k, v := range hdr { + req.Header[k] = v + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +// meetingEditor is one browser tab on the meeting note: a real y-websocket +// client (ygo's provider/client) holding its own document, signed in as one +// teammate. +type meetingEditor struct { + name string + user User + doc *crdt.Doc + conn *ygoclient.Client + done chan struct{} +} + +func joinMeeting(t *testing.T, ts *httptest.Server, projectID, path string, u User) *meetingEditor { + t.Helper() + doc := crdt.New() + url := "ws" + strings.TrimPrefix(ts.URL, "http") + "/api/p/" + projectID + "/ycollab/meeting.md?path=" + path + c, err := ygoclient.New(ygoclient.Options{URL: url, Doc: doc, Header: meetingHeader(u)}) + if err != nil { + t.Fatal(err) + } + e := &meetingEditor{name: u.Name, user: u, doc: doc, conn: c, done: make(chan struct{})} + go func() { + defer close(e.done) + _ = c.Connect(context.Background()) + }() + t.Cleanup(e.leave) + select { + case <-c.Synced(): + case <-time.After(10 * time.Second): + t.Fatalf("%s never synced with the hub", u.Name) + } + return e +} + +// leave closes the tab's socket and waits for its dial loop to end. +func (e *meetingEditor) leave() { + _ = e.conn.Close() + select { + case <-e.done: + case <-time.After(5 * time.Second): + } +} + +func (e *meetingEditor) text() string { return e.doc.GetText("body").ToString() } + +// write inserts line where at says, against the text it was computed from: +// a remote update landing between the read and the transaction would shift +// the index into the middle of somebody else's line, so the transaction only +// commits on an unchanged length (every edit here changes the length) and the +// edit is recomputed otherwise. +func (e *meetingEditor) write(line string, at func(cur string) int) { + txt := e.doc.GetText("body") + for { + cur := txt.ToString() + i := at(cur) + wrote := false + e.doc.Transact(func(txn *crdt.Transaction) { + if txt.Len() != len(cur) { + return + } + txt.Insert(txn, i, line, nil) + wrote = true + }) + if wrote { + return + } + } +} + +// meetingSectionEnd is the start of the heading after name's section: a line +// inserted there becomes the section's last line. +func meetingSectionEnd(name string) func(string) int { + return func(cur string) int { + h := strings.Index(cur, "\n## "+name+"\n") + if h < 0 { + return len(cur) + } + start := h + 1 + if j := strings.Index(cur[start:], "\n## "); j >= 0 { + return start + j + 1 + } + return len(cur) + } +} + +func meetingDocEnd(cur string) int { return len(cur) } + +/* +Eight people in one meeting note, split across two hub processes, while every +way of leaving the room and every outside writer happens mid-meeting. + + Each teammate is signed in as their own account. Alice, Bob, Carol and + Dave are on hub A, which takes the room's lease with its first write; + Erin, Frank, Grace and Heidi are on hub B. Grace never opens a socket: she + is the slow editor staging checkpoints over HTTP. Everyone else types into + their own section and appends shared action items without pausing, so + the holder's idle snapshot never fires and only snapshotMax writes. + + (a) Carol presses Done: a /ycollab/sync and a closed socket, after which + the file and its rendering already hold her last line. + (b) Erin's tab dies offline (pagehide keepalive): three lines typed with + no socket reach the room through ONE sync sent to the process that + does not hold the lease, while everyone keeps typing. That sync waits + for the holder's write, which continuous typing defers to + snapshotMax — the 503 this pins was ycollabSyncDurableWait at 4s + against a 10s snapshotMax. + (c) Grace stages two checkpoints on a stale base; the second names the + first in prior_sent, so its bullet is not inserted twice. + (d) An agent writes the header with a stale If-Match: merged by the + hub, reconciled into the live room. + + The timings are production's, halved, so the relationship between them — + the thing under test — is the one that ships. +*/ +func TestCollabEightPeersMeetingNoteExitChaos(t *testing.T) { + if ycollabSyncDurableWait <= snapshotMax { + t.Fatalf("ycollabSyncDurableWait %v must exceed snapshotMax %v: a non-holder's sync during continuous typing would 503", ycollabSyncDurableWait, snapshotMax) + } + fastRoom(t, snapshotIdle/2, snapshotMax/2) + oldWait := ycollabSyncDurableWait + ycollabSyncDurableWait = oldWait / 2 + t.Cleanup(func() { ycollabSyncDurableWait = oldWait }) + oldRoomIdle := collabRoomIdleTimeout + collabRoomIdleTimeout = 500 * time.Millisecond + t.Cleanup(func() { collabRoomIdleTimeout = oldRoomIdle }) + + names := []string{"Alice", "Bob", "Carol", "Dave", "Erin", "Frank", "Grace", "Heidi"} + people := map[string]User{} + auth := &meetingAuth{users: map[string]User{}} + for _, n := range append(slices.Clone(names), "Agent") { + u := User{Email: strings.ToLower(n) + "@example.com", Name: n} + people[n] = u + auth.users[meetingToken(u)] = u + } + agent := people["Agent"] + + a, b, p := newHubPair(t) + relay := cluster.NewMemRelay() + for _, s := range []*Server{a, b} { + // Before Handler: the auth gate is wired when the handler is built. + s.Auth = auth + if err := s.useCollabRelay(relay); err != nil { + t.Fatal(err) + } + } + ha, hb := a.Handler(), b.Handler() + tsA, tsB := httptest.NewServer(ha), httptest.NewServer(hb) + // Registered after newHubPair, so these close before the hubs do. + t.Cleanup(tsA.Close) + t.Cleanup(tsB.Close) + + const path = "areas/team/daily-meetings/2026-11-11.md" + const oldHeader = "# Daily meeting 2026-11-11\n" + const newHeader = "# Daily meeting 2026-11-11 (release: v0.18.10)\n" + var seed strings.Builder + seed.WriteString(oldHeader) + seed.WriteString("Attendees: " + strings.Join(names, ", ") + "\n") + for _, n := range names { + fmt.Fprintf(&seed, "## %s\n- [ ] %s: action items\n", n, n) + } + seed.WriteString("## Shared action items\n- [ ] Ship v0.18.10\n") + room := p.ID + "/" + path + fileURL := "/api/p/" + p.ID + "/file?path=" + path + renderURL := "/api/p/" + p.ID + "/render?path=" + path + uploadURL := "/api/p/" + p.ID + "/upload/content?path=" + path + + read := func(h http.Handler, u User, url string) *httptest.ResponseRecorder { + t.Helper() + return meetingDo(t, h, u, "GET", url, nil, nil) + } + file := func(h http.Handler) string { return read(h, agent, fileURL).Body.String() } + + if rec := meetingDo(t, ha, agent, "PUT", uploadURL, strings.NewReader(seed.String()), nil); rec.Code != http.StatusOK { + t.Fatalf("seed: %d %s", rec.Code, rec.Body) + } + if rec := read(ha, agent, fileURL); rec.Code != http.StatusOK || rec.Body.String() != seed.String() { + t.Fatalf("seeded file reads %d %q", rec.Code, rec.Body) + } + + var wantMu sync.Mutex + var want []string + record := func(line string) { + wantMu.Lock() + want = append(want, line) + wantMu.Unlock() + } + + // Hub A opens the room first and writes it, which takes the lease. + alice := joinMeeting(t, tsA, p.ID, path, people["Alice"]) + if got := alice.text(); got != seed.String() { + t.Fatalf("Alice joined to %q, want the seed", got) + } + bob := joinMeeting(t, tsA, p.ID, path, people["Bob"]) + carol := joinMeeting(t, tsA, p.ID, path, people["Carol"]) + dave := joinMeeting(t, tsA, p.ID, path, people["Dave"]) + if _, who, ok := a.rooms().get(room); !ok || who.Email == "" { + t.Fatalf("A's room has no signed-in writer (%+v): it would never snapshot", who) + } + const warm = "- Alice note 0\n" + alice.write(warm, meetingSectionEnd("Alice")) + record(warm) + if !waitUntil(10*time.Second, func() bool { return strings.Contains(file(ha), warm) }) { + t.Fatalf("A never wrote the first edit: %q", file(ha)) + } + if !a.holdsLease(room) { + t.Fatal("A wrote the room without holding its lease") + } + erin := joinMeeting(t, tsB, p.ID, path, people["Erin"]) + frank := joinMeeting(t, tsB, p.ID, path, people["Frank"]) + heidi := joinMeeting(t, tsB, p.ID, path, people["Heidi"]) + for _, e := range []*meetingEditor{erin, frank, heidi} { + if !waitUntil(5*time.Second, func() bool { return strings.Contains(e.text(), warm) }) { + t.Fatalf("%s on B never caught up: %q", e.name, e.text()) + } + } + // holdLease TAKES a free lease, so it is asked only once A is known to + // hold it: a false here is A's stored, unexpired record refusing B. + if !a.holdsLease(room) || b.holdLease(context.Background(), room) { + t.Fatalf("lease: A holds %v, B could take it: the non-holder cases below would test nothing", a.holdsLease(room)) + } + + // Everyone with a socket types without pausing. + tick := snapshotIdle / 8 + type typing struct{ stop, done chan struct{} } + startTyping := func(e *meetingEditor, offset int) *typing { + ty := &typing{stop: make(chan struct{}), done: make(chan struct{})} + go func() { + defer close(ty.done) + for i := 1; ; i++ { + select { + case <-ty.stop: + return + case <-time.After(tick + time.Duration(offset)*time.Millisecond): + } + line := fmt.Sprintf("- %s note %d\n", e.name, i) + e.write(line, meetingSectionEnd(e.name)) + record(line) + if i%4 == 0 { + item := fmt.Sprintf("- [ ] %s follow-up %d\n", e.name, i) + e.write(item, meetingDocEnd) + record(item) + } + } + }() + return ty + } + halt := func(ty *typing) { + close(ty.stop) + <-ty.done + } + typists := map[*meetingEditor]*typing{} + for i, e := range []*meetingEditor{alice, bob, carol, dave, erin, frank, heidi} { + typists[e] = startTyping(e, 7*i) + } + // A typist still running when the test fails is stopped before the + // editors' own cleanups close their sockets. + t.Cleanup(func() { + for _, ty := range typists { + halt(ty) + } + }) + stopTyping := func(e *meetingEditor) { + halt(typists[e]) + delete(typists, e) + } + time.Sleep(2 * snapshotIdle) + + type syncAnswer struct { + OK bool `json:"ok"` + Text string `json:"text"` + Merged bool `json:"merged"` + } + // syncOK retries only the room's "unintegrated updates" busy answer — a + // relay frame still in flight — and fails on every other refusal, + // including the durable-wait 503 this test is about. + syncOK := func(u User, h http.Handler, body map[string]any) syncAnswer { + t.Helper() + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + for attempt := 0; ; attempt++ { + rec := meetingDo(t, h, u, "POST", "/api/p/"+p.ID+"/ycollab/sync?path="+path, bytes.NewReader(data), nil) + if rec.Code == http.StatusServiceUnavailable && strings.Contains(rec.Body.String(), "unintegrated") && attempt < 10 { + time.Sleep(50 * time.Millisecond) + continue + } + if rec.Code != http.StatusOK { + t.Fatalf("%s's sync: %d %s", u.Name, rec.Code, rec.Body) + } + var out syncAnswer + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !out.OK { + t.Fatalf("%s's sync answered %s", u.Name, rec.Body) + } + return out + } + } + + // (a) Carol: Done. Her last line, a sync, the socket closed — and the + // very next read, on either process, already has it. + stopTyping(carol) + const decision = "- Carol decision: ship Friday\n" + carol.write(decision, meetingSectionEnd("Carol")) + record(decision) + syncOK(carol.user, ha, map[string]any{"update": base64.StdEncoding.EncodeToString(carol.doc.EncodeStateAsUpdate())}) + carol.leave() + for _, hub := range []struct { + name string + h http.Handler + }{{"A", ha}, {"B", hb}} { + rec := read(hub.h, carol.user, fileURL) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), decision) { + t.Fatalf("file on %s right after Carol's Done: %d, has her line: %v", hub.name, rec.Code, strings.Contains(rec.Body.String(), decision)) + } + rec = read(hub.h, carol.user, renderURL) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Carol decision: ship Friday") { + t.Fatalf("render on %s right after Carol's Done: %d %.300s", hub.name, rec.Code, rec.Body) + } + } + + // (b) Erin: the tab dies offline. Three lines with no socket, then one + // keepalive sync to B — which does not hold the lease — while the others + // keep A's room busy past the old wait. + stopTyping(erin) + erin.leave() + var offline []string + for i := 1; i <= 3; i++ { + line := fmt.Sprintf("- Erin offline %d\n", i) + erin.write(line, meetingSectionEnd("Erin")) + record(line) + offline = append(offline, line) + } + if !a.holdsLease(room) || b.holdsLease(room) { + t.Fatalf("lease moved before Erin's sync: A %v, B %v", a.holdsLease(room), b.holdsLease(room)) + } + started := time.Now() + syncOK(erin.user, hb, map[string]any{"update": base64.StdEncoding.EncodeToString(erin.doc.EncodeStateAsUpdate())}) + t.Logf("Erin's pagehide sync on the non-holder answered in %v (wait %v, snapshotMax %v)", time.Since(started), ycollabSyncDurableWait, snapshotMax) + live := []*meetingEditor{alice, bob, dave, frank, heidi} + for _, e := range live { + if !waitUntil(5*time.Second, func() bool { + txt := e.text() + for _, l := range offline { + if !strings.Contains(txt, l) { + return false + } + } + return true + }) { + t.Fatalf("Erin's offline lines never reached %s", e.name) + } + } + + // (c) Grace: two staged checkpoints over HTTP on the base she read once. + grace := people["Grace"] + graceBase := read(hb, grace, fileURL).Body.String() + const bullet1, bullet2 = "- [ ] Grace staged 1\n", "- [ ] Grace staged 2\n" + at := meetingSectionEnd("Grace")(graceBase) + text1 := graceBase[:at] + bullet1 + graceBase[at:] + text2 := graceBase[:at] + bullet1 + bullet2 + graceBase[at:] + record(bullet1) + record(bullet2) + syncOK(grace, hb, map[string]any{"base_text": graceBase, "text": text1}) + out := syncOK(grace, hb, map[string]any{"base_text": graceBase, "text": text2, "prior_sent": []string{text1}}) + for _, l := range []string{bullet1, bullet2} { + if n := strings.Count(out.Text, "\n"+l); n != 1 { + t.Fatalf("Grace's %q is in the room %d times after her second checkpoint", l, n) + } + } + + // (d) An agent writes the header on a version the room has since moved + // past (but not so far that its body reads as a sharp shrink). + stale := file(hb) + if !waitUntil(10*time.Second, func() bool { return file(hb) != stale }) { + t.Fatal("the room never wrote past the agent's base") + } + rec := meetingDo(t, hb, agent, "PUT", uploadURL, strings.NewReader(strings.Replace(stale, oldHeader, newHeader, 1)), + http.Header{"If-Match": {shaOf(stale)}}) + if rec.Code != http.StatusOK { + t.Fatalf("agent's stale-base write: %d %s", rec.Code, rec.Body) + } + var put struct { + Merged bool `json:"merged"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &put); err != nil || !put.Merged { + t.Fatalf("agent's stale-base write was not merged: %s", rec.Body) + } + record(newHeader) + for _, e := range live { + if !waitUntil(10*time.Second, func() bool { return strings.HasPrefix(e.text(), newHeader) }) { + t.Fatalf("the agent's header never reached %s: %.200q", e.name, e.text()) + } + } + time.Sleep(snapshotIdle) + + // Everyone stops, converges, and leaves. + for e := range typists { + stopTyping(e) + } + var final string + if !waitUntil(10*time.Second, func() bool { + final = alice.text() + for _, e := range live { + if e.text() != final { + return false + } + } + return roomText(a, room) == final && roomText(b, room) == final + }) { + t.Fatal("the live documents never converged") + } + for _, e := range live { + e.leave() + } + if !waitUntil(10*time.Second, func() bool { return file(ha) == final }) { + t.Fatalf("the stored file never reached the converged document:\nfile %q\nroom %q", file(ha), final) + } + for _, s := range []*Server{a, b} { + if !waitUntil(10*time.Second, func() bool { return !slices.Contains(s.ydocs().Rooms(), room) }) { + t.Fatal("a room stayed resident after every peer left") + } + } + if got := file(ha); got != final { + t.Fatalf("the final snapshot changed the file:\nfile %q\nroom %q", got, final) + } + + // conflictTexts lists from the fold; its unauthenticated reads of each + // copy's text are not needed to count them. + if cc := conflictTexts(t, a, p.ID, path); len(cc) != 0 { + t.Fatalf("%d conflict copies: %v", len(cc), slices.Collect(maps.Keys(cc))) + } + for _, u := range []string{"/api/p/" + p.ID + "/tree", "/api/p/" + p.ID + "/history?prefix=areas/&n=1000"} { + for _, h := range []http.Handler{ha, hb} { + rec := read(h, agent, u) + if rec.Code != http.StatusOK { + t.Fatalf("%s: %d %s", u, rec.Code, rec.Body) + } + if strings.Contains(rec.Body.String(), ".bdrive-conflict-") { + t.Fatalf("%s lists a conflict copy", u) + } + } + } + + if !strings.HasPrefix(final, newHeader) || strings.Contains(final, oldHeader) { + t.Fatalf("header in the final file: %.120q", final) + } + wantMu.Lock() + defer wantMu.Unlock() + for _, l := range want { + if l == newHeader { + continue + } + if n := strings.Count(final, "\n"+l); n != 1 { + t.Errorf("%q is in the final file %d times, want exactly once", strings.TrimSuffix(l, "\n"), n) + } + } + t.Logf("%d edits from 8 editors and an agent, each stored exactly once", len(want)) +} From fc7362f0a5f1ae068751e46ee2a47688a690430f Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 21:28:31 +0900 Subject: [PATCH 02/34] fix(webapp): preserve non-colliding peer edits in VisualEdit word conflicts --- architecture/webapp-frontend.md | 4 +- .../frontend/src/components/VisualEdit.tsx | 13 ++--- internal/webapp/frontend/src/lib/merge3.ts | 58 +++++++++++++++---- .../src/lib/sharedfile_restore.test.ts | 25 +++++++- ...{Editor-CUvVSG63.js => Editor-DHvYAyxu.js} | 2 +- .../static/assets/VisualEdit-BYnijXna.js | 1 + .../static/assets/VisualEdit-CwChUaNM.js | 1 - .../{index-BD48v6-0.js => index-BROkyUpj.js} | 4 +- .../static/assets/sharedfile-DXV-dXg-.js | 16 ----- .../static/assets/sharedfile-jBqmYsT3.js | 16 +++++ internal/webapp/static/index.html | 2 +- 11 files changed, 100 insertions(+), 42 deletions(-) rename internal/webapp/static/assets/{Editor-CUvVSG63.js => Editor-DHvYAyxu.js} (99%) create mode 100644 internal/webapp/static/assets/VisualEdit-BYnijXna.js delete mode 100644 internal/webapp/static/assets/VisualEdit-CwChUaNM.js rename internal/webapp/static/assets/{index-BD48v6-0.js => index-BROkyUpj.js} (99%) delete mode 100644 internal/webapp/static/assets/sharedfile-DXV-dXg-.js create mode 100644 internal/webapp/static/assets/sharedfile-jBqmYsT3.js diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index cc8094a9..d5836ba9 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -189,7 +189,7 @@ classDiagram +sidebarSearch.ts useSidebarSearch setFilterQuery registerFilterResults +collab.ts CollabDoc peerCount isRemote onStalled encodeState applySplices applyRemoteUpdate (y-websocket to the hub-held document; stop only when there is no room route) +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once) - +merge3.ts merge3 diffSplices applySplices retainsChanges (TS port of internal/textmerge) + +merge3.ts merge3 merge3PreferRight diffSplices applySplices retainsChanges (TS port of internal/textmerge) +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room) +sharedfile.ts rebase (the head sha moved because a co-editor saved) @@ -244,7 +244,7 @@ classDiagram shareMermaid --> lib : renderMermaid inlineComment --> lib : anchor.ts (no app imports) components --> lib : rangeFor describe hitTest (Comments) - components --> lib : merge3 diffSplices (VisualEdit), saveNow askingShrink (FileView flush) + components --> lib : merge3PreferRight diffSplices (VisualEdit), saveNow askingShrink (FileView flush) Browser ..> components : Done awaits FileView's flushRef lib --> api : syncCollab putText keepalive (sharedfile) components ..> inlineComment : postMessage via the ?comment=1 iframe diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index d29562ae..be7642f1 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; import * as Y from "yjs"; import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile"; -import { diffSplices, merge3 } from "../lib/merge3"; +import { diffSplices, merge3PreferRight } from "../lib/merge3"; import { type CollabStatus } from "../lib/collab"; import { askShrink, withdrawShrink } from "./ShrinkDialog"; @@ -360,8 +360,7 @@ export function VisualEdit({ return; } const sLive = sText.toString().slice(sFrom.index, sTo.index); - const sMerged = merge3(a.orig, sLive, msg.html); - const sWant = sMerged.ok ? sMerged.text : msg.html; + const sWant = merge3PreferRight(a.orig, sLive, msg.html); a.orig = msg.html; if (sLive === sWant) return; stageDoc.transact(() => { @@ -415,10 +414,10 @@ export function VisualEdit({ typing elsewhere in the same paragraph is in `live` but not in the patch, which the iframe built from what it last rendered — replacing the span wholesale erased their keystrokes. So: their change - (live − orig) and ours (html − orig), merged three ways; where they - collide on the same words the patch wins, as it always did. */ - const merged = merge3(a.orig, live, msg.html); - const want = merged.ok ? merged.text : msg.html; + (live − orig) and ours (html − orig), merged three ways; only the + words where they collide take the patch, and a co-editor's edit to + other words of the same element survives the collision. */ + const want = merge3PreferRight(a.orig, live, msg.html); a.orig = msg.html; if (live === want) return; // Splices run last-first in `live` coordinates, so shifting by the diff --git a/internal/webapp/frontend/src/lib/merge3.ts b/internal/webapp/frontend/src/lib/merge3.ts index e202d0bf..76b0449b 100644 --- a/internal/webapp/frontend/src/lib/merge3.ts +++ b/internal/webapp/frontend/src/lib/merge3.ts @@ -21,7 +21,11 @@ which side is called `a`: merge3(base, a, b) === merge3(base, b, a). { ok: false } is the honest answer only for the same token changed two - different ways. */ + different ways. + + merge3PreferRight(base, a, b) is the same merge for a caller that must get + a text back: every region still merges as above, and only the minimal + token span both sides changed differently takes `b`'s version. */ export type Merge3Result = { ok: true; text: string } | { ok: false }; @@ -181,7 +185,11 @@ function sameAnchor(x: string, y: string, concat: boolean, emptyBase: boolean): type Side = { h: Hunk; toks: string[]; side: 0 | 1 }; -function mergeAt(base: string, a: string, b: string, level: Level): string | null { +/* With `preferB`, a collision takes `b`'s side of the colliding region rather + than failing the merge — at the narrowest level that still collides: lines + descend to tokens, and a token collision the char level cannot resolve is + `b`'s tokens for that span alone. */ +function mergeAt(base: string, a: string, b: string, level: Level, preferB = false): string | null { if (a === b) return a; if (a === base) return b; if (b === base) return a; @@ -247,13 +255,26 @@ function mergeAt(base: string, a: string, b: string, level: Level): string | nul } if (gs === ge) { const s = sameAnchor(ra, rb, level !== CHARS, bt.length === 0); - if (s === null) return null; + if (s === null) { + if (!preferB) return null; + out += rb; + continue; + } out += s; continue; } if (level === CHARS) return null; - const sub = mergeAt(join(bt, gs, ge), ra, rb, (level + 1) as Level); - if (sub === null) return null; + // Chars only recognise a continued insertion; they are never asked to + // pick a side, so a token collision there falls back to `b`'s tokens. + const sub = + level === TOKENS + ? mergeAt(join(bt, gs, ge), ra, rb, CHARS) + : mergeAt(join(bt, gs, ge), ra, rb, (level + 1) as Level, preferB); + if (sub === null) { + if (!preferB) return null; + out += rb; + continue; + } out += sub; } return out + join(bt, pos, bt.length); @@ -265,15 +286,30 @@ function mergeAt(base: string, a: string, b: string, level: Level): string | nul lands after it — "x" + "x\nx" is "xx\nx", one line where Go has two. */ const terminated = (s: string) => (s === "" || s.endsWith("\n") ? s : s + "\n"); +// The final newline is one more thing a side may change: whichever side +// changed it from the base wins, and both can only change it one way. +function withTrailing(base: string, a: string, b: string, text: string): string { + let trailing = a.endsWith("\n"); + if (trailing === base.endsWith("\n")) trailing = b.endsWith("\n"); + if (text === "" || trailing === text.endsWith("\n")) return text; + return trailing ? text + "\n" : text.slice(0, -1); +} + export function merge3(base: string, a: string, b: string): Merge3Result { const text = mergeAt(terminated(base), terminated(a), terminated(b), LINES); if (text === null) return { ok: false }; - // The final newline is one more thing a side may change: whichever side - // changed it from the base wins, and both can only change it one way. - let trailing = a.endsWith("\n"); - if (trailing === base.endsWith("\n")) trailing = b.endsWith("\n"); - if (text === "" || trailing === text.endsWith("\n")) return { ok: true, text }; - return { ok: true, text: trailing ? text + "\n" : text.slice(0, -1) }; + return { ok: true, text: withTrailing(base, a, b, text) }; +} + +/* merge3, except a conflict is not an answer: where `left` and `right` changed + the same base tokens differently, `right` wins THAT span, and every other + edit either side made — including ones inside the same line — survives. */ +export function merge3PreferRight(base: string, left: string, right: string): string { + if (left === right) return left; + if (base === left) return right; + if (base === right) return left; + const text = mergeAt(terminated(base), terminated(left), terminated(right), LINES, true) ?? terminated(right); + return withTrailing(base, left, right, text); } /* The splices that turn `oldText` into `newText`, touching as little as diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 44f6c869..136093d1 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -53,7 +53,7 @@ registerHooks({ const { CollabDoc } = await import("./collab.ts"); const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); const { parseConflict } = await import("./conflict.ts"); -const { merge3 } = await import("./merge3.ts"); +const { merge3, merge3PreferRight } = await import("./merge3.ts"); /* toEqual's semantics: a property that is undefined is a property that is absent. Only plain objects and arrays are rebuilt; anything else (a @@ -590,6 +590,29 @@ test("merge3 keeps an unterminated same-anchor insertion its own line, matching same(merge3("a\nb\n", "a\nb\nc\n", "a\nb"), { ok: true, text: "a\nb\nc" }); }); +/* VisualEdit's patch against a co-editor's typing in the same element: when + both changed the same word, only that word takes the patch (`right`); a + word only the co-editor changed survives, and so does the next keystroke. */ +test("merge3PreferRight lets only the colliding words take the patch", () => { + same(merge3("cat sales", "dog revenue", "bird sales"), { ok: false }); + assert.equal(merge3PreferRight("cat sales", "dog revenue", "bird sales"), "bird revenue"); + assert.equal(merge3PreferRight("bird sales", "bird revenue", "bird! sales"), "bird! revenue"); + assert.equal( + merge3PreferRight("line1\ncat sales\nline3", "PEER1\ndog revenue\nline3", "line1\nbird sales\nMY3"), + "PEER1\nbird revenue\nMY3", + ); + assert.equal( + merge3PreferRight("cat and sales", "dog and revenue", "bird and sales"), + "bird and revenue", + ); + // Fast paths and clean merges are merge3's answer. + assert.equal(merge3PreferRight("a b", "a b", "a c"), "a c"); + assert.equal(merge3PreferRight("a b", "x b", "a b"), "x b"); + assert.equal(merge3PreferRight("a b", "x b", "a y"), "x y"); + // Same-anchor insertions keep both, as merge3 does. + assert.equal(merge3PreferRight("log\n", "log\nb\n", "log\na\n"), "log\na\nb\n"); +}); + /* A staging checkpoint the room refuses 409 while newer typing waits behind it (its idle timer already fired into the in-flight loop). The refusal is settled for the buffer as it is NOW: the conflict copy carries the newer diff --git a/internal/webapp/static/assets/Editor-CUvVSG63.js b/internal/webapp/static/assets/Editor-DHvYAyxu.js similarity index 99% rename from internal/webapp/static/assets/Editor-CUvVSG63.js rename to internal/webapp/static/assets/Editor-DHvYAyxu.js index 35abb1be..966aadd1 100644 --- a/internal/webapp/static/assets/Editor-CUvVSG63.js +++ b/internal/webapp/static/assets/Editor-DHvYAyxu.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BD48v6-0.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-DXV-dXg-.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BROkyUpj.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-jBqmYsT3.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-BYnijXna.js b/internal/webapp/static/assets/VisualEdit-BYnijXna.js new file mode 100644 index 00000000..9f8fa6d4 --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-BYnijXna.js @@ -0,0 +1 @@ +import{r as i,j as y,w as ge,a as me}from"./index-BROkyUpj.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-jBqmYsT3.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-CwChUaNM.js b/internal/webapp/static/assets/VisualEdit-CwChUaNM.js deleted file mode 100644 index 4d16cebf..00000000 --- a/internal/webapp/static/assets/VisualEdit-CwChUaNM.js +++ /dev/null @@ -1 +0,0 @@ -import{r as i,j as y,w as pe,a as he}from"./index-BD48v6-0.js";import{o as be,D as ye,c as T,a as C,m as ie,d as ce}from"./sharedfile-DXV-dXg-.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function Te(k){if(!globalThis.crypto?.subtle)return null;try{const E=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(k));return[...new Uint8Array(E)].map(g=>g.toString(16).padStart(2,"0")).join("")}catch{return null}}function je({apiBase:k,fileURL:E,path:g,initial:ae,me:P,onStateChange:H,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,le]=i.useState(null),[de,J]=i.useState(!1),[ue,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:H,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:H,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ae),L=i.useRef(P);L.current=P;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const fe=700;J(!1),K(!1);const xe=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),me=setTimeout(()=>K(!0),24e3),s=X.current=be({apiBase:k,path:g,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>he(g,e),onShrinkWithdrawn:pe,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const t=e.getText("body").toString(),r=s.collab.text.toString();if(x&&t===r)for(const[a,n]of d){const u=T(n.from,e),m=T(n.to,e);u&&m&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,m.index),span:n.span,orig:n.orig})}else d.clear(),x=!1,t!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new ye,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:t,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");t>e&&a.delete(e,t-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(h.some(n=>n.end>t.length||n.start>n.end)){h=null,p(n=>n+1);return}const r=await Te(t);if(r!==null?r!==$:D>=0&&t.length!==D){h=null,p(n=>n+1);return}d.clear();for(const n of h)d.set(Z(n),{from:C(e,n.start),to:C(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",D=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const t=e.data;if(!t||typeof t!="object")return;if(t.type==="bd-edit:clobbered"){le("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(t.type==="bd-edit:ready"){h=t.ranges,$=t.hash,D=t.len,await w();return}if(t.type!=="bd-edit:patch")return;const r=d.get(Z(t));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),ge=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),oe=ie(r.orig,N,t.html),se=oe.ok?oe.text:t.html;if(r.orig=t.html,N===se)return;o.transact(()=>{for(const f of ce(N,se))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},fe);return}const a=s.collab.doc,n=T(r.from,a),u=T(r.to,a);if(!n||!u||n.index>u.index)return;const m=s.collab.text,te=u.index-n.index;if(n.index===0&&u.index===m.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:m.length}),d.clear(),x=!1,p(c=>c+1);return}const M=m.toString().slice(n.index,u.index),ne=ie(r.orig,M,t.html),re=ne.ok?ne.text:t.html;r.orig=t.html,M!==re&&s.collab.applySplices(ce(M,re).map(c=>({...c,index:c.index+n.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(xe),clearTimeout(me),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[k,g,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),ue&&!de&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:E+(E.includes("?")?"&":"?")+"edit=1",title:g},Q)]})}export{je as VisualEdit}; diff --git a/internal/webapp/static/assets/index-BD48v6-0.js b/internal/webapp/static/assets/index-BROkyUpj.js similarity index 99% rename from internal/webapp/static/assets/index-BD48v6-0.js rename to internal/webapp/static/assets/index-BROkyUpj.js index bf253fcf..24094d4f 100644 --- a/internal/webapp/static/assets/index-BD48v6-0.js +++ b/internal/webapp/static/assets/index-BROkyUpj.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CUvVSG63.js","assets/sharedfile-DXV-dXg-.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CwChUaNM.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DHvYAyxu.js","assets/sharedfile-jBqmYsT3.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-BYnijXna.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const u of o.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,o){var u=null;if(o!==void 0&&(u=""+o),i.key!==void 0&&(u=""+i.key),"key"in i){o={};for(var f in i)f!=="key"&&(o[f]=i[f])}else o=i;return i=o.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:o}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var l=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),o=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||o==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(o))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;no.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,o])=>i>=r.headingEnd&&o<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return l.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,o=n.length-r.length;return l.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>l.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),o>0&&l.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",o]}),i>0&&l.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,o,u){if(typeof o=="string"){const f=o.charCodeAt(0);if(f>=48&&f<=57){const h=+o;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(i),o=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let o=0;o{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const o=e.options.useScrollendEvent&&MV;let u=0;const f=o?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),o&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),o&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),o=n.itemSizeCache.get(i);if(o!==void 0)return o}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,o;(o=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||o.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(o=>{const u=()=>{const f=o.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var o;return(o=r())==null?void 0:o.observe(i,{box:"border-box"})},unobserve:i=>{var o;return(o=r())==null?void 0:o.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(o[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=o.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(o.getItemKey(0)!==S||o.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=o.followOnAppend===!0?"auto":o.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||o.getItemKey(x-1)!==E)&&(h=T)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,u)=>{if(u&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===o?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",u,Id),o.addEventListener("touchend",f,Id),this.unsubs.push(()=>{o.removeEventListener("touchstart",u),o.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[o,u,f,h]=i;o!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,o,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,o)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,o,u)=>o===null||u===null?[]:n({startIndex:o,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-o),f=Math.min(this.options.count-1,i+o);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),o=this.elementsCache.get(i);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,o;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let o=0,u=n.length;othis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,o=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,o?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+o?"end":"start"),r==="center"?n+=(i-o)/2:r==="end"&&(n-=o);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),o=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=o+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[u,f]=o,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,u=this._flatMeasurements;u!=null?i=u[o*2]+u[o*2+1]:i=((n=r[o])==null?void 0:n.end)??0}else{const o=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&o.some(f=>f===null);){const f=r[u];o[f.lane]===null&&(o[f.lane]=f.end),u--}i=Math.max(...o.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,o=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,o=n(i);if(or)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,o=e[i*2];if(on)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&i!==null){const m=$V(i,o,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(o,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],o=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const u=m=>{const y=o.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=o.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=o.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return l.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return l.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return l.jsx(rz,{children:l.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return l.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return l.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return l.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,o,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+o,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+o||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",o=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-o.length))+o}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const o=e.toLowerCase();if(o.length===e.length)return{text:o,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let o=0;o65535?2:1);for(;u65535?2:1}const f=e.slice(o,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:o}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:o},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+o-1]}function aH(e,t,n,r){const i=e.length,o=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*o),m=new Float64Array(i*o);for(let w=0;w0&&(N=Math.max(m[_-o-1]+Pl[f[n+E]],h[_-o-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=o-1;w>=0;w--)for(;x>=0;x--){const j=w*o+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-o-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*o-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const o=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let o=n;for(let u=0;u=o)return!0;if(o=t.indexOf(e[u],o)+1,o===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,o=-1;for(let u=0;ui&&(i=f,o=u)}return o<0?-1/0:(r&&_g(e.drops[o].text,e.drops[o].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,o=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!o){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),o=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!o?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const o=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return o!==u?o0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,o=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],o):n.push([i,o])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const o={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:o,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,o=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{o.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;o.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:o=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>o===w||o.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),o=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:o.list,folderCount:i.total,fileCount:o.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const o=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&o.push(e.slice(u,m)),o.push(l.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[l.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",l.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&l.jsxs(i,{onSelect:()=>n.newFile(f),children:[l.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&l.jsxs(i,{onSelect:()=>n.togglePin(e),children:[l.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),l.jsx(o,{}),l.jsxs(i,{onSelect:()=>n.copyPath(e),children:[l.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&l.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[l.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&l.jsx(o,{}),n.history&&l.jsxs(i,{onSelect:()=>n.history(e),children:[l.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&l.jsxs(i,{onSelect:()=>n.insights(e),children:[l.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&l.jsxs(l.Fragment,{children:[l.jsx(o,{}),l.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[l.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:o,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>l.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return l.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:l.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return l.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return l.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsx("span",{className:"chev",children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"system"})}),l.jsx("span",{className:"label",children:"System files"}),l.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&o){r(W.path);return}m.open(W.path),W.dir||ds()};return l.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[l.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[l.jsx(VV,{asChild:!0,children:l.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),l.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),l.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&l.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&l.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&l.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:l.jsx(ge,{name:"lock"})}),l.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&l.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:l.jsx(ge,{name:"plus"})}),l.jsx(Wv,{asChild:!0,children:l.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:l.jsx(ge,{name:"dots"})})})]})]})}),l.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),l.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,o]=b.useState(!1);b.useEffect(()=>o(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>l.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:E.dir?"folder":"doc"})}),l.jsxs("span",{className:"fhit-text",children:[l.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),l.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&l.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return l.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&l.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&l.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&l.jsxs("button",{className:"fmore",onClick:()=>o(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&l.jsx("div",{className:"fempty",children:"No file or folder names match"}),l.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"search"})}),l.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),l.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:o,onUnpin:u}=e;return t.length?l.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[l.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return l.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&o(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),o(f))},children:[l.jsx(ge,{name:"star"}),l.jsx("span",{className:"label",children:h}),m>0&&l.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&l.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),l.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:l.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-sep"}),t.map(i=>{const o=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return l.jsx(jv,{icon:"doc",label:o,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return l.jsx("span",{className:"crumbs",title:e,children:n.map((i,o)=>{r=r?r+"/"+i:i;const u=r,f=o===n.length-1,h=o>0&&!f;return l.jsxs("span",{className:"crumb",children:[o>0&&l.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?l.jsx("span",{className:"crumb-last",children:i}):l.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,o=e?.until?Ng(e.until):null;return i&&(r.since=i),o&&(r.until=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const o of["q","user","actor","device"])e?.[o]&&n.set(o,e[o]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:o[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=o[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,o=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return l.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[l.jsxs("div",{className:"fv-chips",children:[n&&l.jsxs("span",{className:"fv-chip accent",children:[l.jsx(ge,{name:"shield"})," ",n]}),r&&l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),l.jsxs("div",{className:"fv-meta",children:[o&&l.jsxs("span",{className:"meta-stale",title:o,children:[l.jsx("span",{"aria-hidden":"true",children:"⚠ "}),o]}),f&&l.jsxs("span",{className:"fv-who",title:f,children:[l.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&l.jsxs("span",{children:[l.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&l.jsxs("span",{className:"fv-when",children:[l.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&l.jsxs("span",{className:"fv-reads",title:Ur,children:[l.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,o=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(o),y=r?Vs(r):0;if(!o.length&&!n?.length&&!y)return null;const g=l.jsxs(l.Fragment,{children:[o.length>0&&l.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[l.jsx("p",{className:"fv-sec-h",children:"On this page"}),l.jsx("ul",{children:o.map(w=>l.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:l.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&l.jsx(PH,{heat:r,insightsHref:i}),n?.length?l.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[l.jsx("p",{className:"fv-sec-h",children:"Properties"}),l.jsx("dl",{children:n.map(w=>l.jsxs("div",{children:[l.jsx("dt",{children:w.key}),l.jsx("dd",{children:w.code?l.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?l.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:l.jsx("div",{className:"fv-rail-in",children:g})}):l.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[l.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),l.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return l.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[l.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&l.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),l.jsxs("div",{className:"fv-big",title:Ur,children:[n,l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),l.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>l.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),l.jsx("div",{className:"fv-legend",children:r.map(i=>l.jsxs("span",{children:[l.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&l.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const o=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(o))};return o(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],o="",u=!1,f=0;const h=()=>{i.push(o),o="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,o=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=l.jsxs(l.Fragment,{children:[i&&m.length>0&&l.jsx(ZH,{...e,secs:m}),l.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[l.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&l.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?l.jsxs("p",{className:"er-empty",children:["None yet. Type ",l.jsx("kbd",{children:"/"})," and pick Action item, or write ",l.jsx("code",{children:"- [ ] … @owner"}),"."]}):l.jsx("ul",{className:"er-list",children:h.map(g=>l.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[l.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),l.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",l.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&l.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return o?l.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:l.jsx("div",{className:"fv-rail-in",children:y})}):l.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[l.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),l.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return l.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[l.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),l.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:l.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),l.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),o=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return l.jsxs("li",{children:[l.jsx(G2,{name:r.name}),l.jsx("span",{className:"er-name",children:r.name}),l.jsx("span",{className:"er-state "+(o?"typing":r.body?"done":"none"),children:i&&u?"You · editing":o?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[o,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return l.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[l.jsx("h4",{children:"Recent versions"}),l.jsxs("ul",{className:"er-vlist",children:[l.jsxs("li",{className:"now",children:[l.jsx("i",{className:"er-dot live","aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",children:"Now"}),l.jsx("span",{className:"er-vwho",children:"Live"}),l.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return l.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[l.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),l.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),l.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&l.jsx("button",{type:"button",className:"er-restore",disabled:!!o,title:"Restore this version as a new version",onClick:()=>{y(g)},children:o===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),l.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CUvVSG63.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CwChUaNM.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,o]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&o(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{o(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,o=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?l.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?l.jsx(s7,{...e}):oi.test(n)?l.jsx(a7,{...e}):Lr.test(n)?l.jsx(WH,{...e,fileURL:o}):id.test(n)?l.jsx("iframe",{className:"pdfview",src:o,title:n,onLoad:e.onRendered}):P_.test(n)?l.jsx(o7,{src:o,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?l.jsx(vS,{...e,fileURL:o,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?l.jsx(vS,{...e,fileURL:o}):l.jsx(JH,{...e,fileURL:o})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,o=V2(t,n,e.fileURL,r),u=o.url,f=b.useRef(o.fresh);f.current=o.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?l.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:o}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&o?.()},[u,o]),f?l.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?l.jsx("pre",{className:"plain",children:u.text},n):l.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"name",children:n.split("/").pop()}),l.jsx("p",{children:e.children}),l.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:o}=e;b.useEffect(()=>o?.(),[o]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:l.jsx(ge,{name:"link"})}),l.jsx("div",{className:"name",children:t.split("/").pop()}),l.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),l.jsxs("p",{children:["Target:"," ",f?l.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:l.jsx("code",{children:n})}):l.jsx("code",{children:n}),!f&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),l.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,o=Eo(t,n),u=V2(t,n,o).url,f=ly(o,["text",o],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[o]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(o)}),()=>{Fe=!1}},[w,o]);const x=y===o?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(o),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",o]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",o]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,o]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(l.jsxs(l.Fragment,{children:[l.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[l.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&l.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>l.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&l.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?l.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?l.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):l.jsxs(l.Fragment,{children:[h&&l.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&l.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&l.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[l.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&l.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>l.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[l.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&l.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?l.jsxs("div",{className:"empty",children:["Could not load the editor."," ",l.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?l.jsx("div",{className:"empty",children:"Loading editor…"}):l.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?l.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:l.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):l.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&l.jsx(r7,{...e}),!i&&l.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[l.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),l.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[l.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&l.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?l.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):l.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:o}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?l.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,o)}):l.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:o,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return l.jsx(Tf,{version:i,err:g});if(!y)return l.jsx(uN,{});const _=i?null:o&&o[y.path]||null,N=l.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return l.jsxs(l.Fragment,{children:[l.jsx(i7,{findings:y.findings}),!t&&N,l.jsx(FH,{doc:y,heat:_}),l.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return l.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[l.jsxs("div",{className:"fskel-main",children:[l.jsx("span",{className:"fskel-title"}),l.jsxs("span",{className:"fskel-meta",children:[l.jsx("span",{style:{width:120}}),l.jsx("span",{style:{width:90}}),l.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>l.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),l.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[l.jsx("span",{style:{width:"40%"}}),l.jsx("span",{style:{width:"80%"}}),l.jsx("span",{style:{width:"65%"}}),l.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?l.jsxs("div",{className:"sbadge",role:"status",children:[l.jsx("span",{className:"sb-icon",children:l.jsx(ge,{name:"shield"})}),l.jsxs("div",{className:"sb-text",children:[l.jsx("b",{children:GH(e)}),l.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(o,decodeURIComponent(i))))}function py(e,t,n,r,i){const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(o,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?l.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):l.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return l.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:o}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&o?.()},[u,o]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?l.jsx(Tf,{version:n,err:f}):u==null?null:h?l.jsx(l7,{csv:h},t):l.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((o,u)=>Math.max(o,u.length),0),i=Array.from({length:r},(o,u)=>u);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"csvbox",children:l.jsxs("table",{className:"csvview",children:[l.jsx("thead",{children:l.jsx("tr",{children:i.map(o=>l.jsx("th",{children:t[o]??""},o))})}),l.jsx("tbody",{children:n.map((o,u)=>l.jsx("tr",{children:i.map(f=>l.jsx("td",{children:o[f]??""},f))},u))})]})}),e.truncated>0&&l.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return l.jsxs("span",{className:"dv-dl",children:[l.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),l.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),o=tc(e,r,!0),u=i.data?.kind==="text"&&o.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&o.data?.kind==="text"?kg(i.data.text,o.data.text):null,[i.data,o.data]);if(i.error||o.error)return l.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!o.data)return l.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||o.data.kind==="too-large";return l.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",l.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return l.jsxs("div",{className:"dv",children:[l.jsxs("div",{className:"dv-head",children:[l.jsxs("span",{className:"dv-stat",children:[l.jsxs("span",{className:"dv-add",children:["+",m]})," ",l.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&l.jsx("span",{className:"dv-same",children:"No line changes"})]}),l.jsx("div",{className:"dv-body",children:h.map((g,w)=>l.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[l.jsx("span",{className:"dv-n",children:g.an??""}),l.jsx("span",{className:"dv-n",children:g.bn??""}),l.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),l.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),o=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||o.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,o.data.text):kg("",o.data.text),[i.data,o.data,t])}function d7({add:e,del:t}){return l.jsxs("span",{className:"hstat",children:[e>0&&l.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&l.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:o,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return l.jsxs("div",{className:"dtabs",children:[l.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>l.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),l.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?l.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):l.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&l.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:o,projectId:u,onOpenFile:f}),h==="full"&&y&&l.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:o}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?l.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?l.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?l.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,o)}):l.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):l.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?l.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?l.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):l.jsx("div",{className:"dv",children:l.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;o+=y}}return u||((o!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,o=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=l.jsxs(l.Fragment,{children:[i&&m.length>0&&l.jsx(ZH,{...e,secs:m}),l.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[l.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&l.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?l.jsxs("p",{className:"er-empty",children:["None yet. Type ",l.jsx("kbd",{children:"/"})," and pick Action item, or write ",l.jsx("code",{children:"- [ ] … @owner"}),"."]}):l.jsx("ul",{className:"er-list",children:h.map(g=>l.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[l.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),l.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",l.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&l.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return o?l.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:l.jsx("div",{className:"fv-rail-in",children:y})}):l.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[l.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),l.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return l.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[l.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),l.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:l.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),l.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),o=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return l.jsxs("li",{children:[l.jsx(G2,{name:r.name}),l.jsx("span",{className:"er-name",children:r.name}),l.jsx("span",{className:"er-state "+(o?"typing":r.body?"done":"none"),children:i&&u?"You · editing":o?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[o,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return l.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[l.jsx("h4",{children:"Recent versions"}),l.jsxs("ul",{className:"er-vlist",children:[l.jsxs("li",{className:"now",children:[l.jsx("i",{className:"er-dot live","aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",children:"Now"}),l.jsx("span",{className:"er-vwho",children:"Live"}),l.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return l.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[l.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),l.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),l.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&l.jsx("button",{type:"button",className:"er-restore",disabled:!!o,title:"Restore this version as a new version",onClick:()=>{y(g)},children:o===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),l.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DHvYAyxu.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-BYnijXna.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,o]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&o(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{o(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,o=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?l.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?l.jsx(s7,{...e}):oi.test(n)?l.jsx(a7,{...e}):Lr.test(n)?l.jsx(WH,{...e,fileURL:o}):id.test(n)?l.jsx("iframe",{className:"pdfview",src:o,title:n,onLoad:e.onRendered}):P_.test(n)?l.jsx(o7,{src:o,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?l.jsx(vS,{...e,fileURL:o,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?l.jsx(vS,{...e,fileURL:o}):l.jsx(JH,{...e,fileURL:o})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,o=V2(t,n,e.fileURL,r),u=o.url,f=b.useRef(o.fresh);f.current=o.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?l.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:o}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&o?.()},[u,o]),f?l.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?l.jsx("pre",{className:"plain",children:u.text},n):l.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"name",children:n.split("/").pop()}),l.jsx("p",{children:e.children}),l.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:o}=e;b.useEffect(()=>o?.(),[o]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:l.jsx(ge,{name:"link"})}),l.jsx("div",{className:"name",children:t.split("/").pop()}),l.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),l.jsxs("p",{children:["Target:"," ",f?l.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:l.jsx("code",{children:n})}):l.jsx("code",{children:n}),!f&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),l.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,o=Eo(t,n),u=V2(t,n,o).url,f=ly(o,["text",o],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[o]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(o)}),()=>{Fe=!1}},[w,o]);const x=y===o?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(o),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",o]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",o]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,o]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(l.jsxs(l.Fragment,{children:[l.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[l.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&l.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>l.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&l.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?l.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?l.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):l.jsxs(l.Fragment,{children:[h&&l.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&l.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&l.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[l.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&l.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>l.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[l.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&l.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?l.jsxs("div",{className:"empty",children:["Could not load the editor."," ",l.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?l.jsx("div",{className:"empty",children:"Loading editor…"}):l.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?l.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:l.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):l.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&l.jsx(r7,{...e}),!i&&l.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[l.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),l.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[l.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&l.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?l.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):l.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:o}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?l.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,o)}):l.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:o,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return l.jsx(Tf,{version:i,err:g});if(!y)return l.jsx(uN,{});const _=i?null:o&&o[y.path]||null,N=l.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return l.jsxs(l.Fragment,{children:[l.jsx(i7,{findings:y.findings}),!t&&N,l.jsx(FH,{doc:y,heat:_}),l.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return l.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[l.jsxs("div",{className:"fskel-main",children:[l.jsx("span",{className:"fskel-title"}),l.jsxs("span",{className:"fskel-meta",children:[l.jsx("span",{style:{width:120}}),l.jsx("span",{style:{width:90}}),l.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>l.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),l.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[l.jsx("span",{style:{width:"40%"}}),l.jsx("span",{style:{width:"80%"}}),l.jsx("span",{style:{width:"65%"}}),l.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?l.jsxs("div",{className:"sbadge",role:"status",children:[l.jsx("span",{className:"sb-icon",children:l.jsx(ge,{name:"shield"})}),l.jsxs("div",{className:"sb-text",children:[l.jsx("b",{children:GH(e)}),l.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(o,decodeURIComponent(i))))}function py(e,t,n,r,i){const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(o,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?l.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):l.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return l.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:o}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&o?.()},[u,o]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?l.jsx(Tf,{version:n,err:f}):u==null?null:h?l.jsx(l7,{csv:h},t):l.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((o,u)=>Math.max(o,u.length),0),i=Array.from({length:r},(o,u)=>u);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"csvbox",children:l.jsxs("table",{className:"csvview",children:[l.jsx("thead",{children:l.jsx("tr",{children:i.map(o=>l.jsx("th",{children:t[o]??""},o))})}),l.jsx("tbody",{children:n.map((o,u)=>l.jsx("tr",{children:i.map(f=>l.jsx("td",{children:o[f]??""},f))},u))})]})}),e.truncated>0&&l.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return l.jsxs("span",{className:"dv-dl",children:[l.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),l.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),o=tc(e,r,!0),u=i.data?.kind==="text"&&o.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&o.data?.kind==="text"?kg(i.data.text,o.data.text):null,[i.data,o.data]);if(i.error||o.error)return l.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!o.data)return l.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||o.data.kind==="too-large";return l.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",l.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return l.jsxs("div",{className:"dv",children:[l.jsxs("div",{className:"dv-head",children:[l.jsxs("span",{className:"dv-stat",children:[l.jsxs("span",{className:"dv-add",children:["+",m]})," ",l.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&l.jsx("span",{className:"dv-same",children:"No line changes"})]}),l.jsx("div",{className:"dv-body",children:h.map((g,w)=>l.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[l.jsx("span",{className:"dv-n",children:g.an??""}),l.jsx("span",{className:"dv-n",children:g.bn??""}),l.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),l.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),o=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||o.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,o.data.text):kg("",o.data.text),[i.data,o.data,t])}function d7({add:e,del:t}){return l.jsxs("span",{className:"hstat",children:[e>0&&l.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&l.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:o,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return l.jsxs("div",{className:"dtabs",children:[l.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>l.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),l.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?l.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):l.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&l.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:o,projectId:u,onOpenFile:f}),h==="full"&&y&&l.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:o}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?l.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?l.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?l.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,o)}):l.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):l.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?l.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?l.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):l.jsx("div",{className:"dv",children:l.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>l.jsxs("div",{className:"dv-line dv-ctx",children:[l.jsx("span",{className:"dv-n",children:i+1}),l.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):l.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return l.jsx(l.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?l.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:o,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!o&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!o?.busy&&o.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return l.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[l.jsxs("div",{className:"hline",children:[l.jsx("span",{className:"hkind",children:g7[N]||N}),m&&l.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),l.jsx("span",{className:"hpath",children:e.path}),q&&l.jsx(d7,{add:q.add,del:q.del}),l.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),l.jsxs("div",{className:"hmeta",children:[l.jsx("span",{className:"hwho",title:R,children:yv(e)}),l.jsx("span",{className:"hdev",children:T}),l.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&l.jsx("span",{className:"hgone",children:"can be restored"}),V&&l.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&l.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&l.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&l.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),o.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&l.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:l.jsx(fN,{text:e.note})}),(M||Y)&&l.jsxs("div",{className:"hactions",children:[M&&(r.prev?l.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):l.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"clock"}),"Open this version"]}),l.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[l.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,o=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=o.filter(g=>g.dir).length,f=o.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||o.some(g=>hd(n,g.path,!!g.dir));return l.jsxs("div",{className:"dirlist",children:[l.jsxs("h1",{className:"dl-title",children:[l.jsx("span",{className:"dl-title-icon",children:l.jsx(ge,{name:"folder"})}),l.jsx("span",{children:t.name})]}),l.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&l.jsx("p",{className:"dl-heatnote",children:Ur}),o.length===0?l.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):l.jsx("div",{className:"dl-items",children:o.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return l.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:g.dir?"folder":"doc"})}),l.jsx("span",{className:"dl-name",children:g.name}),S&&l.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&l.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&l.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&l.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),l.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&l.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:l.jsxs("div",{className:"dl-history",children:[l.jsx("h3",{className:"dl-h3",children:"Recent changes"}),l.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>l.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),l.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:o,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return l.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:l.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:B})}),l.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Everyone in ",g," can"]}),l.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&l.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&l.jsxs("p",{className:"ps-note",children:["A folder set to ",l.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",l.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&l.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&l.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),l.jsx("span",{className:"ai-main",title:P.email,children:P.email}),l.jsx("span",{className:"role-cell",children:l.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>l.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&l.jsxs("div",{className:"admin-item sd-add",children:[l.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),l.jsxs("span",{className:"role-cell",children:[l.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"ps-row",children:_?l.jsxs("span",{children:["Access comes from the rule on ",l.jsx("b",{children:_.prefix})," — you can"," ",l.jsx("b",{children:_.me})," here."]}):l.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&l.jsxs(l.Fragment,{children:[" — the project default is ",l.jsx("b",{children:m.default})]}),"."]})}),_&&l.jsx("p",{className:"ps-row",children:l.jsxs(Ie,{variant:"subtle",onClick:()=>o(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),l.jsx("h4",{className:"sd-head",children:"Public link"}),n?l.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsx("span",{children:l.jsx(ge,{name:T?"globe":"lock"})}),l.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[l.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),l.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sd-warn",children:l.jsx("b",{children:"This file may contain credentials"})}),l.jsx("p",{className:"ps-note",children:BH(W)}),l.jsxs("p",{className:"ps-row",children:[l.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),l.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"modal-url",children:T.url}),l.jsxs("div",{className:"modal-expiry",children:[l.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),l.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:l.jsxs("div",{className:"share-banner",role:"status",children:[l.jsxs("div",{className:"sb-head",children:[l.jsx(ge,{name:"share"}),l.jsx("b",{children:"Publicly shared"}),l.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),l.jsxs("p",{className:"sb-note",children:[l.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&l.jsxs(l.Fragment,{children:[" ",v2]})]}),e.map(r=>l.jsxs("div",{className:"sb-link",children:[l.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),l.jsx("span",{className:"sb-meta",children:g2(r,!1)}),l.jsxs("span",{className:"sb-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&l.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,o)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==o);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,o,u,f)=>{const h=await Sn(e+"comments",{path:i,body:o,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,o,u="")=>{const f=await Sn(e+"comments/"+i,{action:o,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;mo&&(i=u,o=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),o=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return o<0?null:[i[o],i[o+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const o=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=o.nextNode();u;u=o.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[o]=0)return e.starts[r]+n;const o=t.ownerDocument.createRange();o.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),o=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=o)return null;const f=(n||i.all.slice(o,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,o,u)};return r&&(h.line=i.all.slice(0,o).split(` `).length),h}function N7(e,t,n,r){const i=e;let o=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([o,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([o,u]=[f.startContainer,f.startOffset])}if(!o)return null;for(const[f,h]of r)try{if(h.isPointInRange(o,u)&&!(h.endContainer===o&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:o,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(o),[o]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return l.jsxs(l.Fragment,{children:[e.children,l.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>l.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[l.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&l.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[l.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&l.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[l.jsx(vN,{a:j.anchor}),l.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),l.jsxs("div",{className:"cm-row",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),l.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:o,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),o(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return l.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[l.jsxs("header",{className:"cm-head",children:[l.jsx("b",{children:"Comments"}),l.jsxs("div",{className:"cm-tabs",role:"tablist",children:[l.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&l.jsxs("span",{children:[" · ",j.length]})]}),l.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&l.jsxs("span",{children:[" · ",S.length]})]})]}),l.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:l.jsx(ge,{name:"x"})})]}),f&&l.jsx("div",{className:"cm-pickbar",children:l.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[l.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),l.jsxs("div",{className:"cm-list",children:[R.length===0&&l.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>l.jsx(M7,{t:U,active:U.id===i,onFocus:()=>o(U.id===i?null:U.id),onJump:()=>{o(null),requestAnimationFrame(()=>o(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),l.jsxs("footer",{className:"cm-foot",children:[l.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),l.jsxs("div",{className:"cm-row",children:[l.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",l.jsx("code",{children:"bdrive comments"})]}),l.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:o,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await o.act(t.id,S,h),m("")});return l.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[l.jsxs("div",{className:"cm-card-top",onClick:r,children:[l.jsx("span",{className:"cm-n",children:t.n}),l.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&l.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>l.jsxs("div",{className:"cm-msg",children:[l.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),l.jsxs("div",{className:"cm-msg-main",children:[l.jsxs("div",{className:"cm-who",children:[l.jsx("b",{children:S.name||S.author||"someone"})," ",l.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),l.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&l.jsxs("div",{className:"cm-queued",children:[l.jsx(ge,{name:"sparkle"}),l.jsxs("span",{children:["Queued for next agent sweep · ",l.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&l.jsxs("div",{className:"cm-resolved",children:[l.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),l.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),l.jsxs("div",{className:"cm-row",children:[u&&l.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await o.remove(t.id)})},children:l.jsx(ge,{name:"trash"})}),l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&l.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[l.jsx(ge,{name:"jump"})," Jump to text"]}),l.jsx("span",{className:"cm-spacer"}),h.trim()&&l.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?l.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):l.jsxs("div",{className:"cm-anchor",children:[e.quote&&l.jsxs("div",{className:"cm-quote",children:[e.prefix&&l.jsx("span",{className:"cm-ctx",children:e.prefix}),l.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&l.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&l.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,o,u){if(o===t.length)return i===e.length?_S:$7;var f=`${i},${o}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(o),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,o+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(o)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),o=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=o.current.get(D))==null?void 0:I.value)&&(o.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{o.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{o.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=o.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=o.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),o=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,o,[e.value,e.children,o],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=o.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(o,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...o}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...o,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),o=ka(u=>!u.search);return!n&&!o?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,o=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||o.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,o=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&o.current){let m=u.current,y=o.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(o,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:o,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:o},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...o}=e;return b.createElement(ot.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),o=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());o.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return l.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[l.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),l.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return l.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return l.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return l.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"picon",children:l.jsx(ge,{name:e.icon})}),l.jsxs("span",{className:"ptext",children:[l.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&l.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&l.jsx("span",{className:"ploc",children:n})]}),!r&&l.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[o,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=o.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(o,m,{limit:oq}).hits,[o,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return l.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:l.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[l.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),l.jsxs(sq,{shouldFilter:!1,loop:!0,children:[l.jsxs("div",{id:"palette-inputwrap",children:[l.jsx(ge,{name:"search"}),l.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:o,onValueChange:u})]}),l.jsx(aq,{children:h?y.length===0?l.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return l.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:l.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>l.jsx(iq,{heading:x,children:j.map(S=>l.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:l.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),l.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=o=>(o.session?"s\0"+o.session:"n\0"+o.note)+"\0"+(o.device?.id??""),n=new Map;e.forEach((o,u)=>{if(!o.note&&!o.session)return;const f=n.get(t(o));if(f){f.entries.push(o),f.idx.push(u);return}n.set(t(o),{note:o.note??"",session:o.session,entries:[o],idx:[u]})});const r=[],i=new Set;return e.forEach((o,u)=>{const f=o.note||o.session?n.get(t(o)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const o of e)r++,n.add(o.path),xi(o)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=o=>o.seq?(o.device?.id??"")+"\0"+o.seq:o.time+"\0"+o.path+"\0"+o.kind+"\0"+(o.device?.id??""),r=new Set,i=[];for(const o of[...e,...t]){const u=n(o);r.has(u)||(r.add(u),i.push(o))}return i.sort((o,u)=>Date.parse(u.time)-Date.parse(o.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let o=n.get(i);o||(o={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,o)),!o.agent&&xi(r)&&(o.agent=Mf(r.note)),t&&r.user===t&&(o.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const o of e){const u=t[o.path],f=ay(o.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:o.path,reads:h,days:f})}return i.sort((o,u)=>u.reads-o.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=o=>{let u=o.dir?0:Date.parse(o.time||"")||0;for(const f of o.children||[])u=Math.max(u,r(f));return u},i=[];for(const o of e.children||[]){if(!o.dir)continue;const u=hd(t,o.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(o);i.push({name:o.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((o,u)=>u.reads-o.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,o=t.id,u=Eq(o),f=sy(o),h=RN(o),[m,y]=b.useState(""),g=T2(o),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return l.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return l.jsx("div",{className:"home home-empty",children:l.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,o),H=cn("history",o,"",m?{actor:m}:void 0);return l.jsxs("div",{className:"home",children:[l.jsxs("header",{className:"home-head",children:[l.jsx("h1",{className:"home-greet",children:gq(i?.name)}),l.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&l.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[l.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),l.jsx("div",{className:"home-cards",children:R.map(U=>l.jsxs("a",{className:"home-card",...In(L(U.path)),children:[l.jsxs("span",{className:"hc-name",children:[l.jsx(ge,{name:"doc"}),Vd(U.path)]}),l.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),l.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),l.jsxs("div",{className:"home-grid",children:[l.jsxs("div",{className:"home-main",children:[l.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[l.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&l.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?l.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):l.jsx("ul",{className:"home-list",children:T.map(U=>l.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),l.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Recent activity"}),l.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>l.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?l.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?l.jsx("p",{className:"home-none",children:"No changes yet."}):l.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return l.jsxs("li",{className:"home-fe",children:[l.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:l.jsx(ge,{name:Y?"sparkle":"users"})}),l.jsxs("div",{className:"fe-body",children:[l.jsxs("div",{children:[l.jsx("b",{className:"fe-who",children:ae})," ",l.jsx("span",{className:"fe-what",children:le})]}),W?l.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?l.jsx("span",{className:"fe-path del",children:Z.path}):l.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&l.jsx("span",{className:"fe-dev",children:Z.device.name})]}),l.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):l.jsx("p",{className:"home-none",children:"Loading…"})]})]}),l.jsxs("aside",{className:"home-side",children:[l.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[l.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?l.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):l.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&l.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),l.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[l.jsxs("h2",{className:"home-h",children:[l.jsx(ge,{name:"terminal"}),"Connect another device"]}),l.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),l.jsx(Jl,{code:kf(window.location.origin,{project:t})}),l.jsx("a",{className:"home-more",...In(cn("install",o)),children:"Full setup guide →"})]}),A.length>0&&l.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Where reads go"}),l.jsx("a",{className:"home-more",...In(cn("dashboard",o)),children:"Insights →"})]}),l.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>l.jsxs("li",{className:"fresh-"+U.fresh,children:[l.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[l.jsx("span",{children:U.name}),l.jsx("span",{className:"hb-n",children:U.reads})]}),l.jsx("span",{className:"hb-track",children:l.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),l.jsxs("div",{className:"home-legend",children:[l.jsx("span",{className:"fresh-fresh",children:"fresh"}),l.jsx("span",{className:"fresh-aging",children:"aging"}),l.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&l.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:l.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,o,u;return e.kind==="conflict"?(n="alert",u="conflict",r=l.jsxs(l.Fragment,{children:["Sync conflict on ",l.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,o="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=l.jsxs(l.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",l.jsx("b",{children:Vd(e.path)})]}),i=e.path,o="Reply"):(n="clock",u="stale",r=l.jsxs(l.Fragment,{children:[l.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,o="Review"),l.jsxs("li",{className:"home-attn-row "+u,children:[l.jsx("span",{className:"ha-icon","aria-hidden":"true",children:l.jsx(ge,{name:n})}),l.jsxs("div",{className:"ha-text",children:[l.jsx("span",{className:"ha-title",children:r}),l.jsx("span",{className:"ha-sub",children:i})]}),l.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:o})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?l.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?l.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,o]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return l.jsxs("div",{className:"insights",children:[l.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsxs("div",{className:"dl-empty in-blank",children:[l.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),l.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&l.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?l.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return l.jsxs("div",{className:"insights",children:[l.jsxs("div",{className:"in-top",children:[l.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>l.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&l.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),l.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),l.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),l.jsx(Pq,{pts:S,th:i,setTh:o,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),l.jsxs("div",{className:"in-split",children:[l.jsxs("section",{className:"in-sec in-sec-map",children:[l.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),l.jsxs("section",{className:"in-sec in-sec-hot",children:[l.jsx("h2",{className:"in-h2",children:"Hot path"}),l.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),l.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),l.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&l.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return l.jsxs("section",{className:"in-sec","data-sec":e.id,children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&l.jsx("p",{className:"in-sub",children:e.sub})]}),l.jsxs("div",{className:"in-sec-tools",children:[e.aside,l.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?l.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],o=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:o("human"),agent:o("agent"),share:o("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return l.jsxs("div",{className:"in-kpis",children:[l.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[l.jsx("div",{className:"in-kpi-l",children:"Reads"}),l.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),l.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?l.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),l.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>l.jsxs("span",{"data-kind":x,children:[l.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[l.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),l.jsxs("div",{className:"in-kpi-v",children:[m,"% ",l.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),l.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:l.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[l.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),l.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&l.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),l.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[l.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),l.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&l.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),l.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const o=Math.round(Number(r));return Number.isFinite(o)&&o>=1?o:i};return l.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[l.jsxs("label",{children:["Stale after"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),l.jsx("span",{"aria-hidden":!0,children:"·"}),l.jsxs("label",{children:["hot ≥"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return l.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?l.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,o)=>Number(o.empty)-Number(i.empty)||o.reads*Math.max(1,o.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return l.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:"Fix these first"}),l.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),l.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?l.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):l.jsxs("table",{className:"in-fix-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads · 30d"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Why it's here"}),l.jsx("th",{children:l.jsx("span",{className:"sr-only",children:"Action"})})]})}),l.jsx("tbody",{children:n.map(i=>{const o=i.path.lastIndexOf("/");return l.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[l.jsxs("td",{className:"in-fx-file",children:[l.jsx(AN,{p:i}),l.jsxs("span",{className:"in-fx-name",children:[l.jsx("span",{children:i.path.slice(o+1)}),o>0&&l.jsx("small",{children:i.path.slice(0,o+1)})]})]}),l.jsxs("td",{className:"in-fx-reads",children:[l.jsx("span",{className:"in-fx-track",children:l.jsx(Fq,{p:i,max:r,lens:e.lens})}),l.jsx("span",{className:"in-fx-n",children:i.reads})]}),l.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),l.jsx("td",{className:"in-fx-why",children:Lq(i)}),l.jsx("td",{className:"in-fx-act",children:i.empty?l.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):l.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&l.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const o=e.reduce((m,y)=>m+y.value,0);if(!o||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/o*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),o=n.get(i);o?o.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const o=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:o.reduce((u,f)=>u+f.reads,0),days:qq((o.length?o:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,o)=>i+o[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=o===null?e:e.filter(_=>DN(_.path,f)===o),w=o===null?Bq(e,f):Gq(g,o||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=l.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[l.jsx("button",{className:o===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),o!==null&&l.jsxs(l.Fragment,{children:[l.jsx("span",{"aria-hidden":!0,children:"›"}),l.jsx("span",{className:"cur",children:o||"(root)"}),o&&i(o)&&l.jsx("button",{className:"in-tm-open",onClick:()=>r(o),children:"Open folder"})]}),o===null&&l.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:o===null?"Folder":"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Files"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Flag"})]})}),l.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>l.jsxs("tr",{children:[l.jsx("td",{children:_.label}),l.jsx("td",{children:_.reads}),l.jsx("td",{children:_.files.length}),l.jsx("td",{children:vc(_.days)}),l.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return l.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,l.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":o===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return l.jsxs("g",{children:[l.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:l.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&l.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&l.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),l.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return l.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",l.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((o,u)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",o]},o))}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),l.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const o=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return o.some(u=>u.top.length)?l.jsx(l.Fragment,{children:o.map(({k:u,total:f,top:h})=>l.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):l.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsxs("th",{children:[Dg[t]," reads"]}),l.jsx("th",{children:"Last change"})]})}),l.jsx("tbody",{children:n.map(o=>l.jsxs("tr",{children:[l.jsx("td",{children:o.path}),l.jsx("td",{children:o[t]}),l.jsx("td",{children:o.orphan?"deleted":vc(o.days)})]},o.path))})]});return l.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:l.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:l.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[l.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&l.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(o=>{const u=()=>o.orphan?e.onOpenHistory(o.path):e.onOpenFile(o.path),f={danger:o[t]>=e.th.hot&&o.danger,empty:o.empty};return l.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(o),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[l.jsxs("span",{className:"in-hp-line",children:[l.jsxs("span",{className:"in-hp-name"+(o.danger||o.empty?" danger":""),children:[l.jsx(AN,{p:{danger:o.danger||f.danger,empty:o.empty}}),o.path]}),o.orphan&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),l.jsx("span",{className:"in-hp-count",children:o[t]})]}),l.jsx("span",{className:"in-hp-bar",children:l.jsx("span",{className:"in-hp-"+t,style:{width:(o[t]/r*100).toFixed(1)+"%"}})})]},o.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const o={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>o.l+m+N/f*(960-o.l-o.r-2*m),g=N=>340-o.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-o.t-o.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-o.r,top:o.t+8,bottom:340-o.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Days since change"}),l.jsx("th",{children:"Verdict"})]})}),l.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>l.jsxs("tr",{children:[l.jsx("td",{children:N.path}),l.jsx("td",{children:N.reads}),l.jsx("td",{children:Math.round(N.days)}),l.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return l.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:l.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[l.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[l.jsx("rect",{x:y(t.stale),y:o.t,width:Math.max(0,960-o.r-y(t.stale)),height:Math.max(0,g(t.hot)-o.t),className:"in-danger-zone"}),S.map(N=>l.jsxs("text",{x:y(N),y:340-o.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>l.jsx("text",{x:o.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),l.jsx("line",{x1:y(t.stale),y1:o.t,x2:y(t.stale),y2:340-o.b,className:"in-threshold","data-th":"stale"}),l.jsx("line",{x1:o.l,y1:g(t.hot),x2:960-o.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),l.jsx("line",{x1:o.l,y1:340-o.b,x2:960-o.r,y2:340-o.b,className:"in-axis"}),l.jsx("line",{x1:o.l,y1:o.t,x2:o.l,y2:340-o.b,className:"in-axis"}),l.jsx("text",{x:960-o.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),l.jsx("text",{x:12,y:(o.t+340-o.b)/2,className:"in-label",transform:`rotate(-90 12 ${(o.t+340-o.b)/2})`,children:"reads / 30d (log) →"}),l.jsx("text",{x:y(t.stale)+6,y:o.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),l.jsxs("text",{x:y(t.stale)+92,y:o.t+14,className:"in-quad-count",children:["· ",x]}),l.jsx("text",{x:o.l+6,y:o.t+14,className:"in-quad",children:"hot + fresh"}),l.jsx("text",{x:960-o.r-6,y:340-o.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),l.jsx("text",{x:o.l+6,y:340-o.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>l.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:l.jsx("title",{children:Af(N)})},N.path)),j.map(N=>l.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),l.jsxs("p",{className:"in-legend",children:[l.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",l.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",l.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((o,u)=>o+u.total,0);if(!r)return n;if(e.length>=3){const o=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(o/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(o=>o.total=2){const o=t[t.length-1];n.push({icon:"archive",head:`${o.name||"(root)"}${o.name?"/":""} is the least-read folder by agents`,body:`${Hs(o.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return l.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,o=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(o,r),f=t==="human"||t==="share",h=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Device"}),r.map(y=>l.jsx("th",{children:y.name||"(root)"},y.name)),l.jsx("th",{children:"Total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("td",{children:y.name}),r.map(g=>l.jsx("td",{children:i(y.d,g.name)},g.name)),l.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=l.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return l.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&l.jsxs("div",{className:"in-cov",children:[l.jsxs("div",{className:"in-matrix-wrap",children:[l.jsxs("table",{className:"in-matrix",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{}),r.map(y=>l.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),l.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return l.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),l.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),l.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&l.jsxs("aside",{className:"in-takeaways",children:[l.jsx("h3",{children:"What this tells you"}),u.map(y=>l.jsxs("div",{className:"in-takeaway",children:[l.jsx(sB,{name:y.icon}),l.jsxs("div",{children:[l.jsx("b",{children:y.head}),l.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,o=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&o({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return l.jsxs("div",{className:"hfilters",children:[l.jsxs("label",{className:"hf-search",children:[l.jsx(ge,{name:"search"}),l.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>l.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>o({actor:N}),children:R},R))}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"laptop"}),l.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;o({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[l.jsx("option",{value:"",children:"All devices"}),j.length>0&&l.jsx("optgroup",{label:"Devices",children:j.map(N=>l.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&l.jsx("optgroup",{label:"People",children:x.map(N=>l.jsx("option",{value:"u:"+N,children:N},N))})]})]}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"clock"}),l.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&o({range:void 0});return}y(!1),o({range:R,since:void 0,until:void 0})},children:[l.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>l.jsx("option",{value:N,children:R},N)),l.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&l.jsxs("span",{className:"hf-dates",children:[l.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>o({since:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-dash",children:"–"}),l.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>o({until:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&l.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const o={...e};for(const u of i)delete o[u];return o},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:o,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&o?.()},[S,o]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&l.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&l.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return l.jsx("div",{className:"activity",children:l.jsxs("div",{className:"history",children:[le,be,E||A?l.jsx(mB,{onRetry:U,timedOut:!E}):_&&l.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return l.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[l.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?l.jsxs("div",{className:"empty hempty",children:[l.jsx("span",{className:"hempty-icon",children:l.jsx(ge,{name:"search"})}),l.jsx("b",{children:"No changes match these filters."}),l.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>l.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,l.jsx(ge,{name:"x"})]},ve))}),l.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),l.jsxs("span",{className:"hempty-actions",children:[l.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&l.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):l.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?l.jsxs("div",{className:"hday",children:[l.jsx("b",{children:dy(Ze)}),l.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?l.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):l.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&l.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?l.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&l.jsx(dB,{})]})}function dB(){return l.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[l.jsx(ge,{name:"hist"}),l.jsx("b",{children:"Select a change"}),l.jsx("span",{children:"Its diff, rendered view and full file appear here."}),l.jsxs("span",{className:"ap-keys",children:[l.jsx("kbd",{children:"J"})," ",l.jsx("kbd",{children:"K"})," move · ",l.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return l.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[l.jsx("div",{className:"hday",children:l.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>l.jsxs("div",{className:"hskel-row",children:[l.jsx("span",{className:"hskel-dot"}),l.jsxs("span",{className:"hskel-lines",children:[l.jsx("span",{style:{width:e+"%"}}),l.jsx("span",{style:{width:e/2+"%"}})]}),l.jsx("span",{className:"hskel-time"})]},t)),l.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return l.jsxs("div",{className:"empty hempty herror",role:"alert",children:[l.jsx("span",{className:"hempty-icon herror-icon",children:l.jsx(ge,{name:"alert"})}),l.jsx("b",{children:"Couldn't load activity"}),l.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),l.jsx("span",{className:"hempty-actions",children:l.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[l.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let o="";try{o=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(o?"&tz="+encodeURIComponent(o):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return l.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return l.jsxs("div",{className:"hsum",children:[l.jsxs("div",{className:"hsum-head",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),l.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",l.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),l.jsxs("div",{className:"hsum-legend",children:[l.jsx("span",{className:"agent",children:"Agents"}),l.jsx("span",{className:"human",children:"People"})]})]}),l.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return l.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[l.jsxs("div",{className:"hsum-stack",children:[l.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),l.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),l.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",o=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return l.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[l.jsxs("div",{className:"ap-head",children:[l.jsx(ge,{name:"doc"}),l.jsx("span",{className:"ap-name",children:o}),l.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:l.jsx(ge,{name:"chev"})}),l.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:l.jsx(ge,{name:"chevd"})}),l.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:l.jsx(ge,{name:"x"})})]}),l.jsx("div",{className:"ap-path",children:t.path}),l.jsxs("div",{className:"ap-who",children:[l.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),l.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&l.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[l.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&l.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[l.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&l.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[l.jsx(ge,{name:"link"}),"Copy link"]})]}),l.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),l.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:o,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return l.jsxs("div",{className:"hrun"+(w?" open":""),children:[l.jsxs("div",{className:"hrun-head",children:[l.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:l.jsx(ge,{name:w?"chevd":"chev"})}),l.jsx("span",{className:"havatar agent","aria-hidden":"true",children:l.jsx(ge,{name:"terminal"})}),l.jsxs("span",{className:"hrun-title",children:[l.jsxs("span",{className:"hrun-what",children:[l.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),l.jsxs("span",{className:"hrun-sub",children:[l.jsx("span",{className:"hrun-note",children:l.jsx(fN,{text:e.note})}),l.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),l.jsx("span",{className:"hrun-time",children:H}),m&&l.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[l.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&l.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>l.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:o(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&l.jsxs("div",{className:"hrun-reads",children:[l.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>l.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[l.jsx("span",{className:"hkind",children:"read"}),l.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&l.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=o=>o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),o=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-o}function SB(e){const t=e.width??bB,n=i=>o=>{if(o.button!==0)return;o.preventDefault();const u=o.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=o.clientX;let g=null;u.setPointerCapture(o.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>o=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(o.key!==u&&o.key!==f)return;o.preventDefault();const h=$S(o.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(o.key===u?LS:-LS),h))};return l.jsx(l.Fragment,{children:["left","right"].map(i=>l.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=o?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"clock"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),l.jsx("span",{children:"This is not the current file."})]}),l.jsxs("div",{className:"vb-actions",children:[l.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),l.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"alert"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),l.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?l.jsxs(l.Fragment,{children:["The other version lives at ",l.jsx("code",{children:t.original})]}):l.jsx(l.Fragment,{children:"The other version kept the original name."})]})]}),n&&l.jsx("div",{className:"vb-actions",children:l.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:o}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!o),w=!i||!!o,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!o&&!!t.reads?.enabled),{data:E}=hE(i&&o?o?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!o&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&o&&Z&&!L&&pq(o.id,M)},[i,o,Z,M,L]),b.useEffect(()=>{(!i||o)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,o,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,o?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,o?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,o?.id,Ne)),ds()},[o?.id]),re=b.useCallback(ie=>gt(cn("history",o?.id,ie)),[o?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!o&&(Z||U)&&Fn(o.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!o&&Fn(Ut(M)??o.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,o?.id,L,!0,r.editing))},[M,o?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,o?.id,L,!1,r.editing),{replace:!0})},[M,o?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(o?.id,i&&!!o),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",o?.id]})},[f,o?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&o?pr?.mounts.find(ie=>ie.project===o.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!o,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!o&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!o&&Fn(o?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",l.jsxs(l.Fragment,{children:[l.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),l.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>l.jsxs("div",{className:"undo-row",children:[l.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&l.jsx("span",{className:"undo-after",children:"changed after this run"}),l.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&l.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&l.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&l.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&o){const Le=o.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:o.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&o&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!o||Le.id!==o.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,o,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?o?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?o?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!o&&t.upload.enabled&&Fn(o.perm,"write"),Io=b.useCallback(ie=>!!o&&Fn(Ut(ie?ie+"/":"")??o.perm,"write"),[o,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,o?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,o?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&o&&Fn(o.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&o?ie=>re(ie):void 0,insights:i&&o?ie=>gt(cn("dashboard",o.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,o,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=l.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:o?cn("install",o.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=l.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:o?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,o?.id,Ne),onFilters:ie=>gt(cn("history",o?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?l.jsx(uN,{}):l.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=l.jsxs("div",{className:"notfound",children:[l.jsx("h1",{children:"Couldn't find that"}),l.jsxs("p",{children:[l.jsx("code",{children:M})," isn't in this project right now."]}),l.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),l.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=l.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!o,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=l.jsxs(l.Fragment,{children:[L&&l.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&l.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=l.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:o?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?l.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=l.jsx(Nq,{project:o,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=l.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"link"})}),l.jsxs("div",{className:"vb-text",children:[l.jsxs("b",{children:["Moved from ",le.from]}),l.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?l.jsxs(l.Fragment,{children:[l.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&l.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||o?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?o.name:null,Cc=l.jsx(ci,{nav:t.desktop?l.jsxs("span",{id:"nav-btns",children:[l.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:l.jsx(ge,{name:"chevl"})}),l.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:l.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:l.jsxs(l.Fragment,{children:[l.jsx(jV,{people:x,path:M}),Vn&&l.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[l.jsx(ge,{name:"comment"})," ",l.jsx("span",{className:"lbl",children:"Comments"}),z>0&&l.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&l.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[l.jsx(ge,{name:"hist"})," ",l.jsx("span",{className:"lbl",children:"History"})]}),An&&l.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,o?.id,L,r.full,!0));return}const ie=Ln(M,o?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&l.jsx(ge,{name:"pencil"})," ",l.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&l.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&l.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[l.jsx(ge,{name:"link"})," ",l.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&l.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:l.jsx(ge,{name:"expand"})}),Kr&&l.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&l.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&l.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:l.jsx(ge,{name:"dots"})}),Te&&l.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&l.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&l.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&l.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&l.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&l.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!o&&l.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",o?.id,M))},children:"Insights"})]})]})});return l.jsxs(l.Fragment,{children:[l.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:l.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,l.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:l.jsxs(l.Fragment,{children:[!i&&l.jsx(F2,{}),Sc.trim()?l.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):l.jsxs(l.Fragment,{children:[rn&&l.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&l.jsxs("div",{className:"sb-section files-head",children:[l.jsx("span",{children:"Files"}),l.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:l.jsx(ge,{name:"sort"})}),Fa&&l.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:l.jsx(ge,{name:"fileplus"})})]}),l.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?l.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[l.jsx(ge,{name:"shrink"}),l.jsx("span",{className:"lbl",children:"Exit"}),l.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:l.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&l.jsx(b7,{shares:En,canRevoke:!!o&&Fn(o.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&l.jsx(SB,{width:rt,onChange:kt})]})}),je&&o&&l.jsx(x7,{project:o,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,o.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&l.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(o?.perm,"admin")}),l.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?l.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return l.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=l.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?l.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return l.jsx(ri,{to:"/setup"});if(!M)return l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=o?.kind==="hub"?{crumb:"Signup & access",body:l.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Organization not found"}),l.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:l.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?l.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Project not found"}),l.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?l.jsx(lU,{projects:g}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No agent access on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?l.jsx(GU,{url:e.billing.url}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No billing on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:l.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:l.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return l.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return l.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:o?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return l.jsxs(l.Fragment,{children:[l.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:l.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-mark",children:l.jsx(Sv,{size:20})}),l.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:l.jsx(PU,{pid:M.id,menu:P}),orgBar:l.jsxs(l.Fragment,{children:[l.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!o&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),l.jsx(li,{vault:l.jsx(mf,{name:"BearDrive",beta:!0}),topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?l.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):l.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:l.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return l.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?l.jsx(kB,{config:e}):l.jsx(MB,{config:e}):l.jsx(li,{vault:l.jsx(mf,{name:"…",showSignout:!1}),topbar:l.jsx(ci,{}),children:l.jsx("div",{className:"empty",children:"Loading…"})}),l.jsx(VL,{}),l.jsx(ZL,{}),l.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},o=e.path;if(!o||e.view||e.version||e.editing||!t(o))return[...r,i];const u=encodeURIComponent(o);return[...r,{queryKey:["render",n,o,""],url:n+"render?path="+u},i,{queryKey:["comments",n,o],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?l.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[l.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),l.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),l.jsx("p",{className:"mb-4",children:l.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),l.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(l.jsx(b.StrictMode,{children:l.jsx(LB,{children:l.jsx(NM,{client:$N,children:l.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,l as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-DXV-dXg-.js b/internal/webapp/static/assets/sharedfile-DXV-dXg-.js deleted file mode 100644 index 9dc115ef..00000000 --- a/internal/webapp/static/assets/sharedfile-DXV-dXg-.js +++ /dev/null @@ -1,16 +0,0 @@ -import{H as at,h as un,i as Rt,k as $o,f as wr,e as mr,l as fn,m as Fo}from"./index-BD48v6-0.js";const Q=()=>new Map,ds=e=>{const t=Q();return e.forEach((n,s)=>{t.set(s,n)}),t},wt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Bo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Vo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Nt=()=>new Set,Zn=e=>e[e.length-1],jo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Dt((this._observers.get(t)||Q()).values()).forEach(s=>s(...n))}destroy(){this._observers=Q()}}class Jo{constructor(){this._observers=Q()}on(t,n){wt(this._observers,t,Nt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Dt((this._observers.get(t)||Q()).values()).forEach(s=>s(...n))}destroy(){this._observers=Q()}}const lt=Math.floor,mn=Math.abs,Ls=(e,t)=>ee>t?e:t,Po=Math.pow,Kr=e=>e!==0?e<0:1/e<0,yr=1,kr=2,ts=4,es=8,Be=32,Ct=64,tt=128,Mn=31,gs=63,Gt=127,Wo=2147483647,bn=Number.MAX_SAFE_INTEGER,Sr=Number.MIN_SAFE_INTEGER,Yo=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&<(e)===e),Qr=String.fromCharCode,zo=e=>e.toLowerCase(),Go=/^\s*/g,qo=e=>e.replace(Go,""),Xo=/([A-Z])/g,br=(e,t)=>qo(e.replace(Xo,n=>`${t}${zo(n)}`)),Ko=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rVe.encode(e),Zo=Ve?Qo:Ko;let $e=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});$e&&$e.decode(new Uint8Array).length===1&&($e=null);const tl=(e,t)=>Ho(t,()=>e).join("");class qe{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const z=()=>new qe,Os=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Os(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ps=J,b=(e,t)=>{for(;t>Gt;)J(e,tt|Gt&t),t=lt(t/128);J(e,Gt&t)},Rs=(e,t)=>{const n=Kr(t);for(n&&(t=-t),J(e,(t>gs?tt:0)|(n?Ct:0)|gs&t),t=lt(t/64);t>0;)J(e,(t>Gt?tt:0)|Gt&t),t=lt(t/128)},ws=new Uint8Array(3e4),nl=ws.length/3,sl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;b(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ls(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(te(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},N=(e,t)=>{b(e,t.byteLength),vn(e,t)},Us=(e,t)=>{el(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},il=(e,t)=>Us(e,4).setFloat32(0,t,!1),ol=(e,t)=>Us(e,8).setFloat64(0,t,!1),ll=(e,t)=>Us(e,8).setBigInt64(0,t,!1),_r=new DataView(new ArrayBuffer(4)),cl=e=>(_r.setFloat32(0,e),_r.getFloat32(0)===e),je=(e,t)=>{switch(typeof t){case"string":J(e,119),qt(e,t);break;case"number":Yo(t)&&mn(t)<=Wo?(J(e,125),Rs(e,t)):cl(t)?(J(e,124),il(e,t)):(J(e,123),ol(e,t));break;case"bigint":J(e,122),ll(e,t);break;case"object":if(t===null)J(e,126);else if(me(t)){J(e,117),b(e,t.length);for(let n=0;n0&&b(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Cr=e=>{e.count>0&&(Rs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&b(e.encoder,e.count-2))};class yn{constructor(){this.encoder=new qe,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Cr(this),this.count=1,this.s=t)}toUint8Array(){return Cr(this),v(this.encoder)}}const Dr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Rs(e.encoder,t),e.count>1&&b(e.encoder,e.count-2)}};class ns{constructor(){this.encoder=new qe,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Dr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Dr(this),v(this.encoder)}}class al{constructor(){this.sarr=[],this.s="",this.lensE=new yn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new qe;return this.sarr.push(this.s),this.s="",qt(t,this.sarr.join("")),vn(t,this.lensE.toUint8Array()),v(t)}}const dt=e=>new Error(e),ot=()=>{throw dt("Method unimplemented")},et=()=>{throw dt("Unexpected case")},Zr=dt("Unexpected end of array"),ti=dt("Integer out of Range");class Nn{constructor(t){this.arr=t,this.pos=0}}const Bt=e=>new Nn(e),hl=e=>e.pos!==e.arr.length,ul=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Y=e=>ul(e,_(e)),ye=e=>e.arr[e.pos++],_=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posbn)throw ti}throw Zr},Ms=e=>{let t=e.arr[e.pos++],n=t&gs,s=64;const r=(t&Ct)>0?-1:1;if((t&tt)===0)return r*n;const i=e.arr.length;for(;e.posbn)throw ti}throw Zr},fl=e=>{let t=_(e);if(t===0)return"";{let n=String.fromCodePoint(ye(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ye(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},dl=e=>$e.decode(Y(e)),vt=$e?dl:fl,vs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},gl=e=>vs(e,4).getFloat32(0,!1),pl=e=>vs(e,8).getFloat64(0,!1),wl=e=>vs(e,8).getBigInt64(0,!1),ml=[e=>{},e=>null,Ms,gl,pl,wl,e=>!1,e=>!0,vt,e=>{const t=_(e),n={};for(let s=0;s{const t=_(e),n=[];for(let s=0;sml[127-ye(e)](e);class Ar extends Nn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hl(this)?this.count=_(this)+1:this.count=-1),this.count--,this.s}}class kn extends Nn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ms(this);const t=Kr(this.s);this.count=1,t&&(this.s=-this.s,this.count=_(this)+2)}return this.count--,this.s}}class ss extends Nn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Ms(this),n=t&1;this.diff=lt(t/2),this.count=1,n&&(this.count=_(this)+2)}return this.s+=this.diff,this.count--,this.s}}class yl{constructor(t){this.decoder=new kn(t),this.str=vt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const kl=crypto.getRandomValues.bind(crypto),ei=()=>kl(new Uint32Array(1))[0],Sl="10000000-1000-4000-8000"+-1e11,bl=()=>Sl.replace(/[018]/g,e=>(e^ei()&15>>e/4).toString(16)),$t=Date.now,Ir=e=>new Promise(e);Promise.all.bind(Promise);const Tr=e=>e===void 0?null:e;class _l{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let ni=new _l,Ns=!0;try{typeof localStorage<"u"&&localStorage&&(ni=localStorage,Ns=!1)}catch{}const si=ni,El=e=>Ns||addEventListener("storage",e),Cl=e=>Ns||removeEventListener("storage",e),Je=Symbol("Equality"),ri=(e,t)=>e===t||!!e?.[Je]?.(t)||!1,Dl=e=>typeof e=="object",Al=Object.assign,Il=Object.keys,Tl=(e,t)=>{for(const n in e)t(e[n],n)},xl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},_n=e=>Il(e).length,Ll=e=>{for(const t in e)return!1;return!0},Xe=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},$s=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ol=(e,t)=>e===t||_n(e)===_n(t)&&Xe(e,(n,s)=>(n!==void 0||$s(t,s))&&ri(t[s],n)),Rl=Object.freeze,ii=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&ii(e[t])}return Rl(e)},Fs=(e,t,n=0)=>{try{for(;ne,ue=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Je]!=null)return e[Je](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var oi={};const Ft=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",li=typeof window<"u"&&typeof document<"u"&&!Ft;let ht;const vl=()=>{if(ht===void 0)if(Ft){ht=Q();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");ht.set(`--${br(t,"-")}`,n),ht.set(`-${br(t,"-")}`,n)}})):ht=Q();return ht},ms=e=>vl().has(e),En=e=>Tr(Ft?oi[e.toUpperCase().replaceAll("-","_")]:si.getItem(e)),ci=e=>ms("--"+e)||En(e)!==null,Nl=ci("production"),$l=Ft&&Ml(oi.FORCE_COLOR,["true","1","2"]),Fl=$l||!ms("--no-colors")&&!ci("no-color")&&(!Ft||process.stdout.isTTY)&&(!Ft||ms("--color")||En("COLORTERM")!==null||(En("TERM")||"").includes("color")),ai=e=>new Uint8Array(e),Bl=(e,t,n)=>new Uint8Array(e,t,n),Vl=e=>new Uint8Array(e),jl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Jl=e=>{const t=atob(e),n=ai(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Bl(t.buffer,t.byteOffset,t.byteLength)},Wl=li?jl:Hl,Yl=li?Jl:Pl,zl=e=>{const t=ai(e.byteLength);return t.set(e),t};class Gl{constructor(t,n){this.left=t,this.right=n}}const Et=(e,t)=>new Gl(e,t),ql=(e,t)=>e.forEach(n=>t(n.left,n.right)),xr=e=>e.next()>=.5,rs=(e,t,n)=>lt(e.next()*(n+1-t)+t),hi=(e,t,n)=>lt(e.next()*(n+1-t)+t),Bs=(e,t,n)=>hi(e,t,n),Xl=e=>Qr(Bs(e,97,122)),Kl=(e,t=0,n=20)=>{const s=Bs(e,t,n);let r="";for(let i=0;it[Bs(e,0,t.length-1)],Ql=Symbol("0schema");class Zl{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(tl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const ys=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Je]?ri(e,t):me(e)?Is(e,n=>Ts(t,s=>ys(n,s))):Dl(e)?Xe(e,(n,s)=>ys(n,t[s])):!1;class q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),ys(n,s)}equals(t){return this.constructor===t.constructor&&ue(this.shape,t.shape)}[Ql](){return!0}[Je](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ot()}get nullable(){return Ae(this,jn)}get optional(){return new di(this)}cast(t){return Lr(t,this),t}expect(t){return Lr(t,this),t}}class Vs extends q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const V=(e,t=null)=>new Vs(e,t);V(Vs);class js extends q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const W=e=>new js(e);V(js);class $n extends q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Fn=(...e)=>new $n(e),ui=V($n),tc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),fi=e=>{if(ke.check(e))return[tc(e)];if(ui.check(e))return e.shape.map(t=>t+"");if(_i.check(e))return["[+-]?\\d+.?\\d*"];if(Ei.check(e))return[".*"];if(Cn.check(e))return e.shape.map(fi).flat(1);et()};class ec extends q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(fi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}V(ec);const nc=Symbol("optional");class di extends q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[nc](){return!0}}const sc=V(di);class rc extends q{check(t,n){return n?.extend(null,"never",typeof t),!1}}V(rc);class Bn extends q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Bn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):Xe(this.shape,(s,r)=>{const i=this._isPartial&&!$s(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const ic=e=>new Bn(e),oc=V(Bn),lc=W(e=>e!=null&&(e.constructor===Object||e.constructor==null));class gi extends q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&Xe(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const pi=(e,t)=>new gi(e,t),cc=V(gi);class wi extends q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&Xe(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const ac=(...e)=>new wi(e);V(wi);class mi extends q{constructor(t){super(),this.shape=t.length===1?t[0]:new Hs(t)}check(t,n){const s=me(t)&&Is(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const yi=(...e)=>new mi(e),hc=V(mi),uc=W(e=>me(e));class ki extends q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const fc=(e,t=null)=>new ki(e,t);V(ki);const dc=fc(q);class gc extends q{constructor(t){super(),this.len=t.length-1,this.args=ac(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const pc=V(gc),wc=W(e=>typeof e=="function");class mc extends q{constructor(t){super(),this.shape=t}check(t,n){const s=Is(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}V(mc,e=>e.shape.length>0);class Hs extends q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ts(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ae=(...e)=>e.findIndex(t=>Cn.check(t))>=0?Ae(...e.map(t=>Pe(t)).map(t=>Cn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Hs(e),Cn=V(Hs),Si=()=>!0,Dn=W(Si),yc=V(js,e=>e.shape===Si),Js=W(e=>typeof e=="bigint"),kc=W(e=>e===Js),bi=W(e=>typeof e=="symbol");W(e=>e===bi);const fe=W(e=>typeof e=="number"),_i=W(e=>e===fe),ke=W(e=>typeof e=="string"),Ei=W(e=>e===ke),Vn=W(e=>typeof e=="boolean"),Sc=W(e=>e===Vn),Ci=Fn(void 0);V($n,e=>e.shape.length===1&&e.shape[0]===void 0);Fn(void 0);const jn=Fn(null),bc=V($n,e=>e.shape.length===1&&e.shape[0]===null);V(Uint8Array);V(Vs,e=>e.shape===Uint8Array);const _c=Ae(fe,ke,jn,Ci,Js,Vn,bi);(()=>{const e=yi(Dn),t=pi(ke,Dn),n=Ae(fe,ke,jn,Vn,e,t);return e.shape=n,t.shape.values=n,n})();const Pe=e=>{if(dc.check(e))return e;if(lc.check(e)){const t={};for(const n in e)t[n]=Pe(e[n]);return ic(t)}else{if(uc.check(e))return Ae(...e.map(Pe));if(_c.check(e))return Fn(e);if(wc.check(e))return V(e)}et()},Lr=Nl?()=>{}:(e,t)=>{const n=new Zl;if(!t.check(e,n))throw dt(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Ec{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Pe(t),h:n}),this}else(t){return this.if(Dn,t)}done(){return(t,n)=>{for(let s=0;snew Ec(e),Di=Cc(Dn).if(_i,(e,t)=>rs(t,Sr,bn)).if(Ei,(e,t)=>Kl(t)).if(Sc,(e,t)=>xr(t)).if(kc,(e,t)=>BigInt(rs(t,Sr,bn))).if(Cn,(e,t)=>ie(t,is(t,e.shape))).if(oc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(sc.check(r)){if(xr(t))continue;r=r.shape}n[s]=Di(r,t)}return n}).if(hc,(e,t)=>{const n=[],s=hi(t,0,42);for(let r=0;ris(t,e.shape)).if(bc,(e,t)=>null).if(pc,(e,t)=>{const n=ie(t,e.res);return()=>n}).if(yc,(e,t)=>ie(t,is(t,[fe,ke,jn,Ci,Js,Vn,yi(fe),pi(Ae("a","b","c"),fe)]))).if(cc,(e,t)=>{const n={},s=rs(t,0,3);for(let r=0;rDi(Pe(t),e),mt=typeof document<"u"?document:{},Dc=e=>mt.createElement(e),Ac=()=>mt.createDocumentFragment();W(e=>e.nodeType===vc);const Ic=e=>mt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Tc=(e,t)=>(ql(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),xc=e=>{const t=Ac();for(let n=0;n(Ai(e,xc(t)),e),Hh=(e,t=[],n=[])=>Lc(Tc(Dc(e),t),n);W(e=>e.nodeType===Rc);const Jh=Ic;W(e=>e.nodeType===Uc);const Oc=e=>Bo(e,(t,n)=>`${n}:${t};`).join(""),Ai=(e,t)=>e.appendChild(t),Rc=mt.ELEMENT_NODE,Uc=mt.TEXT_NODE;mt.CDATA_SECTION_NODE;mt.COMMENT_NODE;const Mc=mt.DOCUMENT_NODE;mt.DOCUMENT_TYPE_NODE;const vc=mt.DOCUMENT_FRAGMENT_NODE;W(e=>e.nodeType===Mc);const At=Symbol,Ii=At(),Ti=At(),Nc=At(),$c=At(),Fc=At(),xi=At(),Bc=At(),Ps=At(),Vc=At(),jc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=Q();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Li(e)),Ri.forEach(t=>t.print(e))},Oi=(...e)=>{console.warn(...Li(e)),e.unshift(Ps),Ri.forEach(t=>t.print(e))},Ri=Nt(),Ui=e=>({[Symbol.iterator](){return this},next:e}),Wc=(e,t)=>Ui(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),os=(e,t)=>Ui(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Hn{constructor(t,n){this.clock=t,this.len=n}}class Ie{constructor(){this.clients=new Map}}const Se=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=lt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Yc(n,t.clock)!==null},Ws=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Hn(r.clock,te(r.len,i.clock+i.len-r.clock)):(s{const t=new Ie;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{wt(e.clients,t,()=>[]).push(new Hn(n,s))},zc=()=>new Ie,Gc=e=>{const t=zc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Te=(e,t)=>{b(e.restEncoder,t.clients.size),Dt(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),b(e.restEncoder,n);const r=s.length;b(e.restEncoder,r);for(let i=0;i{const t=new Ie,n=_(e.restDecoder);for(let s=0;s0){const o=wt(t.clients,r,()=>[]);for(let l=0;l{const s=new Ie,r=_(e.restDecoder);for(let i=0;i0){const i=new Kt;return b(i.restEncoder,0),Te(i,s),i.toUint8Array()}return null},Mi=ei;class ee extends xs{constructor({guid:t=bl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Mi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new zi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ir(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Ir(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&R(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Dt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return R(this,t,n)}get(t,n=P){const s=wt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==P&&r!==n)if(r===P){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,pe)}getText(t=""){return this.get(t,Ee)}getMap(t=""){return this.get(t,_e)}getXmlElement(t=""){return this.get(t,Ce)}getXmlFragment(t=""){return this.get(t,Qt)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Dt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ee({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,R(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class vi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return _(this.restDecoder)}readDsLen(){return _(this.restDecoder)}}class Ni extends vi{readLeftID(){return C(_(this.restDecoder),_(this.restDecoder))}readRightID(){return C(_(this.restDecoder),_(this.restDecoder))}readClient(){return _(this.restDecoder)}readInfo(){return ye(this.restDecoder)}readString(){return vt(this.restDecoder)}readParentInfo(){return _(this.restDecoder)===1}readTypeRef(){return _(this.restDecoder)}readLen(){return _(this.restDecoder)}readAny(){return He(this.restDecoder)}readBuf(){return zl(Y(this.restDecoder))}readJSON(){return JSON.parse(vt(this.restDecoder))}readKey(){return vt(this.restDecoder)}}class qc{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=_(this.restDecoder),this.dsCurrVal}readDsLen(){const t=_(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class be extends qc{constructor(t){super(t),this.keys=[],_(t),this.keyClockDecoder=new ss(Y(t)),this.clientDecoder=new kn(Y(t)),this.leftClockDecoder=new ss(Y(t)),this.rightClockDecoder=new ss(Y(t)),this.infoDecoder=new Ar(Y(t),ye),this.stringDecoder=new yl(Y(t)),this.parentInfoDecoder=new Ar(Y(t),ye),this.typeRefDecoder=new kn(Y(t)),this.lenDecoder=new kn(Y(t))}readLeftID(){return new de(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new de(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return He(this.restDecoder)}readBuf(){return Y(this.restDecoder)}readJSON(){return He(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=te(s,t[0].id.clock);const r=gt(t,s);b(e.restEncoder,t.length-r),e.writeClient(n),b(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{$(t,i)>r&&s.set(i,r)}),Jn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),b(e.restEncoder,s.size),Dt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{Xc(e,t.clients.get(r),r,i)})},Kc=(e,t)=>{const n=Q(),s=_(e.restDecoder);for(let r=0;r{const s=[];let r=Dt(n.keys()).sort((d,g)=>d-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new zi,c=new Map,a=(d,g)=>{const m=c.get(d);(m==null||m>g)&&c.set(d,g)};let u=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const g=d.id.client,m=n.get(g);m?(m.i--,l.clients.set(g,m.refs.slice(m.i)),n.delete(g),m.i=0,m.refs=[]):l.clients.set(g,[d]),r=r.filter(S=>S!==g)}s.length=0};for(;;){if(u.constructor!==rt){const g=wt(h,u.id.client,()=>$(t,u.id.client))-u.id.clock;if(g<0)s.push(u),a(u.id.client,u.id.clock-1),f();else{const m=u.getMissing(e,t);if(m!==null){s.push(u);const S=n.get(m)||{refs:[],i:0};if(S.refs.length===S.i)a(m,$(t,m)),f();else{u=S.refs[S.i++];continue}}else(g===0||g0)u=s.pop();else if(o!==null&&o.i0){const d=new Kt;return zs(d,l,new Map),b(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},Zc=(e,t)=>zs(e,t.doc.store,t.beforeState),ta=(e,t,n,s=new be(e))=>R(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=Kc(s,o),a=Qc(r,l,c),u=l.pendingStructs;if(u){for(const[f,d]of u.missing)if(d<$(l,f)){i=!0;break}if(a){for(const[f,d]of a.missing){const g=u.missing.get(f);(g==null||g>d)&&u.missing.set(f,d)}u.update=In([u.update,a.update])}}else l.pendingStructs=a;const h=Or(s,r,l);if(l.pendingDs){const f=new be(Bt(l.pendingDs));_(f.restDecoder);const d=Or(f,r,l);h&&d?l.pendingDs=In([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Bi(r.doc,f)}},n,!1),Bi=(e,t,n,s=be)=>{const r=Bt(t);ta(r,e,n,new s(r))},Vi=(e,t,n)=>Bi(e,t,n,Ni),ea=(e,t,n=new Map)=>{zs(e,t.store,n),Te(e,Gc(t.store))},na=(e,t=new Uint8Array([0]),n=new Kt)=>{const s=Hi(t);ea(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(_a(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Qe)return Sa(r.map((i,o)=>o===0?i:Ca(i)));if(n.constructor===Kt)return In(r)}return r[0]},ji=(e,t)=>na(e,t,new Qe),sa=e=>{const t=new Map,n=_(e.restDecoder);for(let s=0;ssa(new vi(Bt(e))),Ji=(e,t)=>(b(e.restEncoder,t.size),Dt(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{b(e.restEncoder,n),b(e.restEncoder,s)}),e),ra=(e,t)=>Ji(e,Jn(t.store)),ia=(e,t=new Fi)=>(e instanceof Map?Ji(t,e):ra(t,e),t.toUint8Array()),oa=e=>ia(e,new $i);class la{constructor(){this.l=[]}}const Rr=()=>new la,Ur=(e,t)=>e.l.push(t),Mr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Pi=(e,t,n)=>Fs(e.l,[t,n]);class de{constructor(t,n){this.client=t,this.clock=n}}const he=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new de(e,t),Wi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw et()},An=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Yi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Ph=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ca=e=>new Yi(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class aa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ha=(e,t,n=0)=>new aa(e,t,n),dn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Wi(e):s=C(e._item.id.client,e._item.id.clock),new Yi(s,r,t,n)},Wh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return dn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return dn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return dn(e,s.lastId,n);s=s.right}return dn(e,null,n)},ua=(e,t)=>{const n=ge(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},fa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if($(s,r.client)<=r.clock)return null;const u=n?Es(s,r):ua(s,r),h=u.item;if(!(h instanceof U))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(a+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if($(s,i.client)<=i.clock)return null;const{item:u}=n?Es(s,i):{item:ge(s,i)};if(u instanceof U&&u.content instanceof yt)c=u.content.type;else return null}else throw et();l>=0?a=c._length:a=0}return ha(c,a,e.assoc)},Yh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&he(e.item,t.item)&&he(e.type,t.type)&&e.assoc===t.assoc,ce=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Ke(t.ds,e.id),Ss=(e,t)=>{const n=wt(e.meta,Ss,Nt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r<$(s,i)&&K(e,C(i,r))}),Se(e,t.ds,r=>{}),n.add(t))};class zi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Jn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},$=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Gi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw et()}n.push(t)},gt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=lt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[gt(n,t.clock)]},ge=da,bs=(e,t,n)=>{const s=gt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[bs(e,n,t.clock)]},vr=(e,t,n)=>{const s=t.clients.get(n.client),r=gt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==st&&s.splice(r+1,0,Un(e,i,n.clock-i.id.clock+1)),i},ga=(e,t,n)=>{const s=e.clients.get(t.id.client);s[gt(s,t.id.clock)]=n},qi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=bs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Vo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ws(t.deleteSet),Zc(e,t),Te(e,t.deleteSet),!0),$r=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&wt(e.changed,t,Nt).add(n)},Sn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof U&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},wa=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=gt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ls(r.length-1,1+gt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+Sn(r,c)}})},Xi=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Pi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Fa(n)})}),Fs(l,[])}finally{s.gc&&wa(i,r,s.gcFilter),ma(i,r),n.afterState.forEach((u,h)=>{const f=n.beforeState.get(h)||0;if(f!==u){const d=r.clients.get(h),g=te(gt(d,f),1);for(let m=d.length-1;m>=g;)m-=1+Sn(d,m)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:f}=o[u].id,d=r.clients.get(h),g=gt(d,f);g+11||g>0&&Sn(d,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Pc(Ps,Ii,"[yjs] ",Ti,xi,"Changed the client-id because another client seems to be using it."),s.clientID=Mi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new Qe;Nr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new Kt;Nr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):Xi(e,t+1)}}},R=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new pa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&Xi(r,0)}}return o};class ya{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Fr=(e,t,n)=>{Se(e,n.deletions,s=>{s instanceof U&&t.scope.some(r=>r===e.doc||An(r,s))&&er(s,!1)})},Br=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;R(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let f=!1;Se(l,a.insertions,d=>{if(d instanceof U){if(d.redone!==null){let{item:g,diff:m}=Es(c,d.id);m>0&&(g=K(l,C(g.id.client,g.id.clock+m))),d=g}!d.deleted&&i.some(g=>g===l.doc||An(g,d))&&h.push(d)}}),Se(l,a.deletions,d=>{d instanceof U&&i.some(g=>g===l.doc||An(g,d))&&!Ke(a.insertions,d.id)&&u.add(d)}),u.forEach(d=>{f=po(l,d,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const g=h[d];e.deleteFilter(g)&&(g.delete(l),f=!0)}e.currStackItem=f?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class zh extends xs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=me(t)?t[0].doc:t instanceof ee?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const f=new Ie;c.afterState.forEach((S,w)=>{const D=c.beforeState.get(w)||0,I=S-D;I>0&&We(f,w,D,I)});const d=$t();let g=!1;if(this.lastChange>0&&d-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=ks([S.deletions,c.deleteSet]),S.insertions=ks([S.insertions,f])}else h.push(new ya(c.deleteSet,f)),g=!0;!a&&!u&&(this.lastChange=d),Se(c,c.deleteSet,S=>{S instanceof U&&this.scope.some(w=>w===c.doc||An(w,S))&&er(S,!0)});const m=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",m):this.emit("stack-item-updated",m)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=me(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof P?s.doc!==this.doc:s!==this.doc)&&Oi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Fr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Fr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Br(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Br(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*ka(e){const t=_(e.restDecoder);for(let n=0;nIn(e,Ni,Qe),ba=(e,t)=>{if(e.constructor===st){const{client:n,clock:s}=e.id;return new st(C(n,s+t),e.length-t)}else if(e.constructor===rt){const{client:n,clock:s}=e.id;return new rt(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new U(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},In=(e,t=be,n=Kt)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Bt(u)));let r=s.map(u=>new Gs(u,!0)),i=null;const o=new n,l=new qs(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const g=f.curr.id.clock-d.curr.id.clock;return g===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===rt?1:-1:g}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let f=u.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=u.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Ut(l,i.struct,i.offset),i={struct:f,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===rt?i.struct.length-=g:f=ba(f,g)),i.struct.mergeWith(f)||(Ut(l,i.struct,i.offset),i={struct:f,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let f=u.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==rt;f=u.next())Ut(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Ut(l,i.struct,i.offset),i=null),Xs(l);const c=s.map(u=>Ys(u)),a=ks(c);return Te(o,a),o.toUint8Array()},_a=(e,t,n=be,s=Kt)=>{const r=Hi(t),i=new s,o=new qs(i),l=new n(Bt(e)),c=new Gs(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,f=r.get(h)||0;if(c.curr.constructor===rt){c.next();continue}if(u.id.clock+u.length>f)for(Ut(o,u,te(f-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Ut(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}Xs(o);const a=Ys(l);return Te(i,a),i.toUint8Array()},Ki=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=z(),e.written=0)},Ut=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ki(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Xs=e=>{Ki(e);const t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n{const r=new n(Bt(e)),i=new Gs(r,!1),o=new s,l=new qs(o);for(let a=i.curr;a!==null;a=i.next())Ut(l,t(a),0);Xs(l);const c=Ys(r);return Te(o,c),o.toUint8Array()},Ca=e=>Ea(e,Ul,be,Qe),Vr="You must not compute changes after the event-handler fired.";class Pn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Da(this.currentTarget,this.target))}deletes(t){return Ke(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw dt(Vr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=Zn(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=Zn(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=Zn(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw dt(Vr);const n=this.target,s=Nt(),r=Nt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Da=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},G=()=>{Oi("Invalid access: Add Yjs type to a document before reading data.")},Qi=80;let Ks=0;class Aa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Ks++}}const Ia=e=>{e.timestamp=Ks++},Zi=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ks++},Ta=(e,t,n)=>{if(e.length>=Qi){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>mn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&mn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=te(t,r.index+n))}},Yn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;wt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Pi(s._eH,n,t)};class P{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Rr(),this._dEH=Rr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ot()}clone(){throw ot()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Ur(this._eH,t)}observeDeep(t){Ur(this._dEH,t)}unobserve(t){Mr(this._eH,t)}unobserveDeep(t){Mr(this._dEH,t)}toJSON(){}}const to=(e,t,n)=>{e.doc??G(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},eo=e=>{e.doc??G();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??G();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return ze(e,(s,r)=>{n.push(t(s,r,e))}),n},xa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},so=(e,t)=>{e.doc??G();const n=Wn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Zt(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Ze(new Uint8Array(h))),r.integrate(e,0);break;case ee:r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new tn(h)),r.integrate(e,0);break;default:if(h instanceof P)r=new U(C(o,$(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new yt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ro=()=>dt("Length exceeded!"),io=(e,t,n,s)=>{if(n>t._length)throw ro();if(n===0)return t._searchMarker&&Ye(t._searchMarker,n,s.length),Tn(e,t,null,s);const r=n,i=Wn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Tn(e,t,r,n)},oo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Wn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw ro();t._searchMarker&&Ye(t._searchMarker,r,-i+s)},xn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},Qs=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new Zt([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Zt([s]);break;case Uint8Array:l=new Ze(s);break;case ee:l=new tn(s);break;default:if(s instanceof P)l=new yt(s);else throw new Error("Unexpected content type")}new U(C(o,$(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},Zs=(e,t)=>{e.doc??G();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},lo=e=>{const t={};return e.doc??G(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},co=(e,t)=>{e.doc??G();const n=e._map.get(t);return n!==void 0&&!n.deleted},Oa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&ce(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},gn=e=>(e.doc??G(),Wc(e._map.entries(),t=>!t[1].deleted));class Ra extends Pn{}class pe extends P{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new pe;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new pe}clone(){const t=new pe;return t.insert(0,this.toArray().map(n=>n instanceof P?n.clone():n)),t}get length(){return this.doc??G(),this._length}_callObserver(t,n){super._callObserver(t,n),Yn(this,t,new Ra(this,t))}insert(t,n){this.doc!==null?R(this.doc,s=>{io(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?R(this.doc,n=>{La(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?R(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return so(this,t)}toArray(){return eo(this)}slice(t=0,n=this.length){return to(this,t,n)}toJSON(){return this.map(t=>t instanceof P?t.toJSON():t)}map(t){return no(this,t)}forEach(t){ze(this,t)}[Symbol.iterator](){return xa(this)}_write(t){t.writeTypeRef(sh)}}const Ua=e=>new pe;class Ma extends Pn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class _e extends P{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new _e}clone(){const t=new _e;return this.forEach((n,s)=>{t.set(s,n instanceof P?n.clone():n)}),t}_callObserver(t,n){Yn(this,t,new Ma(this,t,n))}toJSON(){this.doc??G();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof P?r.toJSON():r}}),t}get size(){return[...gn(this)].length}keys(){return os(gn(this),t=>t[0])}values(){return os(gn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return os(gn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??G(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return Zs(this,t)}has(t){return co(this,t)}clear(){this.doc!==null?R(this.doc,t=>{this.forEach(function(n,s,r){xn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(rh)}}const va=e=>new _e,Mt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Ol(e,t);class _s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&et(),this.right.content.constructor===j?this.right.deleted||xe(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const jr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===j?t.right.deleted||xe(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Wn(t,n):null;if(i){const o=new _s(i.p.left,i.p,i.index,r);return jr(e,o,n-i.index)}else{const o=new _s(null,t._start,0,r);return jr(e,o,n)}},ao=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===j&&Mt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new U(C(i,$(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new j(l,o));u.integrate(e,0),n.right=u,n.forward()})},xe=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},ho=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===j&&Mt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},uo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Mt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new U(C(i,$(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new j(l,c)),n.right.integrate(e,0),n.forward()}}return o},ls=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;ho(n,r);const l=uo(e,t,n,r),c=s.constructor===String?new pt(s):s instanceof P?new yt(s):new ne(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ye(t._searchMarker,n.index,c.getLength()),u=new U(C(o,$(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),ao(e,t,n,l)},Hr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;ho(n,r);const l=uo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===j));){if(!n.right.deleted)switch(n.right.content.constructor){case j:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Mt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new U(C(o,$(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new pt(c)),n.right.integrate(e,0),n.forward()}ao(e,t,n,l)},fo=(e,t,n,s,r)=>{let i=t;const o=Q();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===j){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===j){const{key:u,value:h}=a,f=s.get(u)??null;(o.get(u)!==a||f===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&f!==h&&(f===null?r.delete(u):r.set(u,f))),!c&&!t.deleted&&xe(r,a)}}t=t.right}return l},Na=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===j){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},$a=e=>{let t=0;return R(e.doc,n=>{let s=e._start,r=e._start,i=Q();const o=ds(i);for(;r;)r.deleted===!1&&(r.content.constructor===j?xe(o,r.content):(t+=fo(n,s,r,i,o),i=ds(o),s=r)),r=r.right}),t},Fa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&qi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===j&&o.constructor!==st&&t.add(o.parent)})}R(n,s=>{Se(e,e.deleteSet,r=>{if(r instanceof st||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===j?t.add(i):Na(s,r)});for(const r of t)$a(r)})},Jr=(e,t,n)=>{const s=n,r=ds(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case yt:case ne:case pt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];R(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(d={insert:a},r.size>0&&(d.attributes={},r.forEach((g,m)=>{g!==null&&(d.attributes[m]=g)}))),a="";break;case"retain":u>0&&(d={retain:u},Ll(c)||(d.attributes=Al({},c))),u=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case yt:case ne:this.adds(o)?this.deletes(o)||(f(),l="insert",a=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=1);break;case pt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=o.length);break;case j:{const{key:d,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=r.get(d)??null;Mt(m,g)?g!==null&&o.delete(s):(l==="retain"&&f(),Mt(g,i.get(d)??null)?delete c[d]:c[d]=g)}}else if(this.deletes(o)){i.set(d,g);const m=r.get(d)??null;Mt(m,g)||(l==="retain"&&f(),c[d]=m)}else if(!o.deleted){i.set(d,g);const m=c[d];m!==void 0&&(Mt(m,g)?m!==null&&o.delete(s):(l==="retain"&&f(),g===null?delete c[d]:c[d]=g))}o.deleted||(l==="insert"&&f(),xe(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ee extends P{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??G(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ee}clone(){const t=new Ee;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Ba(this,t,n);Yn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??G();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===pt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?R(this.doc,s=>{const r=new _s(null,this._start,0,new Map);for(let i=0;i0)&&ls(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Hr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Jr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??G();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let f=!1;i.forEach((g,m)=>{f=!0,h[m]=g});const d={insert:l};f&&(d.attributes=h),r.push(d),l=""}}const u=()=>{for(;c!==null;){if(ce(c,t)||n!==void 0&&ce(c,n))switch(c.content.constructor){case pt:{const h=i.get("ychange");t!==void 0&&!ce(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!ce(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case yt:case ne:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const f={};h.attributes=f,i.forEach((d,g)=>{f[g]=d})}r.push(h);break}case j:ce(c,t)&&(a(),xe(i,c.content));break}c=c.right}a()};return t||n?R(o,h=>{t&&Ss(h,t),n&&Ss(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ls(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!s);ls(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?R(s,r=>{Jr(r,pn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?R(r,i=>{const o=pn(i,this,t,!1);o.right!==null&&Hr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return Zs(this,t)}getAttributes(){return lo(this)}_write(t){t.writeTypeRef(ih)}}const Va=e=>new Ee;class cs{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??G()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Ce||n.constructor===Qt)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Qt extends P{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Qt}clone(){const t=new Qt;return t.insert(0,this.toArray().map(n=>n instanceof P?n.clone():n)),t}get length(){return this.doc??G(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new cs(this,t)}querySelector(t){t=t.toUpperCase();const s=new cs(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Dt(new cs(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Yn(this,t,new Ja(this,n,t))}toString(){return no(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),ze(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?R(this.doc,s=>{io(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)R(this.doc,s=>{const r=t&&t instanceof P?t._item:t;Tn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw dt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?R(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return eo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return so(this,t)}slice(t=0,n=this.length){return to(this,t,n)}forEach(t){ze(this,t)}_write(t){t.writeTypeRef(lh)}}const ja=e=>new Qt;class Ce extends Qt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Ce(this.nodeName)}clone(){const t=new Ce(this.nodeName),n=this.getAttributes();return Tl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof P?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?R(this.doc,n=>{xn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?R(this.doc,s=>{Qs(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return Zs(this,t)}hasAttribute(t){return co(this,t)}getAttributes(t){return t?Oa(this,t):lo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return ze(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(oh),t.writeKey(this.nodeName)}}const Ha=e=>new Ce(e.readKey());class Ja extends Pn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Ln extends _e{constructor(t){super(),this.hookName=t}_copy(){return new Ln(this.hookName)}clone(){const t=new Ln(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(ch),t.writeKey(this.hookName)}}const Pa=e=>new Ln(e.readKey());class On extends Ee{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new On}clone(){const t=new On;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(ah)}}const Wa=e=>new On;class tr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ot()}mergeWith(t){return!1}write(t,n,s){throw ot()}integrate(t,n){throw ot()}}const Ya=0;class st extends tr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Gi(t.doc.store,this)}write(t,n){t.writeInfo(Ya),t.writeLen(this.length-n)}getMissing(t,n){return null}}class Ze{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ze(this.content)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const za=e=>new Ze(e.readBuf());class Ge{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ge(this.len)}splice(t){const n=new Ge(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){We(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Ga=e=>new Ge(e.readLen()),go=(e,t)=>new ee({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class tn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new tn(go(this.doc.guid,this.opts))}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const qa=e=>new tn(go(e.readString(),e.readAny()));class ne{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ne(this.embed)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Xa=e=>new ne(e.readJSON());class j{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new j(this.key,this.value)}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Ka=e=>new j(e.readKey(),e.readJSON());class Rn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Rn(this.arr)}splice(t){const n=new Rn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const eh=e=>new pt(e.readString()),nh=[Ua,va,Va,Ha,ja,Pa,Wa],sh=0,rh=1,ih=2,oh=3,lh=4,ch=5,ah=6;class yt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new yt(this.type._copy())}splice(t){throw ot()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const hh=e=>new yt(nh[e.readTypeRef()](e)),Es=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ge(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof U);return{item:r,diff:s}},er=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Un=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new U(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Pr=(e,t)=>Ts(e,n=>Ke(n.deletions,t)),po=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return K(e,a);let u=t.parent._item,h=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||po(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=K(e,u.redone)}const d=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,f=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:K(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:K(e,w.redone);if(w!==null&&w.parent._item===u){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||Ke(s,h.right.id)||Pr(i.undoStack,h.right.id)||Pr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=K(e,h.redone);if(h&&h.right!==null)return null}else h=d._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=d._map.get(t.parentSub)||null)}const g=$(l,c),m=C(c,g),S=new U(m,h,h&&h.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=m,er(S,!0),S.integrate(e,0),S};class U extends tr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?kr:0}set marker(t){(this.info&es)>0!==t&&(this.info^=es)}get marker(){return(this.info&es)>0}get keep(){return(this.info&yr)>0}set keep(t){this.keep!==t&&(this.info^=yr)}get countable(){return(this.info&kr)>0}get deleted(){return(this.info&ts)>0}set deleted(t){this.deleted!==t&&(this.info^=ts)}markDeleted(){this.info|=ts}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=$(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=$(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===de&&this.id.client!==this.parent.client&&this.parent.clock>=$(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=vr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=K(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===st||this.right&&this.right.constructor===st)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===U?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===U&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===de){const s=ge(n,this.parent);s.constructor===st?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=vr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),he(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),We(t.deleteSet,this.id.client,this.id.clock,this.length),$r(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw et();this.content.gc(t),n?ga(t,this,new st(this.id,this.length)):this.content=new Ge(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Mn|(s===null?0:tt)|(r===null?0:Ct)|(i===null?0:Be);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Wi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===de?(t.writeParentInfo(!1),t.writeLeftID(l)):et();i!==null&&t.writeString(i)}this.content.write(t,n)}}const wo=(e,t)=>uh[t&Mn](e),uh=[()=>{et()},Ga,Qa,za,eh,Xa,Ka,hh,th,qa,()=>{et()}],fh=10;class rt extends tr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){et()}write(t,n){t.writeInfo(fh),b(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const mo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},yo="__ $YJS$ __";mo[yo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");mo[yo]=!0;const ko=new Map;class dh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Yl(n.newValue||"")}),El(this._onChange)}postMessage(t){si.setItem(this.room,Wl(Vl(t)))}close(){Cl(this._onChange)}}const gh=typeof BroadcastChannel>"u"?dh:BroadcastChannel,nr=e=>wt(ko,e,()=>{const t=Nt(),n=new gh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),ph=(e,t)=>(nr(e).subs.add(t),t),wh=(e,t)=>{const n=nr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),ko.delete(e)),s},ae=(e,t,n=null)=>{const s=nr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},So=0,sr=1,bo=2,Cs=(e,t)=>{b(e,So);const n=oa(t);N(e,n)},_o=(e,t,n)=>{b(e,sr),N(e,ji(t,n))},mh=(e,t,n)=>_o(t,n,Y(e)),Eo=(e,t,n,s)=>{try{Vi(t,Y(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},yh=(e,t)=>{b(e,bo),N(e,t)},kh=Eo,Sh=(e,t,n,s,r)=>{const i=_(e);switch(i){case So:mh(e,t,n);break;case sr:Eo(e,n,s,r);break;case bo:kh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},bh=0,_h=(e,t,n)=>{_(e)===bh&&n(t,vt(e))},as=3e4;class Co extends Jo{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=$t();this.getLocalState()!==null&&as/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&as<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&rr(this,s,"timeout")},lt(as/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:$t()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),ue(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const rr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Fe=(e,t,n=e.states)=>{const s=t.length,r=z();b(r,s);for(let i=0;i{const s=Bt(t),r=$t(),i=[],o=[],l=[],c=[],a=_(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Ch=e=>xl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),zt=0,Do=3,we=1,Dh=2,en=[];en[zt]=(e,t,n,s,r)=>{b(e,zt);const i=Sh(t,e,n.doc,n);s&&i===sr&&!n.synced&&(n.synced=!0)};en[Do]=(e,t,n,s,r)=>{b(e,we),N(e,Fe(n.awareness,Array.from(n.awareness.getStates().keys())))};en[we]=(e,t,n,s,r)=>{Eh(n.awareness,Y(t),n)};en[Dh]=(e,t,n,s,r)=>{_h(t,n.doc,(i,o)=>Ah(n,o))};const Wr=3e4,Ah=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),Ao=(e,t,n)=>{const s=Bt(t),r=z(),i=_(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Ih=e=>!(e.code>=4400&&e.code<4500),Ds=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,rr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Io,Ls(Po(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Io=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=$t();const s=Ao(e,new Uint8Array(n.data),!0);Os(s)>1&&t.send(v(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Ds(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=$t(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=z();if(b(n,zt),Cs(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){const s=z();b(s,we),N(s,Fe(e.awareness,[e.doc.clientID])),t.send(v(s))}},e.emit("status",[{status:"connecting"}])}},hs=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&ae(e.bcChannel,t,e)};class Th extends xs{constructor(t,n,s,{connect:r=!0,awareness:i=new Co(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:f=Ih}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=en.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=z();b(d,zt),Cs(d,s),this.ws.send(v(d))}},a)),this._bcSubscriber=(d,g)=>{if(g!==this){const m=Ao(this,new Uint8Array(d),!1);Os(m)>1&&ae(this.bcChannel,v(m),this)}},this._updateHandler=(d,g)=>{if(g!==this){const m=z();b(m,zt),yh(m,d),hs(this,v(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:g,removed:m},S)=>{const w=d.concat(g).concat(m),D=z();b(D,we),N(D,Fe(i,w)),hs(this,v(D))},this._exitHandler=()=>{rr(this.awareness,[s.clientID],"app closed")},Ft&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Wr<$t()-this.wsLastMessageReceived&&Ds(this,this.ws,null)},Wr/10),r&&this.connect()}get url(){const t=Ch(this.params);return this.serverUrl+"/"+this.roomname+(t.length===0?"":"?"+t)}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,t&&(this.wsUnsuccessfulReconnects=0),this.emit("synced",[t]),this.emit("sync",[t]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Ft&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(ph(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const t=z();b(t,zt),Cs(t,this.doc),ae(this.bcChannel,v(t),this);const n=z();b(n,zt),_o(n,this.doc),ae(this.bcChannel,v(n),this);const s=z();b(s,Do),ae(this.bcChannel,v(s),this);const r=z();b(r,we),N(r,Fe(this.awareness,[this.doc.clientID])),ae(this.bcChannel,v(r),this)}disconnectBc(){const t=z();b(t,we),N(t,Fe(this.awareness,[this.doc.clientID],new Map)),hs(this,v(t)),this.bcconnected&&(wh(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Ds(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Io(this),this.connectBc())}}const Yr=Symbol("collab-http-remote");class xh{constructor(t,n,s,r,i){this.url=t,this.onStatus=n,this.onReady=s,this.onStalled=r,this.me=i,this.text=this.doc.getText("body"),this.awareness=new Co(this.doc),this.me&&this.awareness.setLocalStateField("user",{name:this.me.name,color:this.me.colour,colorLight:this.me.colour.replace(/\)$/," / 0.2)")})}url;onStatus;onReady;onStalled;me;doc=new ee;text;awareness;ws=null;closed=!1;reached=!1;stallTimer=null;remoteCursors(){const t=[];return this.awareness.getStates().forEach((n,s)=>{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=fa(ca(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Th(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Lh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=ji(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Yr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,I=new Int32Array(2*w+1);for(let x=-w;x<=w;x+=2){let L;w===0?L=0:x===-w||x!==w&&D[x-1+w-1]=r&&O>=i){u=w;break}}a.push(I)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let f=r,d=i;for(let w=u;w>0;w--){const D=a[w-1],I=f-d,x=I===-w||I!==w&&D[I-1+w-1]Vt&&d>X;)f--,d--,h.push(f,d);f=L,d=O}for(;f>0&&d>0;)f--,d--,h.push(f,d);const g=[];let m=0,S=0;for(let w=h.length-2;w>=0;w-=2){const D=h[w],I=h[w+1];(D>m||I>S)&&g.push({aS:n+m,aE:n+D,bS:n+S,bE:n+I}),m=D+1,S=I+1}return(mi.startsWith(o)&&(o===""||o.endsWith(` -`)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?vh(e,t)<=0?e+t:t+e:null}function To(e,t,n,s){if(t===n)return t;if(t===e)return n;if(n===e)return t;const r=new Map,i=ut(e,s),o=ut(t,s),l=ut(n,s),c=ft(i,r),a=[...De(c,ft(o,r)).map(m=>({h:m,toks:o,side:0})),...De(c,ft(l,r)).map(m=>({h:m,toks:l,side:1}))];a.sort((m,S)=>m.h.aS-S.h.aS||m.h.aE-S.h.aE||m.side-S.side);const u=(m,S,w)=>m.slice(S,w).join(""),h=(m,S,w,D)=>{let I="",x=w;for(const L of m)L.side===S&&(I+=u(i,x,L.h.aS)+u(L.toks,L.h.bS,L.h.bE),x=L.h.aE);return I+u(i,x,D)};let f="",d=0,g=0;for(;gO.side)).size===1){f+=h(m,m[0].side,S,w);continue}const I=h(m,0,S,w),x=h(m,1,S,w);if(I===x){f+=I;continue}if(S===w){const O=Nh(I,x,s!==zr,i.length===0);if(O===null)return null;f+=O;continue}if(s===zr)return null;const L=To(u(i,S,w),I,x,s+1);if(L===null)return null;f+=L}return f+u(i,d,i.length)}const us=e=>e===""||e.endsWith(` -`)?e:e+` -`;function oe(e,t,n){const s=To(us(e),us(t),us(n),Xt);if(s===null)return{ok:!1};let r=t.endsWith(` -`);return r===e.endsWith(` -`)&&(r=n.endsWith(` -`)),s===""||r===s.endsWith(` -`)?{ok:!0,text:s}:{ok:!0,text:r?s+` -`:s.slice(0,-1)}}function Gr(e,t){if(e===t)return[];const n=[],s=new Map,r=ut(e,Xt),i=ut(t,Xt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?g.charCodeAt(w-1):0;I>=55296&&I<=56319&&w--;const x=D>0?g.charCodeAt(g.length-D):0;x>=56320&&x<=57343&&D--,S+=w,g=g.slice(w,g.length-D),m=m.slice(w,m.length-D),(g.length||m.length)&&s.push({index:S,deleteCount:g.length,insertText:m}),a=f,u=d}}function fs(e,t,n){const s=new Map,r=ft(ut(t,Xt),s),i=De(ft(ut(e,Xt),s),r),o=De(r,ft(ut(n,Xt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function wn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const qr=700,le=[2e3,4e3,8e3,15e3],Xr=2e3,Fh=4,Bh=32e3,Vh=32;function Gh(e){let t=e.seed,n=e.baseSha;const s=(p,k)=>{t=p,r=k,Ot(k);const y=It.lastIndexOf(p);y>=0?It.splice(0,y+1):It.length=0};let r=e.baseSha;const i=p=>{if(!p)return;const k=[];for(let y=p;y!==null&&k.length<4;y=y.prev)y.sent!==y.from&&!k.includes(y.sent)&&k.push(y.sent);return k.length?k:void 0},o=(p,k=kt)=>{const y=i(k);return r&&r===n&&t.length>Bh?{base:n,text:p,...y?{prior_sent:y}:{}}:{base:n,base_text:t,text:p,...y?{prior_sent:y}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,f=0,d=null,g=!1,m=!1,S=!1,w=null,D=null,I=0;const x=(p=Date.now())=>{const k=Math.max(p,I+1e3);return I=k,$o(e.path,e.who||"browser",new Date(k))},L=new Map;let O=0,Vt=!1,X=null,jt=0,zn=!1,kt=null,Ht=!1;const It=[],ir=p=>{It.at(-1)!==p&&(It.push(p),It.length>Vh&&It.shift())};let St=!1,Le=null,Jt=0;const Oe=()=>{St=!1,Le=null},Gn=p=>{Jt===p&&Oe()};let Z=0,it=0,nn=null,Pt=null,qn=!1,bt=null,Re=!1,Wt=null,nt=null;const M=p=>e.onState?.(p),sn=p=>e.apiBase+"upload/content?path="+encodeURIComponent(p),Tt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let rn=null,Xn=0;const Ue=()=>{clearTimeout(rn??void 0),rn=null},on=p=>{if(!(p instanceof at?p.status>=500||p.status===429:!0)||h||a)return;Ue();const y=le[Math.min(Xn,le.length-1)];Xn++,rn=setTimeout(()=>{rn=null,!h&&!a&&Me()},y)},or=()=>{Ue(),Xn=0},ln=()=>{Ue(),Wt&&clearTimeout(Wt),Wt=setTimeout(()=>{Me()},qr)},Yt=p=>{if(h)return d=p,!0;const k=F();if(k===p)return!0;const y=Gr(k,p);if(hr())return T.applySplices(y),!0;if(!e.soloApply)return!1;for(const A of y)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Me=()=>{if(a)return Promise.resolve();if(g)return m?Promise.resolve():Ne();if(Pt)return qn=!0,Pt;const p=(async()=>{try{await xo()}finally{Pt=null}})();return Pt=p,p},xo=async()=>{let p=0;for(;;){if(qn=!1,H||a||S)return;const k=F();if(k===t&&!Ht){M("clean");return}M("saving"),e.onWriting?.();const y=l||c?await Lo(k):await Ro(k);if(y==="stop")return;if(y==="rebased"){if(++p>Fh){await cn(F(),n??"");return}continue}if(!qn){M(F()===t&&!Ht?"clean":"dirty");return}}};let xt=!1;const Lo=async p=>{bt=p,Re=!1;let k;try{k=await un(sn(e.path),p,n,xt)}catch(y){return bt=null,y instanceof at&&y.status===422&&wn(y)?(xt=!1,ve(p),"stop"):y instanceof at&&y.status===409?await lr(t,!1)?"rebased":"stop":(M("error"),on(y),"stop")}return bt=null,xt=!1,or(),k.merged?await lr(p,!0)?"rebased":"stop":(Re||s(p,k.sha),e.onSaved?.(p),"done")},lr=async(p,k)=>{let y;try{y=await wr(mr(e.apiBase,e.path))}catch(B){return M("error"),F()!==t&&on(B),!1}if(y.kind!=="text")return M("error"),!1;const A=F(),E=oe(p,y.text,A);return!E.ok||!Yt(E.text)?(k&&s(y.text,y.sha),await cn(A,y.sha??""),!1):(s(y.text,y.sha),k&&e.onSaved?.(y.text),!0)},Oo=p=>{if(p.update&&T.applyRemoteUpdate(p.update),typeof p.text!="string"){kt=null;return}let k=null;for(let y=kt;y!==null;y=y.prev)if(y.sent!==y.from&&fs(y.from,y.sent,p.text)){k=y;break}if(kt=null,k){Ht=!0;const y=oe(k.sent,p.text,F());y.ok&&Yt(y.text)?(t=p.text,r=void 0,Ot(p.sha)):(t=k.sent,r=void 0)}},Ro=async p=>{bt=p,Re=!1;let k;const y=kt;try{kt={sent:p,from:t,prev:y},k=await Rt(Tt,{...o(p,y),...xt?{confirm_shrink:!0}:{}})}catch(E){if(bt=null,E instanceof at&&[400,401,403,404,405,409,413].includes(E.status)&&(kt=y),E instanceof at&&(E.status===404||E.status===405))return c=!0,"rebased";if(E instanceof at&&E.status===422&&wn(E))return xt=!1,ve(p),"stop";if(E instanceof at&&E.status===409&&!a){let B={};try{B=JSON.parse(E.body)}catch{}const ct=typeof B.text=="string"?B.text:null;if(ct!==null){const pr=oe(t,ct,F());if(pr.ok&&Yt(pr.text))return t=ct,r=void 0,Ot(B.sha),"rebased"}Vt=!0;const re=F(),gr=await cn(re,B.sha??"");return h?"stop":gr?(on(gr.err),"stop"):(Vt=!1,F()!==re?"rebased":"stop")}return M(a?"dirty":"error"),on(E),"stop"}if(bt=null,xt=!1,or(),k.update&&T.applyRemoteUpdate(k.update),kt=null,Ht=!1,a)return"stop";const A=oe(p,k.text,F());return A.ok&&Yt(A.text)&&(Re||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let H=null;const ve=p=>{H||h||!e.onShrinkRefused||(M("error"),H={was:fn(t),now:fn(p),confirm:async()=>{if(!h){if(a){M("saving"),e.onWriting?.();const k=Z,y=Jt;try{const A=await Rt(Tt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),Kn(k,y);const E=!St&&it>=Z;M(E?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&it{if(!h)try{const k=await wr(mr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Yt(k.text),H=null,a&&!u){if(await se(!1),h)return;M(it>=Z&&!St?"clean":"dirty");return}it=Z,f&&(f=0,e.onPending?.(0)),Oe(),M("clean")}catch{M("error")}finally{H=null}}},e.onShrinkRefused(H))};let Lt=null;const Uo=()=>{Lt&&clearTimeout(Lt),Lt=setTimeout(()=>{const p=F();Fo(fn(t),fn(p))&&ve(p)},qr)},cn=async(p,k,y=x())=>{const A=++O;L.set(y,p);try{return await un(sn(y),p),A===O&&!a&&(t=p,r=void 0,k&&(n=k),M("clean")),e.onConflictCopy?.(y),null}catch(E){return A===O&&!a&&M("error"),{err:E}}finally{L.get(y)===p&&L.delete(y)}},Kn=(p,k)=>{it=Math.max(it,p),Gn(k),!(h||u)&&(f=Z-it,e.onPending?.(f))},Mo=()=>{h||u||H||nt||(nt=setTimeout(()=>{nt=null,!u&&!h&&se(!1)},Xr))},se=p=>{if(clearTimeout(nt??void 0),nt=null,p){if(it>=Z)return Promise.resolve();const y=Z,A=Jt;return Rt(Tt,{update:T.encodeState(),base:n},!0).then(E=>{Ot(E.sha),Kn(y,A)})}if(nn)return nn;const k=(async()=>{try{for(;!u&&!h&&!H&&it{g=!1,w=null,D=null,jt=0,clearTimeout(X??void 0),X=null,Ht=!1,a=!0,ir(T.text.toString()),p?.(),zn&&(zn=!1,e.onReady(T))},Ne=async()=>{if(h||a||m||S)return;if(clearTimeout(X??void 0),X=null,Wt&&clearTimeout(Wt),Wt=null,Pt){S=!0;try{for(;Pt;)await Pt}finally{S=!1}if(h||a)return;if(!u){F()!==t&&ln();return}}if(kt!==null&&!c){let ct;S=!0;try{ct=await Rt(Tt,{peek:!0})}catch{if(h||a)return;const re=le[Math.min(jt,le.length-1)];jt++,X=setTimeout(()=>{X=null,Ne()},re);return}finally{S=!1}if(h||a)return;if(Oo(ct),!u){(F()!==t||Ht)&&ln();return}}const p=e.soloText?.();if(p===void 0||p===t)return Qn();const k=T.text.toString(),y=oe(t,k,p);if(y.ok)return Qn(()=>T.applySplices(Gr(k,y.text)));g=!0,(w===null||D!==p)&&(w=x(),D=p),m=!0;let A;try{A=await cn(p,n??"",w)}finally{m=!1}if(h)return;if(!A)return e.soloText?.()!==p?(w=null,D=null,Ne()):Qn(()=>{t=T.text.toString()});const E=A.err;if(E instanceof at&&!(E.status>=500||E.status===429))return;const B=le[Math.min(jt,le.length-1)];jt++,X=setTimeout(()=>{X=null,Ne()},B)},T=new xh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),p=>{u=p==="live",p==="solo"&&(l=!0),u&&(nt&&clearTimeout(nt),nt=null,Ue(),a||Ne(),it=Z,f&&(f=0,e.onPending?.(0))),e.onCollab?.(p)},()=>{a?e.onReady(T):zn=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),cr=(p,k)=>{const y=a?T.text.toString():null;if(y!==null&&ir(y),!T.isRemote(k?.origin)){if(M("dirty"),a){St=!0,Le=y,Jt+=1,u||(Z+=1,f=Z-it,e.onPending?.(f),clearTimeout(nt??void 0),nt=setTimeout(()=>{nt=null,!u&&!h&&se(!1)},Xr)),Uo();return}ln()}};T.text.observe(cr);const ar=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",ar),Oh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const F=()=>d!==null?d:hr()?T.text.toString():e.soloText?.()??"",hr=()=>a||l&&T.text.length>0,Ot=p=>{p&&(n=p)},vo=(p,k,y)=>{if(y?.held)return s(p,k),"same";if(p===t||p===bt)return Ot(k),"same";const A=F();if(p===A)return s(p,k),a&&(Oe(),M("clean")),"same";if(a){const B=t;return It.includes(p)||fs(B,p,A)?(s(p,k),St&&(Le===null||p===Le||fs(B,Le,p))&&(Oe(),M("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(p,k),Yt(p),Oe(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const E=oe(t,p,A);return E.ok?(bt!==null&&(Re=!0),s(p,k),Yt(E.text),E.text!==p?ln():bt===null&&M("clean"),E.text===A?"same":"merged"):"blocked"};let an=null;const No=()=>{if(!a)return Me();if(H||h)return Promise.resolve();if(!u)return f>0?se(!1):Promise.resolve();if(!St)return Promise.resolve();if(an)return an;const p=Jt;M("saving");const k=(async()=>{try{const y=await Rt(Tt,{update:T.encodeState()});if(h)return;y.update&&T.applyRemoteUpdate(y.update),s(y.text,y.sha),Gn(p),M(St?"dirty":"clean"),e.onSaved?.(t)}catch(y){if(h||y instanceof at&&y.status===422&&wn(y)&&(clearTimeout(Lt??void 0),Lt=null,ve(F()),H))return;M(St?"dirty":"clean")}finally{an=null}})();return an=k,k};let _t=null;const hn=p=>()=>{_t===p&&(_t=null)},ur=(p,k)=>{if(H)return;if(a){const A=!u&&f>0;if(!A&&!(u&&St))return;const E="room\0"+T.text.toString();if(_t===E)return;_t=E;const B=Jt;(A?se(!0):Rt(Tt,{update:T.encodeState()},!0).then(re=>Ot(re.sha))).then(()=>Gn(B),hn(E));return}if(g||Vt){const A="park\0"+p;if(_t===A)return;_t=A;let E=w!==null&&D===p?w:null;for(const[B,ct]of L)E===null&&ct===p&&(E=B);E??=x(),un(sn(E),p,void 0,!1,!0).catch(hn(A));return}if(!p||p===t)return;const y="text\0"+p;if(_t!==y){if((l||c)&&!k){Me();return}_t=y,l||c?un(sn(e.path),p,n,xt,!0).catch(hn(y)):Rt(Tt,o(p),!0).catch(hn(y))}},fr=()=>{h||ur(F(),!0)},dr=()=>{_t=null};return typeof window<"u"&&(window.addEventListener("pagehide",fr),window.addEventListener("pageshow",dr)),{collab:T,current:F,merge:vo,rebase:Ot,saveNow:No,askingShrink:()=>H!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",fr),window.removeEventListener("pageshow",dr)),clearTimeout(Wt??void 0),clearTimeout(Lt??void 0),Ue(),clearTimeout(X??void 0),X=null;const p=F();h=!0,d=p,H?e.onShrinkWithdrawn?.(H):ur(p,!1),clearTimeout(nt??void 0),T.awareness.off("change",ar),T.text.unobserve(cr),T.destroy()}}}export{ee as D,qr as S,zh as U,Wh as a,ca as b,fa as c,Gr as d,Yh as e,Ls as f,te as g,Hh as h,Et as i,oe as m,Gh as o,Ph as r,Jh as t}; diff --git a/internal/webapp/static/assets/sharedfile-jBqmYsT3.js b/internal/webapp/static/assets/sharedfile-jBqmYsT3.js new file mode 100644 index 00000000..7a4b295b --- /dev/null +++ b/internal/webapp/static/assets/sharedfile-jBqmYsT3.js @@ -0,0 +1,16 @@ +import{H as ht,h as dn,i as Ut,k as Fo,f as yr,e as kr,l as gn,m as Bo}from"./index-BROkyUpj.js";const Z=()=>new Map,ws=e=>{const t=Z();return e.forEach((n,s)=>{t.set(s,n)}),t},mt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Vo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},jo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Ft=()=>new Set,ns=e=>e[e.length-1],Ho=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return At((this._observers.get(t)||Z()).values()).forEach(s=>s(...n))}destroy(){this._observers=Z()}}class Jo{constructor(){this._observers=Z()}on(t,n){mt(this._observers,t,Ft).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return At((this._observers.get(t)||Z()).values()).forEach(s=>s(...n))}destroy(){this._observers=Z()}}const ct=Math.floor,kn=Math.abs,Rs=(e,t)=>ee>t?e:t,Wo=Math.pow,Qr=e=>e!==0?e<0:1/e<0,Sr=1,br=2,ss=4,rs=8,je=32,Dt=64,et=128,Fn=31,ms=63,Xt=127,Yo=2147483647,En=Number.MAX_SAFE_INTEGER,_r=Number.MIN_SAFE_INTEGER,zo=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&ct(e)===e),Zr=String.fromCharCode,Go=e=>e.toLowerCase(),qo=/^\s*/g,Xo=e=>e.replace(qo,""),Ko=/([A-Z])/g,Er=(e,t)=>Xo(e.replace(Ko,n=>`${t}${Go(n)}`)),Qo=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rHe.encode(e),tl=He?Zo:Qo;let Be=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Be&&Be.decode(new Uint8Array).length===1&&(Be=null);const el=(e,t)=>Po(t,()=>e).join("");class Ke{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const G=()=>new Ke,Us=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Us(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ys=J,b=(e,t)=>{for(;t>Xt;)J(e,et|Xt&t),t=ct(t/128);J(e,Xt&t)},Ms=(e,t)=>{const n=Qr(t);for(n&&(t=-t),J(e,(t>ms?et:0)|(n?Dt:0)|ms&t),t=ct(t/64);t>0;)J(e,(t>Xt?et:0)|Xt&t),t=ct(t/128)},ks=new Uint8Array(3e4),sl=ks.length/3,rl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;b(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Rs(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ee(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},$=(e,t)=>{b(e,t.byteLength),Bn(e,t)},vs=(e,t)=>{nl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},ol=(e,t)=>vs(e,4).setFloat32(0,t,!1),ll=(e,t)=>vs(e,8).setFloat64(0,t,!1),cl=(e,t)=>vs(e,8).setBigInt64(0,t,!1),Cr=new DataView(new ArrayBuffer(4)),al=e=>(Cr.setFloat32(0,e),Cr.getFloat32(0)===e),Pe=(e,t)=>{switch(typeof t){case"string":J(e,119),Kt(e,t);break;case"number":zo(t)&&kn(t)<=Yo?(J(e,125),Ms(e,t)):al(t)?(J(e,124),ol(e,t)):(J(e,123),ll(e,t));break;case"bigint":J(e,122),cl(e,t);break;case"object":if(t===null)J(e,126);else if(ye(t)){J(e,117),b(e,t.length);for(let n=0;n0&&b(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Ar=e=>{e.count>0&&(Ms(e.encoder,e.count===1?e.s:-e.s),e.count>1&&b(e.encoder,e.count-2))};class Sn{constructor(){this.encoder=new Ke,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Ar(this),this.count=1,this.s=t)}toUint8Array(){return Ar(this),M(this.encoder)}}const Ir=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ms(e.encoder,t),e.count>1&&b(e.encoder,e.count-2)}};class is{constructor(){this.encoder=new Ke,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Ir(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Ir(this),M(this.encoder)}}class hl{constructor(){this.sarr=[],this.s="",this.lensE=new Sn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Ke;return this.sarr.push(this.s),this.s="",Kt(t,this.sarr.join("")),Bn(t,this.lensE.toUint8Array()),M(t)}}const gt=e=>new Error(e),lt=()=>{throw gt("Method unimplemented")},nt=()=>{throw gt("Unexpected case")},ti=gt("Unexpected end of array"),ei=gt("Integer out of Range");class Vn{constructor(t){this.arr=t,this.pos=0}}const jt=e=>new Vn(e),ul=e=>e.pos!==e.arr.length,fl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},z=e=>fl(e,E(e)),ke=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posEn)throw ei}throw ti},Ns=e=>{let t=e.arr[e.pos++],n=t&ms,s=64;const r=(t&Dt)>0?-1:1;if((t&et)===0)return r*n;const i=e.arr.length;for(;e.posEn)throw ei}throw ti},dl=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(ke(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ke(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},gl=e=>Be.decode(z(e)),Nt=Be?gl:dl,$s=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},pl=e=>$s(e,4).getFloat32(0,!1),wl=e=>$s(e,8).getFloat64(0,!1),ml=e=>$s(e,8).getBigInt64(0,!1),yl=[e=>{},e=>null,Ns,pl,wl,ml,e=>!1,e=>!0,Nt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;syl[127-ke(e)](e);class Tr extends Vn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),ul(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class bn extends Vn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ns(this);const t=Qr(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class os extends Vn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Ns(this),n=t&1;this.diff=ct(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class kl{constructor(t){this.decoder=new bn(t),this.str=Nt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Sl=crypto.getRandomValues.bind(crypto),ni=()=>Sl(new Uint32Array(1))[0],bl="10000000-1000-4000-8000"+-1e11,_l=()=>bl.replace(/[018]/g,e=>(e^ni()&15>>e/4).toString(16)),Bt=Date.now,xr=e=>new Promise(e);Promise.all.bind(Promise);const Lr=e=>e===void 0?null:e;class El{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let si=new El,Fs=!0;try{typeof localStorage<"u"&&localStorage&&(si=localStorage,Fs=!1)}catch{}const ri=si,Cl=e=>Fs||addEventListener("storage",e),Dl=e=>Fs||removeEventListener("storage",e),We=Symbol("Equality"),ii=(e,t)=>e===t||!!e?.[We]?.(t)||!1,Al=e=>typeof e=="object",Il=Object.assign,Tl=Object.keys,xl=(e,t)=>{for(const n in e)t(e[n],n)},Ll=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Cn=e=>Tl(e).length,Ol=e=>{for(const t in e)return!1;return!0},Qe=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Bs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Rl=(e,t)=>e===t||Cn(e)===Cn(t)&&Qe(e,(n,s)=>(n!==void 0||Bs(t,s))&&ii(t[s],n)),Ul=Object.freeze,oi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&oi(e[t])}return Ul(e)},Vs=(e,t,n=0)=>{try{for(;ne,fe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[We]!=null)return e[We](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var li={};const Vt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ci=typeof window<"u"&&typeof document<"u"&&!Vt;let ut;const Nl=()=>{if(ut===void 0)if(Vt){ut=Z();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");ut.set(`--${Er(t,"-")}`,n),ut.set(`-${Er(t,"-")}`,n)}})):ut=Z();return ut},Ss=e=>Nl().has(e),Dn=e=>Lr(Vt?li[e.toUpperCase().replaceAll("-","_")]:ri.getItem(e)),ai=e=>Ss("--"+e)||Dn(e)!==null,$l=ai("production"),Fl=Vt&&vl(li.FORCE_COLOR,["true","1","2"]),Bl=Fl||!Ss("--no-colors")&&!ai("no-color")&&(!Vt||process.stdout.isTTY)&&(!Vt||Ss("--color")||Dn("COLORTERM")!==null||(Dn("TERM")||"").includes("color")),hi=e=>new Uint8Array(e),Vl=(e,t,n)=>new Uint8Array(e,t,n),jl=e=>new Uint8Array(e),Hl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Jl=e=>{const t=atob(e),n=hi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Vl(t.buffer,t.byteOffset,t.byteLength)},Yl=ci?Hl:Pl,zl=ci?Jl:Wl,Gl=e=>{const t=hi(e.byteLength);return t.set(e),t};class ql{constructor(t,n){this.left=t,this.right=n}}const Ct=(e,t)=>new ql(e,t),Xl=(e,t)=>e.forEach(n=>t(n.left,n.right)),Or=e=>e.next()>=.5,ls=(e,t,n)=>ct(e.next()*(n+1-t)+t),ui=(e,t,n)=>ct(e.next()*(n+1-t)+t),js=(e,t,n)=>ui(e,t,n),Kl=e=>Zr(js(e,97,122)),Ql=(e,t=0,n=20)=>{const s=js(e,t,n);let r="";for(let i=0;it[js(e,0,t.length-1)],Zl=Symbol("0schema");class tc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(el(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const bs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[We]?ii(e,t):ye(e)?xs(e,n=>Ls(t,s=>bs(n,s))):Al(e)?Qe(e,(n,s)=>bs(n,t[s])):!1;class X{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),bs(n,s)}equals(t){return this.constructor===t.constructor&&fe(this.shape,t.shape)}[Zl](){return!0}[We](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){lt()}get nullable(){return Ie(this,Wn)}get optional(){return new gi(this)}cast(t){return Rr(t,this),t}expect(t){return Rr(t,this),t}}class Hs extends X{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const j=(e,t=null)=>new Hs(e,t);j(Hs);class Ps extends X{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const Y=e=>new Ps(e);j(Ps);class jn extends X{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Hn=(...e)=>new jn(e),fi=j(jn),ec=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),di=e=>{if(Se.check(e))return[ec(e)];if(fi.check(e))return e.shape.map(t=>t+"");if(Ei.check(e))return["[+-]?\\d+.?\\d*"];if(Ci.check(e))return[".*"];if(An.check(e))return e.shape.map(di).flat(1);nt()};class nc extends X{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}j(nc);const sc=Symbol("optional");class gi extends X{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[sc](){return!0}}const rc=j(gi);class ic extends X{check(t,n){return n?.extend(null,"never",typeof t),!1}}j(ic);class Pn extends X{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Pn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):Qe(this.shape,(s,r)=>{const i=this._isPartial&&!Bs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const oc=e=>new Pn(e),lc=j(Pn),cc=Y(e=>e!=null&&(e.constructor===Object||e.constructor==null));class pi extends X{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&Qe(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const wi=(e,t)=>new pi(e,t),ac=j(pi);class mi extends X{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&Qe(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const hc=(...e)=>new mi(e);j(mi);class yi extends X{constructor(t){super(),this.shape=t.length===1?t[0]:new Js(t)}check(t,n){const s=ye(t)&&xs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const ki=(...e)=>new yi(e),uc=j(yi),fc=Y(e=>ye(e));class Si extends X{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const dc=(e,t=null)=>new Si(e,t);j(Si);const gc=dc(X);class pc extends X{constructor(t){super(),this.len=t.length-1,this.args=hc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const wc=j(pc),mc=Y(e=>typeof e=="function");class yc extends X{constructor(t){super(),this.shape=t}check(t,n){const s=xs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}j(yc,e=>e.shape.length>0);class Js extends X{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ls(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ie=(...e)=>e.findIndex(t=>An.check(t))>=0?Ie(...e.map(t=>Ye(t)).map(t=>An.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Js(e),An=j(Js),bi=()=>!0,In=Y(bi),kc=j(Ps,e=>e.shape===bi),Ws=Y(e=>typeof e=="bigint"),Sc=Y(e=>e===Ws),_i=Y(e=>typeof e=="symbol");Y(e=>e===_i);const de=Y(e=>typeof e=="number"),Ei=Y(e=>e===de),Se=Y(e=>typeof e=="string"),Ci=Y(e=>e===Se),Jn=Y(e=>typeof e=="boolean"),bc=Y(e=>e===Jn),Di=Hn(void 0);j(jn,e=>e.shape.length===1&&e.shape[0]===void 0);Hn(void 0);const Wn=Hn(null),_c=j(jn,e=>e.shape.length===1&&e.shape[0]===null);j(Uint8Array);j(Hs,e=>e.shape===Uint8Array);const Ec=Ie(de,Se,Wn,Di,Ws,Jn,_i);(()=>{const e=ki(In),t=wi(Se,In),n=Ie(de,Se,Wn,Jn,e,t);return e.shape=n,t.shape.values=n,n})();const Ye=e=>{if(gc.check(e))return e;if(cc.check(e)){const t={};for(const n in e)t[n]=Ye(e[n]);return oc(t)}else{if(fc.check(e))return Ie(...e.map(Ye));if(Ec.check(e))return Hn(e);if(mc.check(e))return j(e)}nt()},Rr=$l?()=>{}:(e,t)=>{const n=new tc;if(!t.check(e,n))throw gt(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Cc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ye(t),h:n}),this}else(t){return this.if(In,t)}done(){return(t,n)=>{for(let s=0;snew Cc(e),Ai=Dc(In).if(Ei,(e,t)=>ls(t,_r,En)).if(Ci,(e,t)=>Ql(t)).if(bc,(e,t)=>Or(t)).if(Sc,(e,t)=>BigInt(ls(t,_r,En))).if(An,(e,t)=>oe(t,cs(t,e.shape))).if(lc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(rc.check(r)){if(Or(t))continue;r=r.shape}n[s]=Ai(r,t)}return n}).if(uc,(e,t)=>{const n=[],s=ui(t,0,42);for(let r=0;rcs(t,e.shape)).if(_c,(e,t)=>null).if(wc,(e,t)=>{const n=oe(t,e.res);return()=>n}).if(kc,(e,t)=>oe(t,cs(t,[de,Se,Wn,Di,Ws,Jn,ki(de),wi(Ie("a","b","c"),de)]))).if(ac,(e,t)=>{const n={},s=ls(t,0,3);for(let r=0;rAi(Ye(t),e),yt=typeof document<"u"?document:{},Ac=e=>yt.createElement(e),Ic=()=>yt.createDocumentFragment();Y(e=>e.nodeType===Nc);const Tc=e=>yt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const xc=(e,t)=>(Xl(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Lc=e=>{const t=Ic();for(let n=0;n(Ii(e,Lc(t)),e),Ph=(e,t=[],n=[])=>Oc(xc(Ac(e),t),n);Y(e=>e.nodeType===Uc);const Jh=Tc;Y(e=>e.nodeType===Mc);const Rc=e=>Vo(e,(t,n)=>`${n}:${t};`).join(""),Ii=(e,t)=>e.appendChild(t),Uc=yt.ELEMENT_NODE,Mc=yt.TEXT_NODE;yt.CDATA_SECTION_NODE;yt.COMMENT_NODE;const vc=yt.DOCUMENT_NODE;yt.DOCUMENT_TYPE_NODE;const Nc=yt.DOCUMENT_FRAGMENT_NODE;Y(e=>e.nodeType===vc);const It=Symbol,Ti=It(),xi=It(),$c=It(),Fc=It(),Bc=It(),Li=It(),Vc=It(),Ys=It(),jc=It(),Hc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=Z();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Oi(e)),Ui.forEach(t=>t.print(e))},Ri=(...e)=>{console.warn(...Oi(e)),e.unshift(Ys),Ui.forEach(t=>t.print(e))},Ui=Ft(),Mi=e=>({[Symbol.iterator](){return this},next:e}),Yc=(e,t)=>Mi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),as=(e,t)=>Mi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Yn{constructor(t,n){this.clock=t,this.len=n}}class Te{constructor(){this.clients=new Map}}const be=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=ct((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&zc(n,t.clock)!==null},zs=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Yn(r.clock,ee(r.len,i.clock+i.len-r.clock)):(s{const t=new Te;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{mt(e.clients,t,()=>[]).push(new Yn(n,s))},Gc=()=>new Te,qc=e=>{const t=Gc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},xe=(e,t)=>{b(e.restEncoder,t.clients.size),At(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),b(e.restEncoder,n);const r=s.length;b(e.restEncoder,r);for(let i=0;i{const t=new Te,n=E(e.restDecoder);for(let s=0;s0){const o=mt(t.clients,r,()=>[]);for(let l=0;l{const s=new Te,r=E(e.restDecoder);for(let i=0;i0){const i=new Qt;return b(i.restEncoder,0),xe(i,s),i.toUint8Array()}return null},vi=ni;class ne extends Os{constructor({guid:t=_l(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=vi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Gi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=xr(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>xr(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&O(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(At(this.subdocs).map(t=>t.guid))}transact(t,n=null){return O(this,t,n)}get(t,n=W){const s=mt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==W&&r!==n)if(r===W){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,we)}getText(t=""){return this.get(t,Ce)}getMap(t=""){return this.get(t,Ee)}getXmlElement(t=""){return this.get(t,De)}getXmlFragment(t=""){return this.get(t,Zt)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,At(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ne({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,O(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Ni{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class $i extends Ni{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return ke(this.restDecoder)}readString(){return Nt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Je(this.restDecoder)}readBuf(){return Gl(z(this.restDecoder))}readJSON(){return JSON.parse(Nt(this.restDecoder))}readKey(){return Nt(this.restDecoder)}}class Xc{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class _e extends Xc{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new os(z(t)),this.clientDecoder=new bn(z(t)),this.leftClockDecoder=new os(z(t)),this.rightClockDecoder=new os(z(t)),this.infoDecoder=new Tr(z(t),ke),this.stringDecoder=new kl(z(t)),this.parentInfoDecoder=new Tr(z(t),ke),this.typeRefDecoder=new bn(z(t)),this.lenDecoder=new bn(z(t))}readLeftID(){return new ge(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ge(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Je(this.restDecoder)}readBuf(){return z(this.restDecoder)}readJSON(){return Je(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ee(s,t[0].id.clock);const r=pt(t,s);b(e.restEncoder,t.length-r),e.writeClient(n),b(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{F(t,i)>r&&s.set(i,r)}),zn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),b(e.restEncoder,s.size),At(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{Kc(e,t.clients.get(r),r,i)})},Qc=(e,t)=>{const n=Z(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=At(n.keys()).sort((f,g)=>f-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Gi,c=new Map,a=(f,g)=>{const y=c.get(f);(y==null||y>g)&&c.set(f,g)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const g=f.id.client,y=n.get(g);y?(y.i--,l.clients.set(g,y.refs.slice(y.i)),n.delete(g),y.i=0,y.refs=[]):l.clients.set(g,[f]),r=r.filter(S=>S!==g)}s.length=0};for(;;){if(u.constructor!==it){const g=mt(h,u.id.client,()=>F(t,u.id.client))-u.id.clock;if(g<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,F(t,y)),d();else{u=S.refs[S.i++];continue}}else(g===0||g0)u=s.pop();else if(o!==null&&o.i0){const f=new Qt;return qs(f,l,new Map),b(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ta=(e,t)=>qs(e,t.doc.store,t.beforeState),ea=(e,t,n,s=new _e(e))=>O(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=Qc(s,o),a=Zc(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=xn([u.update,a.update])}}else l.pendingStructs=a;const h=Ur(s,r,l);if(l.pendingDs){const d=new _e(jt(l.pendingDs));E(d.restDecoder);const f=Ur(d,r,l);h&&f?l.pendingDs=xn([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Vi(r.doc,d)}},n,!1),Vi=(e,t,n,s=_e)=>{const r=jt(t);ea(r,e,n,new s(r))},ji=(e,t,n)=>Vi(e,t,n,$i),na=(e,t,n=new Map)=>{qs(e,t.store,n),xe(e,qc(t.store))},sa=(e,t=new Uint8Array([0]),n=new Qt)=>{const s=Pi(t);na(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ea(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===tn)return ba(r.map((i,o)=>o===0?i:Da(i)));if(n.constructor===Qt)return xn(r)}return r[0]},Hi=(e,t)=>sa(e,t,new tn),ra=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sra(new Ni(jt(e))),Ji=(e,t)=>(b(e.restEncoder,t.size),At(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{b(e.restEncoder,n),b(e.restEncoder,s)}),e),ia=(e,t)=>Ji(e,zn(t.store)),oa=(e,t=new Bi)=>(e instanceof Map?Ji(t,e):ia(t,e),t.toUint8Array()),la=e=>oa(e,new Fi);class ca{constructor(){this.l=[]}}const Mr=()=>new ca,vr=(e,t)=>e.l.push(t),Nr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Wi=(e,t,n)=>Vs(e.l,[t,n]);class ge{constructor(t,n){this.client=t,this.clock=n}}const ue=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new ge(e,t),Yi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw nt()},Tn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class zi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Wh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},aa=e=>new zi(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ha{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ua=(e,t,n=0)=>new ha(e,t,n),pn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Yi(e):s=D(e._item.id.client,e._item.id.clock),new zi(s,r,t,n)},Yh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return pn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return pn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return pn(e,s.lastId,n);s=s.right}return pn(e,null,n)},fa=(e,t)=>{const n=pe(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},da=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(F(s,r.client)<=r.clock)return null;const u=n?As(s,r):fa(s,r),h=u.item;if(!(h instanceof R))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(F(s,i.client)<=i.clock)return null;const{item:u}=n?As(s,i):{item:pe(s,i)};if(u instanceof R&&u.content instanceof kt)c=u.content.type;else return null}else throw nt();l>=0?a=c._length:a=0}return ua(c,a,e.assoc)},zh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ue(e.item,t.item)&&ue(e.type,t.type)&&e.assoc===t.assoc,ae=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Ze(t.ds,e.id),Es=(e,t)=>{const n=mt(e.meta,Es,Ft),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Gi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const zn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},F=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},qi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw nt()}n.push(t)},pt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=ct(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[pt(n,t.clock)]},pe=ga,Cs=(e,t,n)=>{const s=pt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Cs(e,n,t.clock)]},$r=(e,t,n)=>{const s=t.clients.get(n.client),r=pt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==rt&&s.splice(r+1,0,vn(e,i,n.clock-i.id.clock+1)),i},pa=(e,t,n)=>{const s=e.clients.get(t.id.client);s[pt(s,t.id.clock)]=n},Xi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Cs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!jo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(zs(t.deleteSet),ta(e,t),xe(e,t.deleteSet),!0),Br=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&mt(e.changed,t,Ft).add(n)},_n=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof R&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ma=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=pt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Rs(r.length-1,1+pt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+_n(r,c)}})},Ki=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Wi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ba(n)})}),Vs(l,[])}finally{s.gc&&ma(i,r,s.gcFilter),ya(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),g=ee(pt(f,d),1);for(let y=f.length-1;y>=g;)y-=1+_n(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),g=pt(f,d);g+11||g>0&&_n(f,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Wc(Ys,Ti,"[yjs] ",xi,Li,"Changed the client-id because another client seems to be using it."),s.clientID=vi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new tn;Fr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new Qt;Fr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):Ki(e,t+1)}}},O=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new wa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&Ki(r,0)}}return o};class ka{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Vr=(e,t,n)=>{be(e,n.deletions,s=>{s instanceof R&&t.scope.some(r=>r===e.doc||Tn(r,s))&&sr(s,!1)})},jr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;O(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;be(l,a.insertions,f=>{if(f instanceof R){if(f.redone!==null){let{item:g,diff:y}=As(c,f.id);y>0&&(g=Q(l,D(g.id.client,g.id.clock+y))),f=g}!f.deleted&&i.some(g=>g===l.doc||Tn(g,f))&&h.push(f)}}),be(l,a.deletions,f=>{f instanceof R&&i.some(g=>g===l.doc||Tn(g,f))&&!Ze(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=wo(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const g=h[f];e.deleteFilter(g)&&(g.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class Gh extends Os{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=ye(t)?t[0].doc:t instanceof ne?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Te;c.afterState.forEach((S,w)=>{const _=c.beforeState.get(w)||0,L=S-_;L>0&&ze(d,w,_,L)});const f=Bt();let g=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=_s([S.deletions,c.deleteSet]),S.insertions=_s([S.insertions,d])}else h.push(new ka(c.deleteSet,d)),g=!0;!a&&!u&&(this.lastChange=f),be(c,c.deleteSet,S=>{S instanceof R&&this.scope.some(w=>w===c.doc||Tn(w,S))&&sr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=ye(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof W?s.doc!==this.doc:s!==this.doc)&&Ri("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Vr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Vr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=jr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=jr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Sa(e){const t=E(e.restDecoder);for(let n=0;nxn(e,$i,tn),_a=(e,t)=>{if(e.constructor===rt){const{client:n,clock:s}=e.id;return new rt(D(n,s+t),e.length-t)}else if(e.constructor===it){const{client:n,clock:s}=e.id;return new it(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new R(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},xn=(e,t=_e,n=Qt)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(jt(u)));let r=s.map(u=>new Xs(u,!0)),i=null;const o=new n,l=new Ks(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const g=d.curr.id.clock-f.curr.id.clock;return g===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===it?1:-1:g}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Mt(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===it?i.struct.length-=g:d=_a(d,g)),i.struct.mergeWith(d)||(Mt(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==it;d=u.next())Mt(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Mt(l,i.struct,i.offset),i=null),Qs(l);const c=s.map(u=>Gs(u)),a=_s(c);return xe(o,a),o.toUint8Array()},Ea=(e,t,n=_e,s=Qt)=>{const r=Pi(t),i=new s,o=new Ks(i),l=new n(jt(e)),c=new Xs(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===it){c.next();continue}if(u.id.clock+u.length>d)for(Mt(o,u,ee(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Mt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}Qs(o);const a=Gs(l);return xe(i,a),i.toUint8Array()},Qi=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:M(e.encoder.restEncoder)}),e.encoder.restEncoder=G(),e.written=0)},Mt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Qi(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Qs=e=>{Qi(e);const t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n{const r=new n(jt(e)),i=new Xs(r,!1),o=new s,l=new Ks(o);for(let a=i.curr;a!==null;a=i.next())Mt(l,t(a),0);Qs(l);const c=Gs(r);return xe(o,c),o.toUint8Array()},Da=e=>Ca(e,Ml,_e,tn),Hr="You must not compute changes after the event-handler fired.";class Gn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Aa(this.currentTarget,this.target))}deletes(t){return Ze(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw gt(Hr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ns(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ns(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ns(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw gt(Hr);const n=this.target,s=Ft(),r=Ft(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Aa=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},q=()=>{Ri("Invalid access: Add Yjs type to a document before reading data.")},Zi=80;let Zs=0;class Ia{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Zs++}}const Ta=e=>{e.timestamp=Zs++},to=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Zs++},xa=(e,t,n)=>{if(e.length>=Zi){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>kn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&kn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ee(t,r.index+n))}},Xn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;mt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Wi(s._eH,n,t)};class W{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Mr(),this._dEH=Mr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw lt()}clone(){throw lt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){vr(this._eH,t)}observeDeep(t){vr(this._dEH,t)}unobserve(t){Nr(this._eH,t)}unobserveDeep(t){Nr(this._dEH,t)}toJSON(){}}const eo=(e,t,n)=>{e.doc??q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},no=e=>{e.doc??q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return qe(e,(s,r)=>{n.push(t(s,r,e))}),n},La=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},ro=(e,t)=>{e.doc??q();const n=qn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new te(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new en(new Uint8Array(h))),r.integrate(e,0);break;case ne:r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new nn(h)),r.integrate(e,0);break;default:if(h instanceof W)r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new kt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},io=()=>gt("Length exceeded!"),oo=(e,t,n,s)=>{if(n>t._length)throw io();if(n===0)return t._searchMarker&&Ge(t._searchMarker,n,s.length),Ln(e,t,null,s);const r=n,i=qn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Ln(e,t,r,n)},lo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=qn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw io();t._searchMarker&&Ge(t._searchMarker,r,-i+s)},On=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},tr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new te([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new te([s]);break;case Uint8Array:l=new en(s);break;case ne:l=new nn(s);break;default:if(s instanceof W)l=new kt(s);else throw new Error("Unexpected content type")}new R(D(o,F(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},er=(e,t)=>{e.doc??q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},co=e=>{const t={};return e.doc??q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},ao=(e,t)=>{e.doc??q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ra=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&ae(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},wn=e=>(e.doc??q(),Yc(e._map.entries(),t=>!t[1].deleted));class Ua extends Gn{}class we extends W{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new we;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new we}clone(){const t=new we;return t.insert(0,this.toArray().map(n=>n instanceof W?n.clone():n)),t}get length(){return this.doc??q(),this._length}_callObserver(t,n){super._callObserver(t,n),Xn(this,t,new Ua(this,t))}insert(t,n){this.doc!==null?O(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?O(this.doc,n=>{Oa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?O(this.doc,s=>{lo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return ro(this,t)}toArray(){return no(this)}slice(t=0,n=this.length){return eo(this,t,n)}toJSON(){return this.map(t=>t instanceof W?t.toJSON():t)}map(t){return so(this,t)}forEach(t){qe(this,t)}[Symbol.iterator](){return La(this)}_write(t){t.writeTypeRef(rh)}}const Ma=e=>new we;class va extends Gn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ee extends W{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return this.forEach((n,s)=>{t.set(s,n instanceof W?n.clone():n)}),t}_callObserver(t,n){Xn(this,t,new va(this,t,n))}toJSON(){this.doc??q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof W?r.toJSON():r}}),t}get size(){return[...wn(this)].length}keys(){return as(wn(this),t=>t[0])}values(){return as(wn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return as(wn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return er(this,t)}has(t){return ao(this,t)}clear(){this.doc!==null?O(this.doc,t=>{this.forEach(function(n,s,r){On(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ih)}}const Na=e=>new Ee,vt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Rl(e,t);class Ds{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&nt(),this.right.content.constructor===H?this.right.deleted||Le(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Pr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===H?t.right.deleted||Le(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?qn(t,n):null;if(i){const o=new Ds(i.p.left,i.p,i.index,r);return Pr(e,o,n-i.index)}else{const o=new Ds(null,t._start,0,r);return Pr(e,o,n)}},ho=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===H&&vt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new R(D(i,F(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new H(l,o));u.integrate(e,0),n.right=u,n.forward()})},Le=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},uo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===H&&vt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},fo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!vt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new R(D(i,F(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new H(l,c)),n.right.integrate(e,0),n.forward()}}return o},hs=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;uo(n,r);const l=fo(e,t,n,r),c=s.constructor===String?new wt(s):s instanceof W?new kt(s):new se(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ge(t._searchMarker,n.index,c.getLength()),u=new R(D(o,F(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),ho(e,t,n,l)},Jr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;uo(n,r);const l=fo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===H));){if(!n.right.deleted)switch(n.right.content.constructor){case H:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(vt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new R(D(o,F(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new wt(c)),n.right.integrate(e,0),n.forward()}ho(e,t,n,l)},go=(e,t,n,s,r)=>{let i=t;const o=Z();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===H){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===H){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Le(r,a)}}t=t.right}return l},$a=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===H){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Fa=e=>{let t=0;return O(e.doc,n=>{let s=e._start,r=e._start,i=Z();const o=ws(i);for(;r;)r.deleted===!1&&(r.content.constructor===H?Le(o,r.content):(t+=go(n,s,r,i,o),i=ws(o),s=r)),r=r.right}),t},Ba=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&Xi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===H&&o.constructor!==rt&&t.add(o.parent)})}O(n,s=>{be(e,e.deleteSet,r=>{if(r instanceof rt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===H?t.add(i):$a(s,r)});for(const r of t)Fa(r)})},Wr=(e,t,n)=>{const s=n,r=ws(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case kt:case se:case wt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];O(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((g,y)=>{g!==null&&(f.attributes[y]=g)}))),a="";break;case"retain":u>0&&(f={retain:u},Ol(c)||(f.attributes=Il({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case kt:case se:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case wt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case H:{const{key:f,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;vt(y,g)?g!==null&&o.delete(s):(l==="retain"&&d(),vt(g,i.get(f)??null)?delete c[f]:c[f]=g)}}else if(this.deletes(o)){i.set(f,g);const y=r.get(f)??null;vt(y,g)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,g);const y=c[f];y!==void 0&&(vt(y,g)?y!==null&&o.delete(s):(l==="retain"&&d(),g===null?delete c[f]:c[f]=g))}o.deleted||(l==="insert"&&d(),Le(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ce extends W{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ce}clone(){const t=new Ce;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Va(this,t,n);Xn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===wt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?O(this.doc,s=>{const r=new Ds(null,this._start,0,new Map);for(let i=0;i0)&&hs(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Jr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Wr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??q();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((g,y)=>{d=!0,h[y]=g});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(ae(c,t)||n!==void 0&&ae(c,n))switch(c.content.constructor){case wt:{const h=i.get("ychange");t!==void 0&&!ae(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!ae(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case kt:case se:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,g)=>{d[g]=f})}r.push(h);break}case H:ae(c,t)&&(a(),Le(i,c.content));break}c=c.right}a()};return t||n?O(o,h=>{t&&Es(h,t),n&&Es(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),hs(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!s);hs(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?O(s,r=>{Wr(r,mn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!1);o.right!==null&&Jr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return er(this,t)}getAttributes(){return co(this)}_write(t){t.writeTypeRef(oh)}}const ja=e=>new Ce;class us{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??q()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===De||n.constructor===Zt)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Zt extends W{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Zt}clone(){const t=new Zt;return t.insert(0,this.toArray().map(n=>n instanceof W?n.clone():n)),t}get length(){return this.doc??q(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new us(this,t)}querySelector(t){t=t.toUpperCase();const s=new us(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),At(new us(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Xn(this,t,new Ja(this,n,t))}toString(){return so(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),qe(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?O(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)O(this.doc,s=>{const r=t&&t instanceof W?t._item:t;Ln(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw gt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?O(this.doc,s=>{lo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return no(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return ro(this,t)}slice(t=0,n=this.length){return eo(this,t,n)}forEach(t){qe(this,t)}_write(t){t.writeTypeRef(ch)}}const Ha=e=>new Zt;class De extends Zt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new De(this.nodeName)}clone(){const t=new De(this.nodeName),n=this.getAttributes();return xl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof W?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return er(this,t)}hasAttribute(t){return ao(this,t)}getAttributes(t){return t?Ra(this,t):co(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return qe(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(lh),t.writeKey(this.nodeName)}}const Pa=e=>new De(e.readKey());class Ja extends Gn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Rn extends Ee{constructor(t){super(),this.hookName=t}_copy(){return new Rn(this.hookName)}clone(){const t=new Rn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(ah),t.writeKey(this.hookName)}}const Wa=e=>new Rn(e.readKey());class Un extends Ce{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Un}clone(){const t=new Un;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(hh)}}const Ya=e=>new Un;class nr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw lt()}mergeWith(t){return!1}write(t,n,s){throw lt()}integrate(t,n){throw lt()}}const za=0;class rt extends nr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),qi(t.doc.store,this)}write(t,n){t.writeInfo(za),t.writeLen(this.length-n)}getMissing(t,n){return null}}class en{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new en(this.content)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Ga=e=>new en(e.readBuf());class Xe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Xe(this.len)}splice(t){const n=new Xe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){ze(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const qa=e=>new Xe(e.readLen()),po=(e,t)=>new ne({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class nn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new nn(po(this.doc.guid,this.opts))}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const Xa=e=>new nn(po(e.readString(),e.readAny()));class se{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new se(this.embed)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Ka=e=>new se(e.readJSON());class H{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new H(this.key,this.value)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Qa=e=>new H(e.readKey(),e.readJSON());class Mn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Mn(this.arr)}splice(t){const n=new Mn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const nh=e=>new wt(e.readString()),sh=[Ma,Na,ja,Pa,Ha,Wa,Ya],rh=0,ih=1,oh=2,lh=3,ch=4,ah=5,hh=6;class kt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new kt(this.type._copy())}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const uh=e=>new kt(sh[e.readTypeRef()](e)),As=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=pe(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof R);return{item:r,diff:s}},sr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},vn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new R(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Yr=(e,t)=>Ls(e,n=>Ze(n.deletions,t)),wo=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Q(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||wo(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Q(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Q(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Q(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||Ze(s,h.right.id)||Yr(i.undoStack,h.right.id)||Yr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Q(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const g=F(l,c),y=D(c,g),S=new R(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,sr(S,!0),S.integrate(e,0),S};class R extends nr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?br:0}set marker(t){(this.info&rs)>0!==t&&(this.info^=rs)}get marker(){return(this.info&rs)>0}get keep(){return(this.info&Sr)>0}set keep(t){this.keep!==t&&(this.info^=Sr)}get countable(){return(this.info&br)>0}get deleted(){return(this.info&ss)>0}set deleted(t){this.deleted!==t&&(this.info^=ss)}markDeleted(){this.info|=ss}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=F(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=F(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ge&&this.id.client!==this.parent.client&&this.parent.clock>=F(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=$r(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Q(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===rt||this.right&&this.right.constructor===rt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===R?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===R&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ge){const s=pe(n,this.parent);s.constructor===rt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=$r(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ue(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),ze(t.deleteSet,this.id.client,this.id.clock,this.length),Br(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw nt();this.content.gc(t),n?pa(t,this,new rt(this.id,this.length)):this.content=new Xe(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Fn|(s===null?0:et)|(r===null?0:Dt)|(i===null?0:je);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Yi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===ge?(t.writeParentInfo(!1),t.writeLeftID(l)):nt();i!==null&&t.writeString(i)}this.content.write(t,n)}}const mo=(e,t)=>fh[t&Fn](e),fh=[()=>{nt()},qa,Za,Ga,nh,Ka,Qa,uh,eh,Xa,()=>{nt()}],dh=10;class it extends nr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){nt()}write(t,n){t.writeInfo(dh),b(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const yo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},ko="__ $YJS$ __";yo[ko]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");yo[ko]=!0;const So=new Map;class gh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:zl(n.newValue||"")}),Cl(this._onChange)}postMessage(t){ri.setItem(this.room,Yl(jl(t)))}close(){Dl(this._onChange)}}const ph=typeof BroadcastChannel>"u"?gh:BroadcastChannel,rr=e=>mt(So,e,()=>{const t=Ft(),n=new ph(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),wh=(e,t)=>(rr(e).subs.add(t),t),mh=(e,t)=>{const n=rr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),So.delete(e)),s},he=(e,t,n=null)=>{const s=rr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},bo=0,ir=1,_o=2,Is=(e,t)=>{b(e,bo);const n=la(t);$(e,n)},Eo=(e,t,n)=>{b(e,ir),$(e,Hi(t,n))},yh=(e,t,n)=>Eo(t,n,z(e)),Co=(e,t,n,s)=>{try{ji(t,z(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},kh=(e,t)=>{b(e,_o),$(e,t)},Sh=Co,bh=(e,t,n,s,r)=>{const i=E(e);switch(i){case bo:yh(e,t,n);break;case ir:Co(e,n,s,r);break;case _o:Sh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},_h=0,Eh=(e,t,n)=>{E(e)===_h&&n(t,Nt(e))},fs=3e4;class Do extends Jo{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Bt();this.getLocalState()!==null&&fs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&fs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&or(this,s,"timeout")},ct(fs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Bt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),fe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const or=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Ve=(e,t,n=e.states)=>{const s=t.length,r=G();b(r,s);for(let i=0;i{const s=jt(t),r=Bt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Dh=e=>Ll(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Gt=0,Ao=3,me=1,Ah=2,sn=[];sn[Gt]=(e,t,n,s,r)=>{b(e,Gt);const i=bh(t,e,n.doc,n);s&&i===ir&&!n.synced&&(n.synced=!0)};sn[Ao]=(e,t,n,s,r)=>{b(e,me),$(e,Ve(n.awareness,Array.from(n.awareness.getStates().keys())))};sn[me]=(e,t,n,s,r)=>{Ch(n.awareness,z(t),n)};sn[Ah]=(e,t,n,s,r)=>{Eh(t,n.doc,(i,o)=>Ih(n,o))};const zr=3e4,Ih=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Io=(e,t,n)=>{const s=jt(t),r=G(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Th=e=>!(e.code>=4400&&e.code<4500),Ts=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,or(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(To,Rs(Wo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},To=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Bt();const s=Io(e,new Uint8Array(n.data),!0);Us(s)>1&&t.send(M(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Ts(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Bt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=G();if(b(n,Gt),Is(n,e.doc),t.send(M(n)),e.awareness.getLocalState()!==null){const s=G();b(s,me),$(s,Ve(e.awareness,[e.doc.clientID])),t.send(M(s))}},e.emit("status",[{status:"connecting"}])}},ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&he(e.bcChannel,t,e)};class xh extends Os{constructor(t,n,s,{connect:r=!0,awareness:i=new Do(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Th}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=sn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=G();b(f,Gt),Is(f,s),this.ws.send(M(f))}},a)),this._bcSubscriber=(f,g)=>{if(g!==this){const y=Io(this,new Uint8Array(f),!1);Us(y)>1&&he(this.bcChannel,M(y),this)}},this._updateHandler=(f,g)=>{if(g!==this){const y=G();b(y,Gt),kh(y,f),ds(this,M(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:g,removed:y},S)=>{const w=f.concat(g).concat(y),_=G();b(_,me),$(_,Ve(i,w)),ds(this,M(_))},this._exitHandler=()=>{or(this.awareness,[s.clientID],"app closed")},Vt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&zr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=da(aa(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new xh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Oh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Hi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Gr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,L=new Int32Array(2*w+1);for(let I=-w;I<=w;I+=2){let x;w===0?x=0:I===-w||I!==w&&_[I-1+w-1]<_[I+1+w-1]?x=_[I+1+w-1]:x=_[I-1+w-1]+1;let v=x-I;for(;x=r&&v>=i){u=w;break}}a.push(L)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const _=a[w-1],L=d-f,I=L===-w||L!==w&&_[L-1+w-1]<_[L+1+w-1]?L+1:L-1,x=_[I+w-1],v=x-I,N=I===L+1?x:x+1,K=I===L+1?v+1:v;for(;d>N&&f>K;)d--,f--,h.push(d,f);d=x,f=v}for(;d>0&&f>0;)d--,f--,h.push(d,f);const g=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const _=h[w],L=h[w+1];(_>y||L>S)&&g.push({aS:n+y,aE:n+_,bS:n+S,bE:n+L}),y=_+1,S=L+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +`)||i[o.length]===` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Nh(e,t)<=0?e+t:t+e:null}function $n(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=ft(e,s),l=ft(t,s),c=ft(n,s),a=dt(o,i),u=[...Ae(a,dt(l,i)).map(S=>({h:S,toks:l,side:0})),...Ae(a,dt(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,_)=>S.slice(w,_).join(""),d=(S,w,_,L)=>{let I="",x=_;for(const v of S)v.side===w&&(I+=h(o,x,v.h.aS)+h(v.toks,v.h.bS,v.h.bE),x=v.h.aE);return I+h(o,x,L)};let f="",g=0,y=0;for(;yN.side)).size===1){f+=d(S,S[0].side,w,_);continue}const I=d(S,0,w,_),x=d(S,1,w,_);if(I===x){f+=I;continue}if(w===_){const N=$h(I,x,s!==gs,o.length===0);if(N===null){if(!r)return null;f+=x;continue}f+=N;continue}if(s===gs)return null;const v=s===Nn?$n(h(o,w,_),I,x,gs):$n(h(o,w,_),I,x,s+1,r);if(v===null){if(!r)return null;f+=x;continue}f+=v}return f+h(o,g,o.length)}const qt=e=>e===""||e.endsWith(` +`)?e:e+` +`;function xo(e,t,n,s){let r=t.endsWith(` +`);return r===e.endsWith(` +`)&&(r=n.endsWith(` +`)),s===""||r===s.endsWith(` +`)?s:r?s+` +`:s.slice(0,-1)}function le(e,t,n){const s=$n(qt(e),qt(t),qt(n),$t);return s===null?{ok:!1}:{ok:!0,text:xo(e,t,n,s)}}function qh(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=$n(qt(e),qt(t),qt(n),$t,!0)??qt(n);return xo(e,t,n,s)}function qr(e,t){if(e===t)return[];const n=[],s=new Map,r=ft(e,$t),i=ft(t,$t),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?g.charCodeAt(w-1):0;L>=55296&&L<=56319&&w--;const I=_>0?g.charCodeAt(g.length-_):0;I>=56320&&I<=57343&&_--,S+=w,g=g.slice(w,g.length-_),y=y.slice(w,y.length-_),(g.length||y.length)&&s.push({index:S,deleteCount:g.length,insertText:y}),a=d,u=f}}function ps(e,t,n){const s=new Map,r=dt(ft(t,$t),s),i=Ae(dt(ft(e,$t),s),r),o=Ae(r,dt(ft(n,$t),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function yn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const Xr=700,ce=[2e3,4e3,8e3,15e3],Kr=2e3,Bh=4,Vh=32e3,jh=32;function Xh(e){let t=e.seed,n=e.baseSha;const s=(p,k)=>{t=p,r=k,Rt(k);const m=Tt.lastIndexOf(p);m>=0?Tt.splice(0,m+1):Tt.length=0};let r=e.baseSha;const i=p=>{if(!p)return;const k=[];for(let m=p;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(p,k=St)=>{const m=i(k);return r&&r===n&&t.length>Vh?{base:n,text:p,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:p,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,g=!1,y=!1,S=!1,w=null,_=null,L=0;const I=(p=Date.now())=>{const k=Math.max(p,L+1e3);return L=k,Fo(e.path,e.who||"browser",new Date(k))},x=new Map;let v=0,N=!1,K=null,Ht=0,Oe=!1,St=null,Pt=!1;const Tt=[],lr=p=>{Tt.at(-1)!==p&&(Tt.push(p),Tt.length>jh&&Tt.shift())};let bt=!1,Re=null,Jt=0;const Ue=()=>{bt=!1,Re=null},Kn=p=>{Jt===p&&Ue()};let tt=0,ot=0,rn=null,Wt=null,Qn=!1,_t=null,Me=!1,Yt=null,st=null;const U=p=>e.onState?.(p),on=p=>e.apiBase+"upload/content?path="+encodeURIComponent(p),xt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let ln=null,Zn=0;const ve=()=>{clearTimeout(ln??void 0),ln=null},cn=p=>{if(!(p instanceof ht?p.status>=500||p.status===429:!0)||h||a)return;ve();const m=ce[Math.min(Zn,ce.length-1)];Zn++,ln=setTimeout(()=>{ln=null,!h&&!a&&Ne()},m)},cr=()=>{ve(),Zn=0},an=()=>{ve(),Yt&&clearTimeout(Yt),Yt=setTimeout(()=>{Ne()},Xr)},zt=p=>{if(h)return f=p,!0;const k=B();if(k===p)return!0;const m=qr(k,p);if(fr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Ne=()=>{if(a)return Promise.resolve();if(g)return y?Promise.resolve():Fe();if(Wt)return Qn=!0,Wt;const p=(async()=>{try{await Lo()}finally{Wt=null}})();return Wt=p,p},Lo=async()=>{let p=0;for(;;){if(Qn=!1,P||a||S)return;const k=B();if(k===t&&!Pt){U("clean");return}U("saving"),e.onWriting?.();const m=l||c?await Oo(k):await Uo(k);if(m==="stop")return;if(m==="rebased"){if(++p>Bh){await hn(B(),n??"");return}continue}if(!Qn){U(B()===t&&!Pt?"clean":"dirty");return}}};let Lt=!1;const Oo=async p=>{_t=p,Me=!1;let k;try{k=await dn(on(e.path),p,n,Lt)}catch(m){return _t=null,m instanceof ht&&m.status===422&&yn(m)?(Lt=!1,$e(p),"stop"):m instanceof ht&&m.status===409?await ar(t,!1)?"rebased":"stop":(U("error"),cn(m),"stop")}return _t=null,Lt=!1,cr(),k.merged?await ar(p,!0)?"rebased":"stop":(Me||s(p,k.sha),e.onSaved?.(p),"done")},ar=async(p,k)=>{let m;try{m=await yr(kr(e.apiBase,e.path))}catch(V){return U("error"),B()!==t&&cn(V),!1}if(m.kind!=="text")return U("error"),!1;const A=B(),C=le(p,m.text,A);return!C.ok||!zt(C.text)?(k&&s(m.text,m.sha),await hn(A,m.sha??""),!1):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ro=p=>{if(p.update&&T.applyRemoteUpdate(p.update),typeof p.text!="string"){St=null;return}let k=null;for(let m=St;m!==null;m=m.prev)if(m.sent!==m.from&&ps(m.from,m.sent,p.text)){k=m;break}if(St=null,k){Pt=!0;const m=le(k.sent,p.text,B());m.ok&&zt(m.text)?(t=p.text,r=void 0,Rt(p.sha)):(t=k.sent,r=void 0)}},Uo=async p=>{_t=p,Me=!1;let k;const m=St;try{St={sent:p,from:t,prev:m},k=await Ut(xt,{...o(p,m),...Lt?{confirm_shrink:!0}:{}})}catch(C){if(_t=null,C instanceof ht&&[400,401,403,404,405,409,413].includes(C.status)&&(St=m),C instanceof ht&&(C.status===404||C.status===405))return c=!0,"rebased";if(C instanceof ht&&C.status===422&&yn(C))return Lt=!1,$e(p),"stop";if(C instanceof ht&&C.status===409&&!a){let V={};try{V=JSON.parse(C.body)}catch{}const at=typeof V.text=="string"?V.text:null;if(at!==null){const mr=le(t,at,B());if(mr.ok&&zt(mr.text))return t=at,r=void 0,Rt(V.sha),"rebased"}N=!0;const ie=B(),wr=await hn(ie,V.sha??"");return h?"stop":wr?(cn(wr.err),"stop"):(N=!1,B()!==ie?"rebased":"stop")}return U(a?"dirty":"error"),cn(C),"stop"}if(_t=null,Lt=!1,cr(),k.update&&T.applyRemoteUpdate(k.update),St=null,Pt=!1,a)return"stop";const A=le(p,k.text,B());return A.ok&&zt(A.text)&&(Me||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let P=null;const $e=p=>{P||h||!e.onShrinkRefused||(U("error"),P={was:gn(t),now:gn(p),confirm:async()=>{if(!h){if(a){U("saving"),e.onWriting?.();const k=tt,m=Jt;try{const A=await Ut(xt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),ts(k,m);const C=!bt&&ot>=tt;U(C?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&ot{if(!h)try{const k=await yr(kr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),zt(k.text),P=null,a&&!u){if(await re(!1),h)return;U(ot>=tt&&!bt?"clean":"dirty");return}ot=tt,d&&(d=0,e.onPending?.(0)),Ue(),U("clean")}catch{U("error")}finally{P=null}}},e.onShrinkRefused(P))};let Ot=null;const Mo=()=>{Ot&&clearTimeout(Ot),Ot=setTimeout(()=>{const p=B();Bo(gn(t),gn(p))&&$e(p)},Xr)},hn=async(p,k,m=I())=>{const A=++v;x.set(m,p);try{return await dn(on(m),p),A===v&&!a&&(t=p,r=void 0,k&&(n=k),U("clean")),e.onConflictCopy?.(m),null}catch(C){return A===v&&!a&&U("error"),{err:C}}finally{x.get(m)===p&&x.delete(m)}},ts=(p,k)=>{ot=Math.max(ot,p),Kn(k),!(h||u)&&(d=tt-ot,e.onPending?.(d))},vo=()=>{h||u||P||st||(st=setTimeout(()=>{st=null,!u&&!h&&re(!1)},Kr))},re=p=>{if(clearTimeout(st??void 0),st=null,p){if(ot>=tt)return Promise.resolve();const m=tt,A=Jt;return Ut(xt,{update:T.encodeState(),base:n},!0).then(C=>{Rt(C.sha),ts(m,A)})}if(rn)return rn;const k=(async()=>{try{for(;!u&&!h&&!P&&ot{g=!1,w=null,_=null,Ht=0,clearTimeout(K??void 0),K=null,Pt=!1,a=!0,lr(T.text.toString()),p?.(),Oe&&(Oe=!1,e.onReady(T))},Fe=async()=>{if(h||a||y||S)return;if(clearTimeout(K??void 0),K=null,Yt&&clearTimeout(Yt),Yt=null,Wt){S=!0;try{for(;Wt;)await Wt}finally{S=!1}if(h||a)return;if(!u){B()!==t&&an();return}}if(St!==null&&!c){let at;S=!0;try{at=await Ut(xt,{peek:!0})}catch{if(h||a)return;const ie=ce[Math.min(Ht,ce.length-1)];Ht++,K=setTimeout(()=>{K=null,Fe()},ie);return}finally{S=!1}if(h||a)return;if(Ro(at),!u){(B()!==t||Pt)&&an();return}}const p=e.soloText?.();if(p===void 0||p===t)return es();const k=T.text.toString(),m=le(t,k,p);if(m.ok)return es(()=>T.applySplices(qr(k,m.text)));g=!0,(w===null||_!==p)&&(w=I(),_=p),y=!0;let A;try{A=await hn(p,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==p?(w=null,_=null,Fe()):es(()=>{t=T.text.toString()});const C=A.err;if(C instanceof ht&&!(C.status>=500||C.status===429))return;const V=ce[Math.min(Ht,ce.length-1)];Ht++,K=setTimeout(()=>{K=null,Fe()},V)},T=new Lh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),p=>{u=p==="live",p==="solo"&&(l=!0),u&&(st&&clearTimeout(st),st=null,ve(),a||Fe(),ot=tt,d&&(d=0,e.onPending?.(0))),e.onCollab?.(p)},()=>{a?e.onReady(T):Oe=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),hr=(p,k)=>{const m=a?T.text.toString():null;if(m!==null&&lr(m),!T.isRemote(k?.origin)){if(U("dirty"),a){bt=!0,Re=m,Jt+=1,u||(tt+=1,d=tt-ot,e.onPending?.(d),clearTimeout(st??void 0),st=setTimeout(()=>{st=null,!u&&!h&&re(!1)},Kr)),Mo();return}an()}};T.text.observe(hr);const ur=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",ur),Rh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const B=()=>f!==null?f:fr()?T.text.toString():e.soloText?.()??"",fr=()=>a||l&&T.text.length>0,Rt=p=>{p&&(n=p)},No=(p,k,m)=>{if(m?.held)return s(p,k),"same";if(p===t||p===_t)return Rt(k),"same";const A=B();if(p===A)return s(p,k),a&&(Ue(),U("clean")),"same";if(a){const V=t;return Tt.includes(p)||ps(V,p,A)?(s(p,k),bt&&(Re===null||p===Re||ps(V,Re,p))&&(Ue(),U("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(p,k),zt(p),Ue(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const C=le(t,p,A);return C.ok?(_t!==null&&(Me=!0),s(p,k),zt(C.text),C.text!==p?an():_t===null&&U("clean"),C.text===A?"same":"merged"):"blocked"};let un=null;const $o=()=>{if(!a)return Ne();if(P||h)return Promise.resolve();if(!u)return d>0?re(!1):Promise.resolve();if(!bt)return Promise.resolve();if(un)return un;const p=Jt;U("saving");const k=(async()=>{try{const m=await Ut(xt,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),Kn(p),U(bt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof ht&&m.status===422&&yn(m)&&(clearTimeout(Ot??void 0),Ot=null,$e(B()),P))return;U(bt?"dirty":"clean")}finally{un=null}})();return un=k,k};let Et=null;const fn=p=>()=>{Et===p&&(Et=null)},dr=(p,k)=>{if(P)return;if(a){const A=!u&&d>0;if(!A&&!(u&&bt))return;const C="room\0"+T.text.toString();if(Et===C)return;Et=C;const V=Jt;(A?re(!0):Ut(xt,{update:T.encodeState()},!0).then(ie=>Rt(ie.sha))).then(()=>Kn(V),fn(C));return}if(g||N){const A="park\0"+p;if(Et===A)return;Et=A;let C=w!==null&&_===p?w:null;for(const[V,at]of x)C===null&&at===p&&(C=V);C??=I(),dn(on(C),p,void 0,!1,!0).catch(fn(A));return}if(!p||p===t)return;const m="text\0"+p;if(Et!==m){if((l||c)&&!k){Ne();return}Et=m,l||c?dn(on(e.path),p,n,Lt,!0).catch(fn(m)):Ut(xt,o(p),!0).catch(fn(m))}},gr=()=>{h||dr(B(),!0)},pr=()=>{Et=null};return typeof window<"u"&&(window.addEventListener("pagehide",gr),window.addEventListener("pageshow",pr)),{collab:T,current:B,merge:No,rebase:Rt,saveNow:$o,askingShrink:()=>P!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",gr),window.removeEventListener("pageshow",pr)),clearTimeout(Yt??void 0),clearTimeout(Ot??void 0),ve(),clearTimeout(K??void 0),K=null;const p=B();h=!0,f=p,P?e.onShrinkWithdrawn?.(P):dr(p,!1),clearTimeout(st??void 0),T.awareness.off("change",ur),T.text.unobserve(hr),T.destroy()}}}export{ne as D,Xr as S,Gh as U,Yh as a,aa as b,da as c,qr as d,zh as e,Rs as f,ee as g,Ph as h,Ct as i,qh as m,Xh as o,Wh as r,Jh as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 5fca1cca..0d83db82 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + From 34193d0d331409ea081bf452124db2c70add1db6 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 21:41:03 +0900 Subject: [PATCH 03/34] fix(webapp): retry failed conflict-copy PUTs and park exit clashes server-side --- internal/webapp/frontend/src/api/http.ts | 26 +- .../webapp/frontend/src/lib/sharedfile.ts | 106 ++++++-- .../src/lib/sharedfile_restore.test.ts | 239 +++++++++++++++++- ...{Editor-DHvYAyxu.js => Editor-2j3g1r__.js} | 2 +- ...dit-BYnijXna.js => VisualEdit-B7FU_dFL.js} | 2 +- .../{index-BROkyUpj.js => index-xYv7N57r.js} | 44 ++-- .../static/assets/sharedfile-jBqmYsT3.js | 16 -- .../static/assets/sharedfile-s3I9dExU.js | 16 ++ internal/webapp/static/index.html | 2 +- internal/webapp/upload.go | 127 +++++++++- internal/webapp/upload_landed_test.go | 198 +++++++++++++++ internal/webapp/ycollab.go | 103 +++++++- internal/webapp/ycollab_sync_test.go | 105 ++++++++ 13 files changed, 900 insertions(+), 86 deletions(-) rename internal/webapp/static/assets/{Editor-DHvYAyxu.js => Editor-2j3g1r__.js} (99%) rename internal/webapp/static/assets/{VisualEdit-BYnijXna.js => VisualEdit-B7FU_dFL.js} (97%) rename internal/webapp/static/assets/{index-BROkyUpj.js => index-xYv7N57r.js} (75%) delete mode 100644 internal/webapp/static/assets/sharedfile-jBqmYsT3.js create mode 100644 internal/webapp/static/assets/sharedfile-s3I9dExU.js diff --git a/internal/webapp/frontend/src/api/http.ts b/internal/webapp/frontend/src/api/http.ts index a613f547..5884f6f2 100644 --- a/internal/webapp/frontend/src/api/http.ts +++ b/internal/webapp/frontend/src/api/http.ts @@ -246,15 +246,20 @@ export async function putText( // Outlive the page (a closing tab parking its buffer). Past the browser's // keepalive cap the request goes as an ordinary one, as syncCollab's does. keepalive = false, + // Leaving for good: a body the hub cannot merge is parked beside the file + // in this same request (`parked` names the copy), since a closing page + // never gets to send a second one. + parkOnConflict = false, // `merged`: the hub found the file had moved past `base` and folded this // body into it three ways (upload.go) — the file is NOT exactly `text`. -): Promise<{ sha?: string; merged?: boolean }> { +): Promise<{ sha?: string; merged?: boolean; parked?: string }> { const r = await fetch(url, { method: "PUT", headers: { "Content-Type": "text/plain; charset=utf-8", ...(base ? { "If-Match": base } : {}), ...(confirmShrink ? { "X-Bdrive-Confirm-Shrink": "1" } : {}), + ...(parkOnConflict ? { "X-Bdrive-Park-On-Conflict": "1" } : {}), }, body: text, keepalive: Boolean(keepalive && new TextEncoder().encode(text).byteLength <= KEEPALIVE_MAX_BYTES), @@ -263,7 +268,7 @@ export async function putText( if (r.status === 401 && !keepalive) toLogin(); if (!r.ok) await fail(r); trackWrite("PUT", url); - return (await r.json().catch(() => ({}))) as { sha?: string; merged?: boolean }; + return (await r.json().catch(() => ({}))) as { sha?: string; merged?: boolean; parked?: string }; } /* Write into a file's co-editing room over plain HTTP, for a client that is @@ -282,9 +287,20 @@ const KEEPALIVE_MAX_BYTES = 60_000; export async function syncCollab( url: string, - payload: { update?: string; base?: string; base_text?: string; text?: string; confirm_shrink?: boolean; peek?: boolean; prior_sent?: string[] }, + payload: { + update?: string; + base?: string; + base_text?: string; + text?: string; + confirm_shrink?: boolean; + peek?: boolean; + prior_sent?: string[]; + // A text that clashes with the room is parked beside the file by the hub + // in this same request, answered with `parked` (a closing page's flush). + park_on_conflict?: boolean; + }, keepalive = false, -): Promise<{ sha: string; text: string; merged?: boolean; update?: string }> { +): Promise<{ sha: string; text: string; merged?: boolean; update?: string; parked?: string }> { const body = JSON.stringify(payload); const bodyBytes = new TextEncoder().encode(body).byteLength; const r = await fetch(url, { @@ -294,5 +310,5 @@ export async function syncCollab( keepalive: Boolean(keepalive && bodyBytes <= KEEPALIVE_MAX_BYTES), }); if (!r.ok) await fail(r); - return (await r.json()) as { sha: string; text: string; merged?: boolean; update?: string }; + return (await r.json()) as { sha: string; text: string; merged?: boolean; update?: string; parked?: string }; } diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index d29b7f74..dc1eebac 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -241,6 +241,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { let waitingToJoin = false; let parkedName: string | null = null; let parkedText: string | null = null; // what `parkedName` was minted for + let parkedSha = ""; // the head `parkedText` clashed with, kept for a retry /* Every conflict copy this file opens gets a name no other copy from it has had: conflictName stamps whole UTC seconds, so each name is minted at least a second after the last. Two parks on the wire at once — a @@ -257,9 +258,10 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { const conflictPuts = new Map(); // Bumped per park: only the newest park moves `saved` when it lands. let conflictSeq = 0; - /* A staging checkpoint the room refused for a genuine clash, whose buffer - has not durably landed as a conflict copy yet. Sending it to the room - again on the way out would only be refused again: destroy() parks it. */ + /* A clash (a staging checkpoint the room refused, or a solo write the file + refused) whose buffer has not durably landed as a conflict copy yet. + Sending it again on the way out would only be refused again: destroy() + parks it, and the save loop's retry parks it again under the same name. */ let stagingConflict = false; let joinTimer: ReturnType | null = null; let joinAttempt = 0; @@ -429,11 +431,21 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } setState("saving"); opts.onWriting?.(); + if (stagingConflict) { + // A park that failed: retry that same copy before anything else, so + // the backoff timer re-sends the park rather than a write the hub + // will refuse again. Newer typing is a new attempt from scratch. + if (parkedName !== null && parkedText === text) { + if ((await parkConflict(text, parkedSha)) === "stop") return; + continue; + } + stagingConflict = false; + } const r = solo || noRoomHttp ? await sendFile(text) : await sendRoom(text); if (r === "stop") return; if (r === "rebased") { if (++rebases > MAX_REBASES) { - await preserve(current(), base ?? ""); + await parkConflict(current(), base ?? ""); return; } continue; @@ -516,10 +528,10 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { const res = merge3(from, head.text, cur); if (!res.ok || !applyText(res.text)) { // The same words changed two different ways: genuinely contended. - // Theirs is the file (it got there first); ours goes beside it. - if (landed) adopt(head.text, head.sha); - await preserve(cur, head.sha ?? ""); - return false; + // Theirs is the file (it got there first); ours goes beside it. Only + // the head moves now: `saved` moves when the copy durably lands. + if (landed) rebase(head.sha); + return (await parkConflict(cur, head.sha ?? "")) === "rebased"; } adopt(head.text, head.sha); if (landed) opts.onSaved?.(head.text); @@ -604,18 +616,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { return "rebased"; } } - stagingConflict = true; - const parked = current(); - const failed = await preserve(parked, theirs.sha ?? ""); - if (gone) return "stop"; // destroy() parked the buffer itself - if (failed) { - retryAfterFailure(failed.err); - return "stop"; - } - stagingConflict = false; - // Typing that landed while the copy was on the wire is not in it: - // it goes to the room, built on what was parked. - return current() !== parked ? "rebased" : "stop"; + return parkConflict(current(), theirs.sha ?? ""); } setState(hubHoldsIt ? "dirty" : "error"); retryAfterFailure(e); @@ -776,6 +777,36 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } }; + /* Park `parked` beside the file after a clash with head `theirSha`. One + name per text: a retry re-writes the same copy. Until it lands the clash + is unparked (`stagingConflict`), so leaving parks it keepalive, and a + transient failure re-arms the save loop, which retries this park. */ + const parkConflict = async (parked: string, theirSha: string): Promise<"rebased" | "stop"> => { + if (parkedName === null || parkedText !== parked) { + parkedName = mintConflictPath(); + parkedText = parked; + } + const name = parkedName; + parkedSha = theirSha; + stagingConflict = true; + const failed = await preserve(parked, theirSha, name); + if (gone) return "stop"; // destroy() parked the buffer itself + if (failed) { + retryAfterFailure(failed.err); + return "stop"; + } + stagingConflict = false; + // A newer park (a join's, over newer typing) keeps its own name. + if (parkedName === name) { + parkedName = null; + parkedText = null; + parkedSha = ""; + } + // Typing that landed while the copy was on the wire is not in it: it is + // sent next, built on what was parked. + return current() !== parked ? "rebased" : "stop"; + }; + /* Edits made while a held room's socket is down live only in this tab's Y.Doc. If the socket stays away, hand them to the hub as a Yjs update: applying it to the room is idempotent, so the reconnect that eventually @@ -1251,10 +1282,41 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { return; } exitSent = key; + const from = saved; + /* The page is going and will not get to send a second request, so this + one asks the hub to park a clash beside the file itself and answers + with the copy (`parked`). An older hub refuses 409 instead: if its head + already holds our edit there is nothing to keep; otherwise the words + are parked from here, as long as the page lives to send it. */ + const onExitError = (e: unknown) => { + if (!(e instanceof HttpError && e.status === 409)) return exitFailed(key)(); + let theirs: { text?: unknown } = {}; + try { + const parsed: unknown = JSON.parse(e.body); + if (parsed && typeof parsed === "object") theirs = parsed as typeof theirs; + } catch { + // an older hub, or a body we cannot read: park + } + if (typeof theirs.text === "string" && (theirs.text === text || retainsChanges(from, text, theirs.text))) return; + stagingConflict = true; + let copy = parkedName !== null && parkedText === text ? parkedName : null; + for (const [path, held] of conflictPuts) if (copy === null && held === text) copy = path; + copy ??= mintConflictPath(); + parkedName = copy; + parkedText = text; + const parkedCopy = copy; + void putText(contentURL(parkedCopy), text, undefined, false, true).then(() => { + stagingConflict = false; + opts.onConflictCopy?.(parkedCopy); + }, exitFailed(key)); + }; + const landed = (out: { parked?: string }) => { + if (out.parked) opts.onConflictCopy?.(out.parked); + }; if (solo || noRoomHttp) { - void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true).catch(exitFailed(key)); + void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true, true).then(landed, onExitError); } else { - void syncCollab(syncURL, roomPayload(text), true).catch(exitFailed(key)); + void syncCollab(syncURL, { ...roomPayload(text), park_on_conflict: true }, true).then(landed, onExitError); } }; const onPageHide = () => { diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 136093d1..6a3c9d00 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -840,6 +840,237 @@ test("staging 409 park and join park in the same second never share a conflict p } }); +/* Solo: a PUT refused 409 whose head clashes is parked beside the file. A + park refused 503 keeps the buffer unsaved ("error") and is retried on the + save backoff onto the SAME copy, with no new typing and no new write to the + file; closing the file while that retry waits parks it there keepalive. */ +for (const closeBeforeRetry of [false, true]) { + test(`solo 409 clash: a park refused 503 is retried onto the same copy (close before retry: ${closeBeforeRetry})`, async () => { + fakeTimers(); + try { + const puts: Array<{ url: string; body: string; keepalive?: boolean }> = []; + let copyAnswer = 503; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = decodeURIComponent(String(url)); + const method = init?.method ?? "GET"; + if (method === "GET") return new Response("Z\n", { status: 200, headers: { ETag: `"sha-z"` } }); + puts.push({ url: u, body: String(init?.body), keepalive: init?.keepalive }); + if (u.includes("bdrive-conflict")) { + if (copyAnswer !== 200) return new Response("unavailable", { status: copyAnswer }); + return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + } + return new Response(JSON.stringify({ error: "changed", sha: "sha-z" }), { status: 409 }); + }) as typeof fetch; + + let buffer = "A\n"; + let solo = false; + const states: string[] = []; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/", // no co-editing route: solo, saved with If-Match + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onState: (s) => states.push(s), + onConflictCopy: (c) => copies.push(c), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "B\n"; + await file.saveNow(); + // The file refused it, the head clashes, and the park was refused. + assert.equal(puts.length, 2); + assert.ok(!puts[0].url.includes("bdrive-conflict")); + assert.ok(puts[1].url.includes("notes.md.bdrive-conflict-")); + assert.equal(puts[1].body, "B\n"); + assert.equal(states.at(-1), "error"); + same(copies, []); + + copyAnswer = 200; + if (closeBeforeRetry) { + file.destroy(); + assert.equal(puts.length, 3); + assert.equal(puts[2].url, puts[1].url); + assert.equal(puts[2].body, "B\n"); + assert.equal(puts[2].keepalive, true); + await advance(60_000); + assert.equal(puts.length, 3); + return; + } + + // No typing: the backoff alone re-sends the park, to the same path. + await advance(SAVE_RETRY_MS[0]); + assert.equal(puts.length, 3); + assert.equal(puts[2].url, puts[1].url); + assert.equal(puts[2].body, "B\n"); + assert.equal(copies.length, 1); + assert.ok(puts[2].url.includes(copies[0])); + assert.equal(states.at(-1), "clean"); + + // Parked: nothing more is sent. + await advance(60_000); + assert.equal(puts.length, 3); + file.destroy(); + assert.equal(puts.length, 3); + } finally { + realTimers(); + } + }); +} + +/* The page is going: its last flush asks the hub to park a clash itself, in + the same request — a discarded page never runs the JS that would send a + second one. An older hub refuses 409 instead, and a page still alive parks + from here, keepalive. A head that already carries our edit needs no copy. */ +test("staging pagehide asks the hub to park a clash in the same request", async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v1 conflict\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.posts.length, 1); + same(h.posts[0], { base: "sha-0", base_text: "v0\n", text: "v1 conflict\n", park_on_conflict: true }); + const parked = "notes.md.bdrive-conflict-tester-20261111-102030"; + h.roomAnswers[0].resolve(h.ok({ ok: true, path: "notes.md", sha: "sha-room", text: "v1 theirs\n", parked })); + await advance(0); + same(h.copies, [parked]); + same(h.puts, []); // one round trip: nothing parked from here + h.file.destroy(); + await advance(60_000); + assert.equal(h.posts.length, 1); + same(h.puts, []); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("staging pagehide refused 409 by an older hub parks the buffer keepalive at once", async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v1 conflict\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.posts.length, 1); + same(h.posts[0], { base: "sha-0", base_text: "v0\n", text: "v1 conflict\n", park_on_conflict: true }); + h.roomAnswers[0].resolve(h.clash()); + await advance(0); + assert.equal(h.puts.length, 1); + assert.ok(h.puts[0].url.includes("notes.md.bdrive-conflict-tester-")); + assert.equal(h.puts[0].body, "v1 conflict\n"); + assert.equal(h.puts[0].keepalive, true); + h.putAnswers[0].resolve(h.ok({ sha: "sha-copy" })); + await advance(0); + assert.equal(h.copies.length, 1); + assert.ok(h.puts[0].url.includes(h.copies[0])); + h.file.destroy(); + await advance(60_000); + assert.equal(h.posts.length, 1); + assert.equal(h.puts.length, 1); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("staging pagehide refused 409 by a head that already holds the edit parks nothing", async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const h = stagingConflictHarness(); + try { + // Our edit inserted a line; the room holds it, with a line after it. + h.state.buffer = "v0\nv1 mine\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.posts.length, 1); + h.roomAnswers[0].resolve( + new Response(JSON.stringify({ error: "changed", sha: "sha-room", text: "v0\nv1 mine\nmore\n" }), { status: 409 }), + ); + await advance(0); + same(h.puts, []); + same(h.copies, []); + h.file.destroy(); + same(h.puts, []); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +for (const hubParks of [true, false]) { + test(`solo pagehide PUT asks the hub to park a clash (${hubParks ? "hub parks it" : "older hub: 409, parked from here"})`, async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + try { + const parked = "notes.md.bdrive-conflict-browser-20261111-102030"; + const puts: Array<{ url: string; body: string; keepalive?: boolean; park?: string }> = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = decodeURIComponent(String(url)); + const headers = (init?.headers ?? {}) as Record; + puts.push({ url: u, body: String(init?.body), keepalive: init?.keepalive, park: headers["X-Bdrive-Park-On-Conflict"] }); + if (u.includes("bdrive-conflict")) return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + if (hubParks) return new Response(JSON.stringify({ ok: true, path: "notes.md", sha: "sha-z", parked }), { status: 200 }); + return new Response(JSON.stringify({ error: "changed", sha: "sha-z" }), { status: 409 }); + }) as typeof fetch; + let buffer = "A\n"; + let solo = false; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/", + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onConflictCopy: (c) => copies.push(c), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "B\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(puts.length, 1); + assert.ok(puts[0].url.includes("upload/content?path=notes.md")); + assert.equal(puts[0].keepalive, true); + assert.equal(puts[0].park, "1"); + await advance(0); + if (hubParks) { + assert.equal(puts.length, 1); // one round trip + same(copies, [parked]); + } else { + assert.equal(puts.length, 2); + assert.ok(puts[1].url.includes("notes.md.bdrive-conflict-")); + assert.equal(puts[1].body, "B\n"); + assert.equal(puts[1].keepalive, true); + assert.equal(puts[1].park, undefined); + assert.equal(copies.length, 1); + } + const sent = puts.length; + file.destroy(); + await advance(60_000); + assert.equal(puts.length, sent); + } finally { + realTimers(); + } + }); +} + /* R11: the socket syncs while a staging checkpoint is still on the wire. The room applies the checkpoint (its own item IDs), and the same items reach this tab twice — in the HTTP answer's `update` and on the socket. The join @@ -1316,9 +1547,11 @@ for (const { mode, dirty } of [ } else { assert.equal(r.method, "POST"); assert.ok(r.url.includes("ycollab/sync?path=notes.md")); - const body = JSON.parse(r.body) as { update?: string; text?: string }; - if (mode === "staging") assert.equal(body.text, "a\nb\nc\nlast words\n"); - else assert.equal(typeof body.update, "string"); + const body = JSON.parse(r.body) as { update?: string; text?: string; park_on_conflict?: boolean }; + if (mode === "staging") { + assert.equal(body.text, "a\nb\nc\nlast words\n"); + assert.equal(body.park_on_conflict, true); + } else assert.equal(typeof body.update, "string"); } } diff --git a/internal/webapp/static/assets/Editor-DHvYAyxu.js b/internal/webapp/static/assets/Editor-2j3g1r__.js similarity index 99% rename from internal/webapp/static/assets/Editor-DHvYAyxu.js rename to internal/webapp/static/assets/Editor-2j3g1r__.js index 966aadd1..4c79d9b2 100644 --- a/internal/webapp/static/assets/Editor-DHvYAyxu.js +++ b/internal/webapp/static/assets/Editor-2j3g1r__.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BROkyUpj.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-jBqmYsT3.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-xYv7N57r.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-s3I9dExU.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-BYnijXna.js b/internal/webapp/static/assets/VisualEdit-B7FU_dFL.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-BYnijXna.js rename to internal/webapp/static/assets/VisualEdit-B7FU_dFL.js index 9f8fa6d4..5823eb68 100644 --- a/internal/webapp/static/assets/VisualEdit-BYnijXna.js +++ b/internal/webapp/static/assets/VisualEdit-B7FU_dFL.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-BROkyUpj.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-jBqmYsT3.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-xYv7N57r.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-s3I9dExU.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-BROkyUpj.js b/internal/webapp/static/assets/index-xYv7N57r.js similarity index 75% rename from internal/webapp/static/assets/index-BROkyUpj.js rename to internal/webapp/static/assets/index-xYv7N57r.js index 24094d4f..0deb497c 100644 --- a/internal/webapp/static/assets/index-BROkyUpj.js +++ b/internal/webapp/static/assets/index-xYv7N57r.js @@ -1,13 +1,13 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DHvYAyxu.js","assets/sharedfile-jBqmYsT3.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-BYnijXna.js"])))=>i.map(i=>d[i]); -import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const u of o.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,o){var u=null;if(o!==void 0&&(u=""+o),i.key!==void 0&&(u=""+i.key),"key"in i){o={};for(var f in i)f!=="key"&&(o[f]=i[f])}else o=i;return i=o.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:o}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var l=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1i.map(i=>d[i]); +import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1p||F[d]!==ne[p]){var ce=` `+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function lt(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function hn(s){try{var a="",c=null;do a+=lt(s,c),c=s,s=s.return;while(s);return a}catch(d){return` Error generating stack: `+d.message+` -`+d.stack}}var Nt=Object.prototype.hasOwnProperty,Ct=e.unstable_scheduleCallback,mn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function vt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function yt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function _t(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function wt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),wt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return wt(J,G,Vc(te),ue);if(te.$$typeof===R)return wt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=wt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var wt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(wt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(wt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Et===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Et.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[sn]=s,a[kn]=c}catch(v){pt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[sn]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kwt&&(C=wt,wt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,wt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>wt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(_t(s,2),Js(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),_t(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(_t(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return Ct(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||vt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:o,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||o&&!o(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(o))return!1}else if(!Vl(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const o=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,o)=>{e=i,t=o});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const o=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{o(()=>{f(...h)})},schedule:o,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),o=()=>i.status!=="pending",u=S=>{if(!o()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{o()||(r?.(),i.resolve(S))},w=S=>{o()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(o()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,o()||e.onContinue?.()}),j=()=>{if(o())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(o())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&o.length){const j=i==="backward",S=j?YS:Ap,E={pages:o,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??o.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,o=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===o?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const o=new Set(i??this.#p);return this.options.throwOnError&&o.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&o.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:o,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:o&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,u)=>{this.#a({type:"failed",failureCount:o,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const o=await this.#s.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#a({type:"success",data:o}),o}catch(o){try{await this.#n.config.onError?.(o,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(o,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,o,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:o}),o}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(o){Promise.reject(o)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(o){Promise.reject(o)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(o){Promise.reject(o)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(o){Promise.reject(o)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let o=this.get(i);return o||(o=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(r.queryHash)?.state.data,u=aM(t,o);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,n);return n.throwOnError||(o=o.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),o=fn(),u=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=o.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!o.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(o,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1){const o=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return o.status===401&&!i&&Bd(),o.ok||await ko(o),qd("PUT",e),await o.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return o.ok||await ko(o),await o.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const o=yw(i,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let i=0;i{let{children:i,...o}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(o,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...f)=>{const h=o(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,o)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(h,{...f,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>l.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(o,u){const f=b.createContext(u);f.displayName=o+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return l.jsx(S.Provider,{value:E,children:x})};m.displayName=o+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${o}\``)}return[m,y]}const i=()=>{const o=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||o;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(o)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return l.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=o(f,_),T=Kt(E,R.collectionRef);return l.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=o(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),l.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=o(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else o(y)},[f,e,o,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),o=b.useRef(t);return uT(()=>{o.current=t},[t]),b.useEffect(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),o=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:o}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),o=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(o.current=u.current??Rl(r.current),u.current=void 0):o.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=o.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(o.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const o=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{o?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),l.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),l.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...o].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,o,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=o=>{o.target&&!r.current&&cj(ST,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,o):i.dispatchEvent(o)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(o),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return l.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,o]=b.useState(!1);ir(()=>o(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(l.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,o=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` +`+d.stack}}var Nt=Object.prototype.hasOwnProperty,Ct=e.unstable_scheduleCallback,mn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function vt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function yt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function _t(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function wt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),wt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return wt(J,G,Vc(te),ue);if(te.$$typeof===R)return wt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=wt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var wt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(wt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(wt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Et===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Et.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[sn]=s,a[kn]=c}catch(v){pt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[sn]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kwt&&(C=wt,wt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,wt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>wt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(_t(s,2),Js(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),_t(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(_t(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return Ct(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||vt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1){const u=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return u.status===401&&!i&&Bd(),u.ok||await ko(u),qd("PUT",e),await u.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` .`.concat(FT,` { overflow: hidden `).concat(r,`; padding-right: `).concat(f,"px ").concat(r,`; @@ -17,7 +17,7 @@ Error generating stack: `+d.message+` overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` padding-left: `.concat(i,`px; - padding-top: `).concat(o,`px; + padding-top: `).concat(l,`px; padding-right: `).concat(u,`px; margin-left:0; margin-top:0; @@ -44,15 +44,15 @@ Error generating stack: `+d.message+` body[`).concat(yo,`] { `).concat(IT,": ").concat(f,`px; } -`)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var o=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(o,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var o=yj(e,r),u=o[1],f=o[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var o=dO(e,window.getComputedStyle(t).direction),u=o*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-o*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return` +`)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return` .block-interactivity-`.concat(e,` {pointer-events: none;} .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},pO=0,oo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],o=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==o)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(o),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==o}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(o,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var o=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(o.get(w)||0)+1;lo.set(w,S),o.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=o.get(g)-1;lo.set(g,w),o.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:o,caller:Yd});return l.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),o=Kt(t,i.triggerRef);return l.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:o,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=qs(Kg,t);return l.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=qs(xd,e.__scopeDialog);return o.modal?l.jsx(fr,{present:r||o.open,children:l.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),o=_T(),u=Kt(t,o);return l.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:l.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=qs(Co,e.__scopeDialog);return l.jsx(fr,{present:r||o.open,children:o.modal?l.jsx(NO,{...i,ref:t}):l.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const o=r.current;if(o)return bj(o)},[]),l.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,o=>{const u=o.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&o.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return l.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=o.target;n.triggerRef.current?.contains(u)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,...u}=e,f=qs(Co,n);return dj(),l.jsx(l.Fragment,{children:l.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:l.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return l.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return l.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return l.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let u,f;if("borderBoxSize"in o){const h=o.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),o=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let o=LO(Ea(e),n==="start",r);return i&&(o=o.map(u=>u+"-"+i),t&&(o=o.concat(o.map(Fp)))),o}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const o=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=o==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:o,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(E)))==null||n?E:E.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(f.floating)),T=await(o.isElement==null?void 0:o.isElement(R))&&await(o.getScale==null?void 0:o.getScale(R))||{x:1,y:1},A=Sd(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:o,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=o.reference[j]+o.reference[x]-w[x]-o.floating[j],A=w[x]-o.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||o.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&o.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=o.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...o,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...o,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=o&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:o+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await o.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:o,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:o},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:o}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(o.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(o.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(o){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),o=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==o||bd(r)!==u;return f&&(n=o,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Lj(t);let u=(o?bd(n.width):n.width)/r,f=(o?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(o,n,r)?$j(o):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(o&&r){const w=Xn(o),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&o)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!o)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!o?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(o+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),o=Br(e),u=i.visualViewport;let f=o.clientWidth,h=o.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(o)<=0){const w=o.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(o.clientWidth-x.clientWidth-S),_=getComputedStyle(o).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=xo(e),u=e.clientWidth*o.x,f=e.clientHeight*o.y,h=i*o.x,m=r*o.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const o=ur(e).position==="fixed";let u=o?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:o?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:o.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||o?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),o&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,o):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),o&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},o={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:o})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const o=i[r];if(!(o==="_owner"&&e.$$typeof)&&!jd(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:o,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=o||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...o}=e;return l.jsx(ot.svg,{...o,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:l.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[o,u]=b.useState(void 0);return l.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=qj(Gj,n),u=b.useRef(null),f=o.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=o.placementState&&iv(o.placementState),w=g?.[0],x=g?.[1];return r?null:l.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:o="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(o!=="center"?"-"+o:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ht}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),l.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:l.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:l.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,o=IA(Yj,r),u=PA[o.placedSide];return l.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:l.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>l.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:l.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:l.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:o,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(o),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),l.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:l.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:u,...f}=e,h=us(),m=o||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),l.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:l.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(o),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),l.jsx(Xj,{...f,children:l.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:l.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return l.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=Si(lv,t);return l.jsx(mD,{scope:t,forceMount:n,children:l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return l.jsx(Gl.Provider,{scope:e.__scopeMenu,children:l.jsx(fr,{present:r||o.open,children:l.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?l.jsx(gD,{...i,ref:t}):l.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const o=r.current;if(o)return bj(o)},[]),l.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return l.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return l.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:l.jsx(be,{...$,children:l.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(o,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:l.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:l.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:l.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,o),m=b.useRef(!1),y=()=>{const g=o.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return l.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[o.children]),l.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:l.jsx(rD,{asChild:!0,...f,focusable:!r,children:l.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return l.jsx(wC,{scope:e.__scopeMenu,checked:n,children:l.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=Vr(r);return l.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:o,children:l.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),o=n===i.value;return l.jsx(wC,{scope:e.__scopeMenu,checked:o,children:l.jsx(rf,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":hv(o),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=CD(fv,n);return l.jsx(fr,{present:r||_d(o.checked)||o.checked===!0,children:l.jsx(ot.span,{...i,ref:t,"data-state":hv(o.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return l.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return l.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),o=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=o,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return l.jsx(ov,{asChild:!0,...m,children:l.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{o.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(o.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];o.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(w),w.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||o.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...o}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return l.jsx(Gl.Provider,{scope:e.__scopeMenu,children:l.jsx(fr,{present:r||u.open,children:l.jsx(Gl.Slot,{scope:e.__scopeMenu,children:l.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...o,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let u=RD(e,Math.max(o,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,u=t.length-1;or!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:o,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return l.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:l.jsx(MC,{...y,dir:o,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,o=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{o.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),o.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),l.jsxs(l.Fragment,{children:[l.jsx(TC,{...u,virtualRef:m}),l.jsx(ot.span,{"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),o.open&&o.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return l.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),o=Pn(n),u=b.useRef(!1);return l.jsx(AC,{...o,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return l.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:o??!1,onChange:u,caller:of});return l.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:l.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=e_(n_,n),u=Un(n),f=Kt(t,o.triggerRef);return l.jsx(TC,{asChild:!0,...u,children:l.jsx(ot.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(o.onOpenToggle(),o.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&o.onOpenToggle(),h.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return l.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),o=Un(n),u=b.useRef(!1);return l.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return l.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>l.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,o=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return l.jsx(ot.div,{"data-orientation":o,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),l.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:o})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),o?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),l.jsx(Xj,{...m,children:l.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),o=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),l.jsx(Wj,{asChild:!0,...u,children:l.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=oc(pv,t);return l.jsx(Gz,{scope:t,forceMount:n,children:l.jsx(fr,{present:n||o.open,children:l.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,u=oc(_o,e.__scopeTooltip);return l.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?l.jsx(w_,{side:i,...o,ref:t}):l.jsx(Zz,{side:i,...o,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),o=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),l.jsx(w_,{...e,ref:o})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),l.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:l.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[l.jsx(Xz,{children:r}),l.jsx(Yz,{scope:n,isInside:!0,children:l.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:l.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,i,o)){case o:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,u=t.length-1;or!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const o=t[t.length-1],u=t[t.length-2];if((o.x-u.x)*(i.y-u.y)>=(o.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const o=n[n.length-1],u=n[n.length-2];if((o.x-u.x)*(i.y-u.y)>=(o.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],o=n.nextPart.get(i);if(o){const m=N_(e,t+1,o);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let o=0;o{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),o=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let o=0;o"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(o,u)=>{n[o]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(o){let u=n[o];if(u!==void 0)return u;if((u=r[o])!==void 0)return i(o,u),u},set(o,u){o in n?n[o]=u:i(o,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const o=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(o,x,w,j)};if(t){const i=t+Gw,o=r;r=u=>u.startsWith(i)?o(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=o=>n({className:o,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let o=0;o0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:o(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,o;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,o=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return o=u,(...h)=>o(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),o=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ht=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[o,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return l.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return l.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return l.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return l.jsx(o4,{children:l.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,l.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:o,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!o&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(o)?o:[o]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},o)=>b.createElement(f3,{ref:o,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const o=document.getElementById("main");o&&(n&&t?o.setAttribute("inert",""):o.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,o=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-o),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,o=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!o)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+o);od(f),np(f)};return l.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?l.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return l.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return l.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[l.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),l.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),l.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return l.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return l.jsxs(l.Fragment,{children:[l.jsx("div",{id:"sb-backdrop",onClick:ds}),l.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??l.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,l.jsx(iL,{}),l.jsx("div",{id:"rail",children:e.rail??l.jsx(oE,{})})]}),l.jsxs("main",{id:"main",children:[e.topbar,e.exit,l.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return l.jsxs(l.Fragment,{children:[e??l.jsx("span",{className:"rail-mark",children:l.jsx(Sv,{size:20})}),l.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return l.jsxs(uf,{delayDuration:100,children:[l.jsx(df,{asChild:!0,children:l.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[l.jsx(ge,{name:e.icon}),e.badge?l.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),l.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&l.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return l.jsxs("header",{id:"vault",children:[l.jsx("span",{id:"vault-badge",children:l.jsx(Sv,{size:22})}),l.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:o=>{n&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())},children:t}),i&&l.jsx("span",{id:"vault-beta",children:"Beta"}),r&&l.jsx("div",{className:"vault-actions",children:l.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:l.jsx(ge,{name:"power"})})})]})}function ci(e){return l.jsxs("header",{id:"topbar",children:[l.jsxs(uf,{delayDuration:150,children:[l.jsx(df,{asChild:!0,children:l.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:l.jsx(ge,{name:"sidebar"})})}),l.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",l.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,l.jsx("span",{id:"crumb",children:e.crumb}),l.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,o=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===o),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),u?this.toasts=this.toasts.map(h=>h.id===o?(this.publish({...h,...t,id:o,title:r}),{...h,...t,id:o,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:o}),o},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let o=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))o=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){o=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){o=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){o=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){o=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{o&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,o,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ht,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),lt=ye.useRef(g.duration||Y||Jw),hn=ye.useRef(null),Nt=ye.useRef(null),Ct=_===0,mn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,vt,yt)=>yt>=hs?ze:ze+vt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{lt.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=Nt.current;if(ze){const vt=ze.getBoundingClientRect().height;return Fe(vt),j(yt=>[{toastId:g.id,height:vt,position:g.position},...yt]),()=>j(yt=>yt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=Nt.current,vt=ze.style.height;ze.style.height="auto";const yt=ze.getBoundingClientRect().height;ze.style.height=vt,Fe(yt),j(Vt=>Vt.find(_t=>_t.toastId===g.id)?Vt.map(_t=>_t.toastId===g.id?{..._t,height:yt}:_t):[{toastId:g.id,height:yt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(vt=>vt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},lt.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var vt;return ye.createElement("div",{className:tr($?.loader,g==null||(vt=g.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":mn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":Ct,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(hn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,vt,yt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=Nt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((vt=Nt.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_t=new Date().getTime()-((yt=hn.current)==null?void 0:yt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/_t;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var nn,Nn;(nn=Nt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(Nn=Nt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var vt,yt,Vt;if(!Q.current||!An||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const _t=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(_t)>1)&&K(Math.abs(En)>Math.abs(_t)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&_t<0||nn.includes("bottom")&&_t>0)Nn.y=_t;else{const Jn=_t*gr(_t);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(yt=Nt.current)==null||yt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=Nt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(o=g.classNames)==null?void 0:o.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const o=i===1,u=o?"--mobile-offset":"--offset",f=o?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:o="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([o].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,o]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return l.jsx(zL,{theme:t,className:"toaster group",icons:{success:l.jsx(B3,{className:"size-4"}),info:l.jsx(I5,{className:"size-4"}),warning:l.jsx(tE,{className:"size-4"}),error:l.jsx(g6,{className:"size-4"}),loading:l.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return l.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:o}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=o?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...o,...f}[S]):{...o,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const o=r?YM:"button";return l.jsx(o,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return l.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return l.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return l.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return l.jsxs(BL,{"data-slot":"dialog-portal",children:[l.jsx(GL,{}),l.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&l.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[l.jsx(nE,{}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return l.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return l.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(o=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:o}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return l.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:l.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?l.jsx(YL,{m:e}):l.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[o,u]=b.useState(e.value),f=e.match===void 0||o.trim()===e.match,h=()=>{const m=o;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return l.jsxs(l.Fragment,{children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.title})}),l.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),l.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:o,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&l.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),l.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return l.jsxs(l.Fragment,{children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.title})}),l.jsx("div",{className:"modal-msg",children:e.message}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),l.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,o=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{o(e.keep)};return l.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:l.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[l.jsxs("div",{className:"sd-head",children:[l.jsx("span",{className:"sd-icon","aria-hidden":"true",children:l.jsx(ge,{name:"shield"})}),l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),l.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),l.jsxs("div",{className:"sd-compare",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Saved version"}),l.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Your editor"}),l.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),l.jsxs("div",{className:"modal-actions sd-actions",children:[l.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),l.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{o(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",o=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),o&&(u.connect=o),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),o=i.path.indexOf("/"),u=o===-1?i.path:i.path.slice(0,o);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=o===-1?"":i.path.slice(o+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const o=vE(e),u=o&&i?"edit/"+o:o,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(o=>{n.push(o);const u=t(o);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return o=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(o);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Xn(l),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(ot.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ht}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(ot.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(ot.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Un(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(ot.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(ot.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ht=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ht,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),lt=ye.useRef(g.duration||Y||Jw),hn=ye.useRef(null),Nt=ye.useRef(null),Ct=_===0,mn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,vt,yt)=>yt>=hs?ze:ze+vt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{lt.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=Nt.current;if(ze){const vt=ze.getBoundingClientRect().height;return Fe(vt),j(yt=>[{toastId:g.id,height:vt,position:g.position},...yt]),()=>j(yt=>yt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=Nt.current,vt=ze.style.height;ze.style.height="auto";const yt=ze.getBoundingClientRect().height;ze.style.height=vt,Fe(yt),j(Vt=>Vt.find(_t=>_t.toastId===g.id)?Vt.map(_t=>_t.toastId===g.id?{..._t,height:yt}:_t):[{toastId:g.id,height:yt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(vt=>vt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},lt.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var vt;return ye.createElement("div",{className:tr($?.loader,g==null||(vt=g.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":mn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":Ct,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(hn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,vt,yt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=Nt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((vt=Nt.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_t=new Date().getTime()-((yt=hn.current)==null?void 0:yt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/_t;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var nn,Nn;(nn=Nt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(Nn=Nt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var vt,yt,Vt;if(!Q.current||!An||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const _t=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(_t)>1)&&K(Math.abs(En)>Math.abs(_t)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&_t<0||nn.includes("bottom")&&_t>0)Nn.y=_t;else{const Jn=_t*gr(_t);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(yt=Nt.current)==null||yt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=Nt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=o.getValue())!=null?u:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,o],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(o,n,t,e)},{}),o}function h$(e,t,n,r){var i,o;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(o=f.id)!=null?o:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(o),u},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(o,e)}),o}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var o,u;const f=(o=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?o:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(i!=null&&i.includes(o.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const o=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,o,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const o=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,o,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,o,u,f,h,m;return[...(i=(o=t[0])==null?void 0:o.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,o;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(o=h[0])==null?void 0:o.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,o,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const o=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(o))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const o=e.getValue(t);return o>=r&&o<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(o>u){const f=o;o=u,u=f}return[o,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),o=r?.find(y=>y.id===e.id),u=Sa(n,o?o.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(o){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var o;return(o=Sa(t,i))==null?void 0:o.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const o=i.getValue(e);return r+(typeof o=="number"?o:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(r=o)&&(r=o)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(o=>{const u=o.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let o=i.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((o,u)=>o-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(u=>u.id===o)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let o=[];if(!(t!=null&&t.length))o=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&o.push(f.splice(m,1)[0])}o=[...o,...f]}return k$(o,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var o,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((o=i?.left)!=null?o:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,o,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((o=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,o=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return o?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const o=[...r??[],...i??[]];return n.filter(u=>!o.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(u=>u.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(u=>u.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,o;return!!((i=r.left)!=null&&i.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(o=>!i.includes(o.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=o??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,o)=>i+o.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,o)=>i+o.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var o;n+=(o=i.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return o=>{if(!r||!i||(o.persist==null||o.persist(),ip(o)&&o.touches&&o.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(o)?Math.round(o.touches[0].clientX):o.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(o)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,o)=>({...i,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,o;e.setExpanded(r?{}:(i=(o=e.initialState)==null?void 0:o.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const u=o.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const o=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!o,!o&&n)return{...u,[e.id]:!0};if(o&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=o=>Sa(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let o=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,u)),{...i,pageIndex:o}})},e.resetPageIndex=r=>{var i,o;e.setPageIndex(r?eg:(i=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,o;e.setPageSize(r?tg:(i=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const o=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/o);return{...i,pageIndex:f,pageSize:o}})},e.setPageCount=r=>e.setPagination(i=>{var o;let u=Sa(r,(o=e.options.pageCount)!=null?o:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((o,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const o=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...o]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,o=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return o?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const o=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=o?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,o;return!!((i=r.top)!=null&&i.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(o=>!i.has(o.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):i.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(o=>{ng(i,o.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(o=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return o;const f={...o};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var o;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=u.subRows)!=null&&o.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},o=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:o(h.subRows)}),y)return h}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,o=!1;return e.subRows.forEach(u=>{if(!(o&&!i)&&(u.getCanSelect()&&(Dv(u,t)?o=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?o=!0:(f==="some"&&(o=!0),i=!1)}}),i?"all":o?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),o=r.shift(),u=parseInt(i,10),f=parseInt(o,10),h=[u,f].sort();if(isNaN(h[0])){if(i>o)return 1;if(o>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const o=i?.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return Tl.datetime;if(typeof o=="string"&&(r=!0,o.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=o?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(o||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const o=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const o=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(o,w):{...o,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...o,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,o,u){o===void 0&&(o=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],o=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};o.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(o=>$v.includes(o)))return n;const i=r.reduce((o,u)=>bn(o)?void 0:o[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",St=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),o=i.length,u=o-1;for(;++r{const i={};for(const o in e)Object.defineProperty(i,o,{get:()=>{const u=o;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),Re(n,o))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const o=n.get(e);if(o&&o.has(t))return!0;if(o)o.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const o=Re(e,i);if(o){const{_f:u,...f}=o;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return St(i,DE,t[n]),St(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,o)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(o?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,o=n[i];return r&&delete r[o],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const o of e)o.next&&o.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(o=>o!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],o=t[r];if(i&&Pt(i)&&o){const u=IE(i,o);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=o)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],o=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(o))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],o),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const o=e[i],u=r&&r[i];UE(o)&&(!Array.isArray(o)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(o,Array.isArray(o)?[]:{},u):ai(o,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(o,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const o of e){const u=Re(t,o);u&&St(i,o,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const o=i.join("."),u=Re(t,o),f=Re(e,o);if(u&&!Array.isArray(u)&&n!==o)return{name:n};if(f&&f.type)return{name:o,error:f};if(f&&f.root&&f.root.type)return{name:`${o}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...o}=e,u=Object.keys(o);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?St(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,o,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&St(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&St(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&St(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else St(o,z,Q)},H=(z,Q)=>{St(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=o,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(o,z)),Se=Re(o,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?St(o,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(o,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,o,void 0,r):Ee?Gt(n.dirtyFields,z):St(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(St(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?St(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(o,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):St(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:o,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&ht(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?ht(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,o,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):St(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&<(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&St(o,z,Q),!sr(u.mount?o:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?o:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?o:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&St(o,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?o:Bt(o)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(o,z),rt=sr(Ee,_e);if(rt||St(o,z,_e),Se)E.array.next({name:z,values:fe?o:Bt(o)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?o:Bt(o);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(o):z;if(!sr(o,X)){o={...o,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:o}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(o,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(St(o,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const yt=h[X];yt&&yt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),vt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(o)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),vt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:yt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(yt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(yt)}else A([X],!0),Se=(await v1(me,f.disabled,o,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?o:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;St(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...o};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),lt=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(o,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(o)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},hn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},Nt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return St(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?hn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;St(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},Ct=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),mn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(o);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),Ct(),setTimeout(Ct);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),St(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,o,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(o,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?St(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(o=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)St(o,_e,Re(xe,_e))}else o=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&o?ai(i,o,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(o):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:Nt,unregister:lt,getFieldState:Te,handleSubmit:Ut,setError:ht,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:Ct,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:hn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:mn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return o},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:Nt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,o,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:lt,setError:ht,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,o]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>o({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return o(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,o(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),o=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));St(u,"root",o),St(n,r,u)}else St(n,r,o)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function jt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const o=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,o)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,o)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const o=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(o,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return Ci(this,"shape",o),o}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,o={...i};if(n)for(const u in n){if(!(u in o))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)o[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",o),o}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,o=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...o,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...o,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...o,...u.path]);else{const f=[...o,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const o=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},o);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,o,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const o=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},o);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,o,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new wo;return o.issues.length?{success:!1,error:new(e??Kv)(o.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:o.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:o.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,o=i.length;if(o===t.length)return;const u=Gv(i),f=o>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` -`).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),o=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of o)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,i.join(` -`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},o=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>o(y,u,f)):o(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}jt(e,"~standard",()=>({validate:i=>{try{const o=F8(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,o]=r;if(!o)throw new Error;const u=Number(o);if(`${u}`!==o)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return o.length?Promise.all(o).then(()=>n):n}});function Od(e,t,n,r,i,o){const u=n in r;if(e.issues.length){if(i&&o&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,o){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));jt(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,o=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return o?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` + color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",St=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return St(i,DE,t[n]),St(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Pt(i)&&l){const u=IE(i,l);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&St(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?St(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&St(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&St(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&St(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else St(l,z,Q)},H=(z,Q)=>{St(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(l,z)),Se=Re(l,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?St(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):St(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(St(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?St(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):St(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&ht(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?ht(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):St(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&<(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&St(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&St(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||St(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(St(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const yt=h[X];yt&&yt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),vt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),vt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:yt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(yt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(yt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;St(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),lt=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},hn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},Nt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return St(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?hn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;St(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},Ct=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),mn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),Ct(),setTimeout(Ct);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),St(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?St(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)St(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:Nt,unregister:lt,getFieldState:Te,handleSubmit:Ut,setError:ht,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:Ct,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:hn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:mn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:Nt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:lt,setError:ht,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));St(u,"root",l),St(n,r,u)}else St(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function jt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` +`).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>` ${l}`)];return new t(...n,i.join(` +`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}jt(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));jt(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` if (${T}.issues.length) { if (${A} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ @@ -111,21 +111,21 @@ Error generating stack: `+d.message+` } } - `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let o;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(o||(o=i(t.shape)),w=o(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!vo(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),jt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),jt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),jt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),o=!0;else{if(h.issues.length===0)return h;u.push(h)}}return o?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,o=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||u instanceof Promise?Promise.all([o,u]).then(([h,m])=>T1(n,h,m)):T1(n,o,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};for(const o of r){const u=dg(e[o],t[o]);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};i[o]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(o.length&&i&&e.issues.push({...i,keys:o}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(u=>O1(u,i)):O1(o,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.innerType._zod.optin),jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>A1(o,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>D1(o,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>yi(o,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>t.in._zod.values),jt(e._zod,"optin",()=>t.in._zod.optin),jt(e._zod,"optout",()=>t.out._zod.optout),jt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(u=>Qu(u,t.in,r)):Qu(o,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Qu(o,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),jt(e._zod,"propValues",()=>t.innerType._zod.propValues),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"optin",()=>t.innerType?._zod?.optin),jt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(o=>L1(o,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(Wl(o))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},o=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ + `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),jt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),jt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),jt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.innerType._zod.optin),jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>t.in._zod.values),jt(e._zod,"optin",()=>t.in._zod.optin),jt(e._zod,"optout",()=>t.out._zod.optout),jt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),jt(e._zod,"propValues",()=>t.innerType._zod.propValues),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"optin",()=>t.innerType?._zod?.optin),jt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){o(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){o(u);continue}}if(e.metadataRegistry.get(u[0])?.id){o(u);continue}if(f.cycle){o(u);continue}if(f.count>1&&e.reused==="ref"){o(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},u=o2({...i??{},target:o,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:o,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,o=KE(i.entries);o.every(u=>typeof u=="number")&&(n.type="number"),o.every(u=>typeof u=="string")&&(n.type="string"),n.enum=o},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(o.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const u=o.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=o.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=jn(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,o=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,o?"oneOf":"anyOf",h]}));o?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,o=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(o)?o.allOf:[o],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,o=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?o?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:o};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,o,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,o){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return o.shouldUseNativeValidation&&cg({},o),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,o){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return o.shouldUseNativeValidation&&cg({},o),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const o in n){const u=n[o];Object.defineProperty(r,o,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,o)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),jt(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,o)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const o={};for(const u of r)if(n.has(u))o[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:o})},e.exclude=(r,i)=>{const o={...t.entries};for(const u of r)if(n.has(u))delete o[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:o})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(Wl(o,n.value,t));else{const u=o;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return l.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:l.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return l.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return l.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return l.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return l.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return l.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?l.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:l.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):l.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return l.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:l.jsxs(Q9,{className:"admin-table",children:[l.jsx(X9,{children:e.getHeaderGroups().map(n=>l.jsx(K1,{children:n.headers.map(r=>l.jsx(eU,{header:r},r.id))},n.id))}),l.jsx(W9,{children:e.getRowModel().rows.map(n=>l.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>l.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:o=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>l.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>l.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>l.jsxs("span",{className:"share-acts",children:[l.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:l.jsx(ge,{name:"copy"})}),r&&l.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return o?l.jsx("div",{className:"admin-list",children:l.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?l.jsx("div",{className:"admin-list",children:l.jsx("div",{className:"admin-empty",children:i})}):l.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",o=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return l.jsxs("div",{className:"admin",children:[l.jsx("h1",{id:"org-title",children:e.name}),!i&&l.jsx("p",{className:"role-chip-row",children:l.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&l.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&l.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),o()}catch(j){ke(j.message,!0)}}),children:[l.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),l.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),l.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&l.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),l.jsx("h3",{children:"Members"}),l.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:o}),l.jsx("h3",{children:"Projects"}),l.jsxs("div",{className:"admin-list",children:[w.length===0&&l.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>l.jsx("div",{className:"admin-item",children:l.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"admin-h",children:[l.jsx("h3",{children:"Invite links"}),l.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),l.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&l.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>l.jsxs("div",{className:"admin-item",children:[l.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),l.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),l.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),l.jsx("h3",{children:"Public share links"}),l.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),l.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),l.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},o=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"admin-h",children:[l.jsx("h3",{children:"Apps"}),l.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),l.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),l.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&l.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>l.jsxs("div",{children:[l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",title:u.name,children:u.name}),l.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&l.jsxs(l.Fragment,{children:[l.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>o((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),l.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>l.jsxs("div",{className:"admin-item",children:[l.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),l.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),l.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,o]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return l.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?l.jsx("span",{className:"ai-tag role-static",children:y.role}):l.jsxs("span",{className:"role-cell",children:[l.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[l.jsx("option",{value:"owner",children:"owner"}),l.jsx("option",{value:"member",children:"member"})]}),l.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:o,getCoreRowModel:ME(),getSortedRowModel:TE()});return l.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const o=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return l.jsxs("div",{className:"admin",children:[l.jsx("h1",{children:"Signup & access"}),l.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),l.jsx("h3",{children:"New-account vetting"}),l.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[l.jsxs("div",{className:"admin-list",children:[l.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),l.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),l.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),l.jsx("h3",{children:"Who can sign up"}),l.jsxs("div",{className:"admin-list",children:[l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Allowed email domains"}),l.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Self-signup"}),l.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:"Hub admins"}),l.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),l.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),l.jsx("h3",{children:"Pending signups"}),l.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&l.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),l.jsx(Ie,{variant:"primary",onClick:()=>o(u.id,"approve",u.email),children:"Approve"}),l.jsx("button",{className:"ai-del",onClick:()=>o(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return l.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[l.jsxs("span",{className:"ai-main",children:[l.jsx("div",{className:"tg-label",children:e}),l.jsx("div",{className:"tg-desc",children:t})]}),l.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return l.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return l.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return l.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return l.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return l.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return l.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Connections are unavailable"}),l.jsx("p",{children:n.error.message})]});const o=n.data?.grants??[];return l.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[l.jsx("h2",{children:"Connected agents"}),l.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",l.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),o.length===0?l.jsx(Es,{children:l.jsxs(Ns,{children:[l.jsx(ks,{children:"No agents connected"}),l.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",l.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):o.map(u=>l.jsxs(Es,{className:"mcp-grant",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:u.client_name||"Unnamed client"}),l.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),l.jsxs(Ps,{children:[l.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>l.jsx("span",{className:"ps-chip",children:i(f)},f))}),l.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return l.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return l.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return l.jsx(Rz,{children:l.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return l.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return l.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return l.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[l.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:l.jsx(zz,{children:l.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return l.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return l.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return l.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,o]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=o.human||0,r.agent+=o.agent||0,r.share+=o.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-eo.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let o=r.cx+r.r+4,u="start";o+i.length*NU>t.right&&(o=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:o,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],o=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(o.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:o}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const o=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:o,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==o),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),o=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:o}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const o=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return l.jsxs("nav",{id:"projects","aria-label":"Projects",children:[l.jsx($2,{projects:e,current:o,menu:n,account:r,onNew:i,trigger:l.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${o?.name??"none"}`,title:o?.name,children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:o?mc(o.name):void 0,children:l.jsx(ui,{name:o?.icon})}),l.jsx("span",{className:"proj-name",children:o?o.name:e.length?"Select a project":"No projects yet"}),l.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&l.jsx(F2,{}),n&&l.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>l.jsx("li",{children:l.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[l.jsx(ge,{name:m}),l.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&l.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:o,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return l.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[l.jsx(Wv,{asChild:!0,children:o}),l.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[l.jsx("div",{className:"sb-menu-projects",children:e.map(_=>l.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),ds()},children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:l.jsx(ui,{name:_.icon})}),l.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&l.jsx(ge,{name:"check"})]},_.id))}),l.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[l.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:l.jsx(ge,{name:"plus"})}),l.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&l.jsx(mg,{}),n&&t&&l.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[l.jsx(ge,{name:"gear"}),l.jsx("span",{className:"label",children:"Project settings"})]}),w&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[l.jsx(ge,{name:"building"}),l.jsx("span",{className:"label",children:"Organization settings"}),l.jsx("span",{className:"meta",children:w.name}),E&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[l.jsx(ge,{name:"card"}),l.jsx("span",{className:"label",children:"Billing"}),l.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&l.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[l.jsx(ge,{name:"shield"}),l.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&l.jsx("span",{className:"meta",children:r.admin.pending})]}),l.jsx(mg,{}),r&&l.jsx(dU,{className:"sb-menu-label",children:r.me.email}),l.jsxs("div",{className:"sb-theme",children:[l.jsx("span",{className:"label",children:"Theme"}),l.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>l.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:l.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[l.jsx(ge,{name:"plug"}),l.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?l.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[l.jsx(ge,{name:"power"}),l.jsx("span",{className:"label",children:"Log out"})]}):l.jsx(Cs,{asChild:!0,children:l.jsxs("a",{id:"signout",href:"/auth/logout",children:[l.jsx(ge,{name:"power"}),l.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:o}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),o&&u.push("synced "+ho(o));const f=l.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?l.jsx("span",{className:"sync-dot","aria-hidden":"true"}):l.jsx(ge,{name:"laptop"}),l.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?l.jsx("div",{className:"sb-foot",children:l.jsxs(uf,{delayDuration:300,children:[l.jsx(df,{asChild:!0,children:f}),l.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):l.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return l.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[l.jsx(ge,{name:"search"}),l.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?l.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):l.jsxs(uf,{delayDuration:150,children:[l.jsx(df,{asChild:!0,children:l.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),l.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",l.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return l.jsx(l.Fragment,{children:L2.map(([r,i,o])=>l.jsx(jv,{id:"rail-"+r,icon:o,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return l.jsx($2,{...e,side:"right",trigger:l.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:l.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return l.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:l.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return l.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[l.jsx(HU,{}),l.jsx("span",{children:"Star on GitHub"}),l.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return l.jsxs("footer",{id:"accountbar",children:[l.jsx(qU,{}),l.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[l.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),l.jsxs("span",{className:"acct",children:[l.jsx("b",{children:"Sign in…"}),l.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return l.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return l.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Billing is unavailable"}),l.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return l.jsxs("div",{className:"project-settings",id:"billing-view",children:[l.jsxs("h2",{children:["Billing",l.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),l.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx("div",{className:"usage-bar",children:l.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?l.jsx("div",{className:"plan-grid",children:n.plans.map(r=>l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:r.name}),l.jsx(lr,{children:r.blurb})]}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsxs("p",{className:"plan-price",children:[r.price,l.jsx("small",{children:" / user / month"})]}),l.jsxs("form",{method:"post",action:n.checkout_url,children:[l.jsx("input",{type:"hidden",name:"plan",value:r.id}),l.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):l.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Manage subscription"}),l.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx("form",{method:"post",action:n.portal_url,children:l.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return l.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return l.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),o=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{o.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=o.watch("icon"),f=o.watch("description"),h=o.handleSubmit(async m=>{const y=o.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),o.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return l.jsxs("div",{className:"project-settings",children:[l.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&l.jsx("span",{className:"ps-chip",children:"Read-only"})]}),l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"General"}),l.jsx(lr,{children:"Name, description and icon for this project."})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsxs("form",{className:"ps-form",onSubmit:h,children:[l.jsxs("div",{className:"ps-field",children:[l.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),l.jsxs("div",{className:"ps-icon-row",children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:l.jsx(ui,{name:u})}),l.jsxs(Xv,{children:[l.jsx(Wv,{asChild:!0,children:l.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),l.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[l.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>o.setValue("icon","",{shouldDirty:!0}),children:l.jsx(ui,{})}),Object.keys(Yp).map(m=>l.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>o.setValue("icon",m,{shouldDirty:!0}),children:l.jsx(ui,{name:m})},m))]})]})]})]}),l.jsxs("div",{className:"ps-field",children:[l.jsx(pp,{htmlFor:"ps-name",children:"Name"}),l.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!o.formState.errors.name,"aria-describedby":o.formState.errors.name?"ps-name-err":void 0,...o.register("name")}),o.formState.errors.name&&l.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:o.formState.errors.name.message})]}),l.jsxs("div",{className:"ps-field",children:[l.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",l.jsx("span",{className:"ps-opt",children:"(optional)"})]}),l.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!o.formState.errors.description,"aria-describedby":o.formState.errors.description?"ps-desc-err":void 0,...o.register("description")}),l.jsxs("div",{className:"ps-meta",children:[o.formState.errors.description?l.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:o.formState.errors.description.message}):l.jsx("span",{}),l.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&l.jsxs(l.Fragment,{children:[l.jsx(Fr,{}),l.jsx("div",{className:"ps-actions",children:l.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!o.formState.isDirty||o.formState.isSubmitting,children:"Save changes"})})]})]})})]}),l.jsx(XU,{project:e}),l.jsx(JU,{project:e,org:t}),l.jsxs(Es,{id:"ps-devices",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Devices"}),l.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),l.jsx(Ps,{children:l.jsx(Ie,{asChild:!0,variant:"outline",children:l.jsx("a",{...In(cn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&l.jsx(QU,{project:e,onChanged:r}),l.jsxs(Es,{children:[l.jsx(Ns,{children:l.jsx(ks,{children:"About"})}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsxs("dl",{className:"ps-facts",children:[l.jsx("dt",{children:"Project id"}),l.jsx("dd",{children:l.jsx("code",{children:e.id})}),t&&l.jsxs(l.Fragment,{children:[l.jsx("dt",{children:"Workspace"}),l.jsx("dd",{children:t.name})]}),e.created&&l.jsxs(l.Fragment,{children:[l.jsx("dt",{children:"Created"}),l.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),l.jsxs("p",{className:"ps-note ps-export",children:[l.jsx("strong",{children:"Take your files elsewhere."})," Run ",l.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",l.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",l.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&l.jsxs(Es,{className:"ps-danger",children:[l.jsx(Ns,{children:l.jsx(ks,{children:"Danger zone"})}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[l.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),l.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return l.jsxs(Es,{id:"ps-data",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Data"}),l.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),l.jsx(Ps,{children:l.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:l.jsxs(Es,{children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"Public links"}),l.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(o=>o.opens!==void 0)&&l.jsxs(l.Fragment,{children:[" ",v2]})]})]}),l.jsx(Fr,{}),l.jsx(Ps,{children:l.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),o=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return l.jsxs(Es,{className:"ps-people",children:[l.jsxs(Ns,{children:[l.jsx(ks,{children:"People"}),l.jsx(lr,{children:"Who can see and change this project."})]}),l.jsx(Fr,{}),l.jsxs(Ps,{children:[t?.role==="owner"&&l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Not in ",t.name," yet?"]}),l.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),l.jsx("select",{"aria-label":"Default access for workspace members",disabled:!o,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>l.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&l.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),l.jsxs("div",{className:"ps-people-head",children:[l.jsx("h4",{children:"Exceptions"}),o&&l.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?l.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):l.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return l.jsxs("div",{className:"admin-item",children:[l.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&l.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?l.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):l.jsxs("span",{className:"role-cell",children:[l.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!o,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>l.jsx("option",{value:S.value,children:S.label},S.value))}),o&&l.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,o=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} -to set up ${o} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive -bdrive init --server `+n+" --project "+e.id;return l.jsxs("div",{className:"guide",children:[l.jsxs("h1",{className:"in-title gd-head",children:[l.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:l.jsx(ui,{name:e.icon})}),e.name]}),e.description&&l.jsx("p",{className:"in-desc",children:e.description}),l.jsxs("div",{className:"gd-body",children:[l.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&l.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),l.jsx(Jl,{code:r}),l.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),l.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),l.jsxs("details",{className:"gd-manual",children:[l.jsx("summary",{children:"What exactly happens"}),l.jsxs("ul",{className:"gd-desc gd-list",children:[l.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),l.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),l.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),l.jsxs("details",{className:"gd-manual",children:[l.jsx("summary",{children:"Or run it yourself"}),l.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),l.jsx(Jl,{code:i}),l.jsx("p",{className:"gd-desc",children:l.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return l.jsxs("pre",{className:"gd-code",children:[l.jsx("code",{children:e}),l.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return l.jsxs("div",{className:"onboard",children:[l.jsx("h1",{children:"Welcome to BearDrive"}),l.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&l.jsxs("div",{className:"ob-card ob-start",children:[l.jsx("h3",{children:"Start a project"}),l.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),l.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),l.jsxs("div",{className:"ob-card ob-agent",children:[l.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),l.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),l.jsx(Jl,{code:kf(window.location.origin)}),l.jsx("p",{className:"ob-alt",children:l.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return l.jsxs("div",{className:"onboard setup-welcome",children:[l.jsx("h1",{children:"Welcome to BearDrive"}),l.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),l.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),l.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return l.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[l.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),l.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",l.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>l.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&l.jsx("div",{className:"setup-dim",children:"├── …"}),l.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",l.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),l.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[o,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:o});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,o,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return l.jsxs("div",{className:"setup-connect",children:[l.jsxs("header",{children:[l.jsxs("h2",{children:["Add a shared folder to your project",!N&&l.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),l.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",l.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&l.jsxs("ul",{className:"setup-why",children:[l.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),l.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),l.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),l.jsxs("div",{className:"setup-body",children:[l.jsxs("div",{className:"setup-form",children:[l.jsxs("label",{className:"setup-field",children:[l.jsx("span",{children:"Your project folder"}),l.jsxs("div",{className:"setup-root",children:[l.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),l.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),l.jsxs("label",{className:"setup-field",children:[l.jsx("span",{children:"Shared folder name"}),l.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),l.jsxs("label",{className:"setup-toggle",children:[l.jsx("input",{type:"checkbox",id:"setup-hooks",checked:o,onChange:T=>u(T.target.checked)}),l.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&l.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&l.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&l.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&l.jsxs("div",{className:"setup-warn",children:[l.jsx("p",{children:f.warning}),f.helper&&l.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",l.jsx("code",{children:f.helper})," ",l.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),l.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),l.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",l.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),l.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const o=["creating","connecting","syncing","done"],u=Math.max(0,o.indexOf(n.phase));return l.jsxs("div",{className:"setup-syncing",children:[l.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),l.jsx("div",{className:"setup-bar",children:l.jsx("div",{style:{width:`${(u+1)/o.length*100}%`}})}),l.jsxs("ul",{className:"setup-log",children:[l.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),l.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),l.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?l.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):l.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[o,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return l.jsxs("div",{className:"setup-done",children:[l.jsxs("h2",{children:[f,"/ is live"]}),l.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&l.jsx("p",{className:"setup-err",children:e.error}),l.jsxs("div",{className:"setup-cards",children:[l.jsxs("div",{className:"setup-card",children:[l.jsx("h3",{children:"Open the dashboard"}),l.jsx("p",{children:"Browse files, history, and who reads what."}),l.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),l.jsxs("div",{className:"setup-card setup-card-lead",children:[l.jsx("h3",{children:"Tell your agent"}),l.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),l.jsx(Jl,{code:h}),l.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),l.jsxs("div",{className:"setup-card",children:[l.jsx("h3",{children:"Invite teammates"}),l.jsx("p",{children:"A link that signs them up straight into this project."}),l.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),o&&l.jsx("p",{className:"setup-err",id:"setup-invite-err",children:o})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),l.jsxs("div",{className:"setup",children:[e==="welcome"&&l.jsx(nV,{onStart:n}),e==="connect"&&l.jsx(rV,{onStarted:o=>gt("/setup/syncing?name="+encodeURIComponent(o))}),e==="syncing"&&l.jsx(aV,{onDone:o=>{i(o),gt("/setup/done")}}),e==="done"&&l.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,o]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return l.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:l.jsxs(cc,{className:"modal",showCloseButton:!1,children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:"New project"})}),l.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),l.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{o(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&l.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&l.jsxs("fieldset",{className:"start-points",children:[l.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>l.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[l.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),l.jsxs("span",{className:"sp-text",children:[l.jsxs("span",{className:"sp-title",children:[x.title,j===0&&l.jsx("span",{className:"sp-rec",children:"Recommended"})]}),l.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),l.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,o)=>i<3&&dV(o),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:o,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||o?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const o=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},o))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},o))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),o=b.useRef(t);return o.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:o.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:o.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const o=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),jt(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...In(cn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),l=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} +to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive +bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` `).filter(f=>f.trim()).join(` `),t.push(i),i=null)};for(const u of e.split(` -`)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(o(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return o(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(` +`)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(` `).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=cy(e),n=[];let r=0;return e.split(` -`).forEach((i,o)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:o+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` +`).forEach((i,l)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:l+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` `)}function BB(e){return e.split(` -`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),o=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||o==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(o))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;no.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,o])=>i>=r.headingEnd&&o<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return l.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,o=n.length-r.length;return l.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>l.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),o>0&&l.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",o]}),i>0&&l.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,o,u){if(typeof o=="string"){const f=o.charCodeAt(0);if(f>=48&&f<=57){const h=+o;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(i),o=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let o=0;o{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const o=e.options.useScrollendEvent&&MV;let u=0;const f=o?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),o&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),o&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),o=n.itemSizeCache.get(i);if(o!==void 0)return o}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,o;(o=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||o.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(o=>{const u=()=>{const f=o.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var o;return(o=r())==null?void 0:o.observe(i,{box:"border-box"})},unobserve:i=>{var o;return(o=r())==null?void 0:o.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(o[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=o.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(o.getItemKey(0)!==S||o.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=o.followOnAppend===!0?"auto":o.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||o.getItemKey(x-1)!==E)&&(h=T)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,u)=>{if(u&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===o?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",u,Id),o.addEventListener("touchend",f,Id),this.unsubs.push(()=>{o.removeEventListener("touchstart",u),o.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[o,u,f,h]=i;o!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,o,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:o,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,o)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,o,u)=>o===null||u===null?[]:n({startIndex:o,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-o),f=Math.min(this.options.count-1,i+o);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),o=this.elementsCache.get(i);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,o;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let o=0,u=n.length;othis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,o=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,o?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+o?"end":"start"),r==="center"?n+=(i-o)/2:r==="end"&&(n-=o);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),o=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=o+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[u,f]=o,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,u=this._flatMeasurements;u!=null?i=u[o*2]+u[o*2+1]:i=((n=r[o])==null?void 0:n.end)??0}else{const o=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&o.some(f=>f===null);){const f=r[u];o[f.lane]===null&&(o[f.lane]=f.end),u--}i=Math.max(...o.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,o=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,o=n(i);if(or)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,o=e[i*2];if(on)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&i!==null){const m=$V(i,o,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(o,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],o=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const u=m=>{const y=o.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=o.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=o.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return l.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return l.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return l.jsx(rz,{children:l.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return l.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return l.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return l.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,o,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+o,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+o||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",o=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-o.length))+o}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const o=e.toLowerCase();if(o.length===e.length)return{text:o,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let o=0;o65535?2:1);for(;u65535?2:1}const f=e.slice(o,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:o}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:o},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+o-1]}function aH(e,t,n,r){const i=e.length,o=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*o),m=new Float64Array(i*o);for(let w=0;w0&&(N=Math.max(m[_-o-1]+Pl[f[n+E]],h[_-o-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=o-1;w>=0;w--)for(;x>=0;x--){const j=w*o+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-o-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*o-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const o=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let o=n;for(let u=0;u=o)return!0;if(o=t.indexOf(e[u],o)+1,o===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,o=-1;for(let u=0;ui&&(i=f,o=u)}return o<0?-1/0:(r&&_g(e.drops[o].text,e.drops[o].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,o=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!o){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),o=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!o?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const o=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return o!==u?o0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,o=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],o):n.push([i,o])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const o={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:o,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,o=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{o.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;o.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:o=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>o===w||o.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),o=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:o.list,folderCount:i.total,fileCount:o.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const o=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&o.push(e.slice(u,m)),o.push(l.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[l.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",l.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&l.jsxs(i,{onSelect:()=>n.newFile(f),children:[l.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&l.jsxs(i,{onSelect:()=>n.togglePin(e),children:[l.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),l.jsx(o,{}),l.jsxs(i,{onSelect:()=>n.copyPath(e),children:[l.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&l.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[l.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&l.jsx(o,{}),n.history&&l.jsxs(i,{onSelect:()=>n.history(e),children:[l.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&l.jsxs(i,{onSelect:()=>n.insights(e),children:[l.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&l.jsxs(l.Fragment,{children:[l.jsx(o,{}),l.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[l.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:o,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>l.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return l.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:l.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return l.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return l.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),l.jsx("span",{className:"chev",children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"system"})}),l.jsx("span",{className:"label",children:"System files"}),l.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&o){r(W.path);return}m.open(W.path),W.dir||ds()};return l.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[l.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[l.jsx(VV,{asChild:!0,children:l.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),l.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:l.jsx(ge,{name:"chevd"})}),l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),l.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&l.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&l.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&l.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:l.jsx(ge,{name:"lock"})}),l.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&l.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:l.jsx(ge,{name:"plus"})}),l.jsx(Wv,{asChild:!0,children:l.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:l.jsx(ge,{name:"dots"})})})]})]})}),l.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),l.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:l.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,o]=b.useState(!1);b.useEffect(()=>o(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>l.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:E.dir?"folder":"doc"})}),l.jsxs("span",{className:"fhit-text",children:[l.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),l.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&l.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return l.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&l.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&l.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&l.jsxs("button",{className:"fmore",onClick:()=>o(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&l.jsx("div",{className:"fempty",children:"No file or folder names match"}),l.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:"search"})}),l.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),l.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:o,onUnpin:u}=e;return t.length?l.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[l.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return l.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&o(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),o(f))},children:[l.jsx(ge,{name:"star"}),l.jsx("span",{className:"label",children:h}),m>0&&l.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&l.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),l.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:l.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-sep"}),t.map(i=>{const o=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return l.jsx(jv,{icon:"doc",label:o,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return l.jsx("span",{className:"crumbs",title:e,children:n.map((i,o)=>{r=r?r+"/"+i:i;const u=r,f=o===n.length-1,h=o>0&&!f;return l.jsxs("span",{className:"crumb",children:[o>0&&l.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?l.jsx("span",{className:"crumb-last",children:i}):l.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,o=e?.until?Ng(e.until):null;return i&&(r.since=i),o&&(r.until=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const o of["q","user","actor","device"])e?.[o]&&n.set(o,e[o]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` -`);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:o[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=o[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,o=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return l.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[l.jsxs("div",{className:"fv-chips",children:[n&&l.jsxs("span",{className:"fv-chip accent",children:[l.jsx(ge,{name:"shield"})," ",n]}),r&&l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),l.jsxs("span",{className:"fv-chip",children:[l.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),l.jsxs("div",{className:"fv-meta",children:[o&&l.jsxs("span",{className:"meta-stale",title:o,children:[l.jsx("span",{"aria-hidden":"true",children:"⚠ "}),o]}),f&&l.jsxs("span",{className:"fv-who",title:f,children:[l.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&l.jsxs("span",{children:[l.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&l.jsxs("span",{className:"fv-when",children:[l.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&l.jsxs("span",{className:"fv-reads",title:Ur,children:[l.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,o=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(o),y=r?Vs(r):0;if(!o.length&&!n?.length&&!y)return null;const g=l.jsxs(l.Fragment,{children:[o.length>0&&l.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[l.jsx("p",{className:"fv-sec-h",children:"On this page"}),l.jsx("ul",{children:o.map(w=>l.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:l.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&l.jsx(PH,{heat:r,insightsHref:i}),n?.length?l.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[l.jsx("p",{className:"fv-sec-h",children:"Properties"}),l.jsx("dl",{children:n.map(w=>l.jsxs("div",{children:[l.jsx("dt",{children:w.key}),l.jsx("dd",{children:w.code?l.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?l.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:l.jsx("div",{className:"fv-rail-in",children:g})}):l.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[l.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),l.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return l.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[l.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&l.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),l.jsxs("div",{className:"fv-big",title:Ur,children:[n,l.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),l.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>l.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),l.jsx("div",{className:"fv-legend",children:r.map(i=>l.jsxs("span",{children:[l.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&l.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const o=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(o))};return o(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],o="",u=!1,f=0;const h=()=>{i.push(o),o="",r.lengthq2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` +`);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,o=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=l.jsxs(l.Fragment,{children:[i&&m.length>0&&l.jsx(ZH,{...e,secs:m}),l.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[l.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&l.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?l.jsxs("p",{className:"er-empty",children:["None yet. Type ",l.jsx("kbd",{children:"/"})," and pick Action item, or write ",l.jsx("code",{children:"- [ ] … @owner"}),"."]}):l.jsx("ul",{className:"er-list",children:h.map(g=>l.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[l.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),l.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",l.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&l.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return o?l.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:l.jsx("div",{className:"fv-rail-in",children:y})}):l.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[l.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),l.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return l.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[l.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),l.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:l.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),l.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),o=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return l.jsxs("li",{children:[l.jsx(G2,{name:r.name}),l.jsx("span",{className:"er-name",children:r.name}),l.jsx("span",{className:"er-state "+(o?"typing":r.body?"done":"none"),children:i&&u?"You · editing":o?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[o,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return l.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[l.jsx("h4",{children:"Recent versions"}),l.jsxs("ul",{className:"er-vlist",children:[l.jsxs("li",{className:"now",children:[l.jsx("i",{className:"er-dot live","aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",children:"Now"}),l.jsx("span",{className:"er-vwho",children:"Live"}),l.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return l.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[l.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),l.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),l.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),l.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&l.jsx("button",{type:"button",className:"er-restore",disabled:!!o,title:"Restore this version as a new version",onClick:()=>{y(g)},children:o===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),l.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DHvYAyxu.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-BYnijXna.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,o]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&o(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{o(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,o=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?l.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?l.jsx(s7,{...e}):oi.test(n)?l.jsx(a7,{...e}):Lr.test(n)?l.jsx(WH,{...e,fileURL:o}):id.test(n)?l.jsx("iframe",{className:"pdfview",src:o,title:n,onLoad:e.onRendered}):P_.test(n)?l.jsx(o7,{src:o,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?l.jsx(vS,{...e,fileURL:o,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?l.jsx(vS,{...e,fileURL:o}):l.jsx(JH,{...e,fileURL:o})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,o=V2(t,n,e.fileURL,r),u=o.url,f=b.useRef(o.fresh);f.current=o.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?l.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:o}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&o?.()},[u,o]),f?l.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?l.jsx("pre",{className:"plain",children:u.text},n):l.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"name",children:n.split("/").pop()}),l.jsx("p",{children:e.children}),l.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:o}=e;b.useEffect(()=>o?.(),[o]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return l.jsxs("div",{className:"filecard",children:[l.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:l.jsx(ge,{name:"link"})}),l.jsx("div",{className:"name",children:t.split("/").pop()}),l.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),l.jsxs("p",{children:["Target:"," ",f?l.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:l.jsx("code",{children:n})}):l.jsx("code",{children:n}),!f&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),l.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,o=Eo(t,n),u=V2(t,n,o).url,f=ly(o,["text",o],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[o]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(o)}),()=>{Fe=!1}},[w,o]);const x=y===o?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(o),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",o]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",o]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,o]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(l.jsxs(l.Fragment,{children:[l.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[l.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&l.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>l.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&l.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?l.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?l.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):l.jsxs(l.Fragment,{children:[h&&l.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&l.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&l.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[l.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&l.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>l.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[l.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&l.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?l.jsxs("div",{className:"empty",children:["Could not load the editor."," ",l.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?l.jsx("div",{className:"empty",children:"Loading editor…"}):l.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?l.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:l.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):l.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&l.jsx(r7,{...e}),!i&&l.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[l.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),l.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[l.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&l.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?l.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):l.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:o}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?l.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,o)}):l.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:o,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return l.jsx(Tf,{version:i,err:g});if(!y)return l.jsx(uN,{});const _=i?null:o&&o[y.path]||null,N=l.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return l.jsxs(l.Fragment,{children:[l.jsx(i7,{findings:y.findings}),!t&&N,l.jsx(FH,{doc:y,heat:_}),l.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return l.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[l.jsxs("div",{className:"fskel-main",children:[l.jsx("span",{className:"fskel-title"}),l.jsxs("span",{className:"fskel-meta",children:[l.jsx("span",{style:{width:120}}),l.jsx("span",{style:{width:90}}),l.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>l.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),l.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[l.jsx("span",{style:{width:"40%"}}),l.jsx("span",{style:{width:"80%"}}),l.jsx("span",{style:{width:"65%"}}),l.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?l.jsxs("div",{className:"sbadge",role:"status",children:[l.jsx("span",{className:"sb-icon",children:l.jsx(ge,{name:"shield"})}),l.jsxs("div",{className:"sb-text",children:[l.jsx("b",{children:GH(e)}),l.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(o,decodeURIComponent(i))))}function py(e,t,n,r,i){const o=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(o,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?l.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):l.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return l.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:o}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&o?.()},[u,o]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?l.jsx(Tf,{version:n,err:f}):u==null?null:h?l.jsx(l7,{csv:h},t):l.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((o,u)=>Math.max(o,u.length),0),i=Array.from({length:r},(o,u)=>u);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"csvbox",children:l.jsxs("table",{className:"csvview",children:[l.jsx("thead",{children:l.jsx("tr",{children:i.map(o=>l.jsx("th",{children:t[o]??""},o))})}),l.jsx("tbody",{children:n.map((o,u)=>l.jsx("tr",{children:i.map(f=>l.jsx("td",{children:o[f]??""},f))},u))})]})}),e.truncated>0&&l.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return l.jsxs("span",{className:"dv-dl",children:[l.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),l.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),o=tc(e,r,!0),u=i.data?.kind==="text"&&o.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&o.data?.kind==="text"?kg(i.data.text,o.data.text):null,[i.data,o.data]);if(i.error||o.error)return l.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!o.data)return l.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||o.data.kind==="too-large";return l.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",l.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return l.jsxs("div",{className:"dv",children:[l.jsxs("div",{className:"dv-head",children:[l.jsxs("span",{className:"dv-stat",children:[l.jsxs("span",{className:"dv-add",children:["+",m]})," ",l.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&l.jsx("span",{className:"dv-same",children:"No line changes"})]}),l.jsx("div",{className:"dv-body",children:h.map((g,w)=>l.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[l.jsx("span",{className:"dv-n",children:g.an??""}),l.jsx("span",{className:"dv-n",children:g.bn??""}),l.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),l.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),o=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||o.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,o.data.text):kg("",o.data.text),[i.data,o.data,t])}function d7({add:e,del:t}){return l.jsxs("span",{className:"hstat",children:[e>0&&l.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&l.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:o,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return l.jsxs("div",{className:"dtabs",children:[l.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>l.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),l.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?l.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):l.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&l.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:o,projectId:u,onOpenFile:f}),h==="full"&&y&&l.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:o}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?l.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?l.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?l.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,o)}):l.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):l.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?l.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?l.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):l.jsx("div",{className:"dv",children:l.jsx("div",{className:"dv-body",children:n.data.text.split(` -`).map((r,i)=>l.jsxs("div",{className:"dv-line dv-ctx",children:[l.jsx("span",{className:"dv-n",children:i+1}),l.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):l.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return l.jsx(l.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?l.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:o,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!o&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!o?.busy&&o.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return l.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[l.jsxs("div",{className:"hline",children:[l.jsx("span",{className:"hkind",children:g7[N]||N}),m&&l.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),l.jsx("span",{className:"hpath",children:e.path}),q&&l.jsx(d7,{add:q.add,del:q.del}),l.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),l.jsxs("div",{className:"hmeta",children:[l.jsx("span",{className:"hwho",title:R,children:yv(e)}),l.jsx("span",{className:"hdev",children:T}),l.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&l.jsx("span",{className:"hgone",children:"can be restored"}),V&&l.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&l.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&l.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&l.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),o.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&l.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:l.jsx(fN,{text:e.note})}),(M||Y)&&l.jsxs("div",{className:"hactions",children:[M&&(r.prev?l.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):l.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[l.jsx(ge,{name:"clock"}),"Open this version"]}),l.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[l.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,o=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=o.filter(g=>g.dir).length,f=o.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||o.some(g=>hd(n,g.path,!!g.dir));return l.jsxs("div",{className:"dirlist",children:[l.jsxs("h1",{className:"dl-title",children:[l.jsx("span",{className:"dl-title-icon",children:l.jsx(ge,{name:"folder"})}),l.jsx("span",{children:t.name})]}),l.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&l.jsx("p",{className:"dl-heatnote",children:Ur}),o.length===0?l.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):l.jsx("div",{className:"dl-items",children:o.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return l.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[l.jsx("span",{className:"ticon",children:l.jsx(ge,{name:g.dir?"folder":"doc"})}),l.jsx("span",{className:"dl-name",children:g.name}),S&&l.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&l.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&l.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&l.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),l.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&l.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:l.jsxs("div",{className:"dl-history",children:[l.jsx("h3",{className:"dl-h3",children:"Recent changes"}),l.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>l.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),l.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:o,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return l.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:l.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[l.jsx(To,{asChild:!0,children:l.jsx("h3",{children:B})}),l.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsxs("span",{children:["Everyone in ",g," can"]}),l.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&l.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&l.jsxs("p",{className:"ps-note",children:["A folder set to ",l.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",l.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&l.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&l.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>l.jsxs("div",{className:"admin-item",children:[l.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),l.jsx("span",{className:"ai-main",title:P.email,children:P.email}),l.jsx("span",{className:"role-cell",children:l.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>l.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&l.jsxs("div",{className:"admin-item sd-add",children:[l.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),l.jsxs("span",{className:"role-cell",children:[l.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"ps-row",children:_?l.jsxs("span",{children:["Access comes from the rule on ",l.jsx("b",{children:_.prefix})," — you can"," ",l.jsx("b",{children:_.me})," here."]}):l.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&l.jsxs(l.Fragment,{children:[" — the project default is ",l.jsx("b",{children:m.default})]}),"."]})}),_&&l.jsx("p",{className:"ps-row",children:l.jsxs(Ie,{variant:"subtle",onClick:()=>o(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),l.jsx("h4",{className:"sd-head",children:"Public link"}),n?l.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):l.jsxs(l.Fragment,{children:[l.jsxs("p",{className:"ps-row",children:[l.jsx("span",{children:l.jsx(ge,{name:T?"globe":"lock"})}),l.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[l.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),l.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sd-warn",children:l.jsx("b",{children:"This file may contain credentials"})}),l.jsx("p",{className:"ps-note",children:BH(W)}),l.jsxs("p",{className:"ps-row",children:[l.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),l.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"modal-url",children:T.url}),l.jsxs("div",{className:"modal-expiry",children:[l.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),l.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))}),l.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),l.jsxs("div",{className:"modal-actions",children:[l.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:l.jsxs("div",{className:"share-banner",role:"status",children:[l.jsxs("div",{className:"sb-head",children:[l.jsx(ge,{name:"share"}),l.jsx("b",{children:"Publicly shared"}),l.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),l.jsxs("p",{className:"sb-note",children:[l.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&l.jsxs(l.Fragment,{children:[" ",v2]})]}),e.map(r=>l.jsxs("div",{className:"sb-link",children:[l.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),l.jsx("span",{className:"sb-meta",children:g2(r,!1)}),l.jsxs("span",{className:"sb-actions",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),l.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&l.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,o)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==o);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,o,u,f)=>{const h=await Sn(e+"comments",{path:i,body:o,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,o,u="")=>{const f=await Sn(e+"comments/"+i,{action:o,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;mo&&(i=u,o=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),o=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return o<0?null:[i[o],i[o+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const o=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=o.nextNode();u;u=o.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[o]=0)return e.starts[r]+n;const o=t.ownerDocument.createRange();o.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),o=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=o)return null;const f=(n||i.all.slice(o,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,o,u)};return r&&(h.line=i.all.slice(0,o).split(` -`).length),h}function N7(e,t,n,r){const i=e;let o=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([o,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([o,u]=[f.startContainer,f.startOffset])}if(!o)return null;for(const[f,h]of r)try{if(h.isPointInRange(o,u)&&!(h.endContainer===o&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:o,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(o),[o]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return l.jsxs(l.Fragment,{children:[e.children,l.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>l.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[l.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&l.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[l.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&l.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[l.jsx(vN,{a:j.anchor}),l.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),l.jsxs("div",{className:"cm-row",children:[l.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),l.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:o,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),o(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return l.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[l.jsxs("header",{className:"cm-head",children:[l.jsx("b",{children:"Comments"}),l.jsxs("div",{className:"cm-tabs",role:"tablist",children:[l.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&l.jsxs("span",{children:[" · ",j.length]})]}),l.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&l.jsxs("span",{children:[" · ",S.length]})]})]}),l.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:l.jsx(ge,{name:"x"})})]}),f&&l.jsx("div",{className:"cm-pickbar",children:l.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[l.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),l.jsxs("div",{className:"cm-list",children:[R.length===0&&l.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>l.jsx(M7,{t:U,active:U.id===i,onFocus:()=>o(U.id===i?null:U.id),onJump:()=>{o(null),requestAnimationFrame(()=>o(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),l.jsxs("footer",{className:"cm-foot",children:[l.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),l.jsxs("div",{className:"cm-row",children:[l.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",l.jsx("code",{children:"bdrive comments"})]}),l.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:o,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await o.act(t.id,S,h),m("")});return l.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[l.jsxs("div",{className:"cm-card-top",onClick:r,children:[l.jsx("span",{className:"cm-n",children:t.n}),l.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&l.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>l.jsxs("div",{className:"cm-msg",children:[l.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),l.jsxs("div",{className:"cm-msg-main",children:[l.jsxs("div",{className:"cm-who",children:[l.jsx("b",{children:S.name||S.author||"someone"})," ",l.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),l.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&l.jsxs("div",{className:"cm-queued",children:[l.jsx(ge,{name:"sparkle"}),l.jsxs("span",{children:["Queued for next agent sweep · ",l.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&l.jsxs("div",{className:"cm-resolved",children:[l.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),l.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),l.jsxs("div",{className:"cm-row",children:[u&&l.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await o.remove(t.id)})},children:l.jsx(ge,{name:"trash"})}),l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&l.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&l.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[l.jsx(ge,{name:"jump"})," Jump to text"]}),l.jsx("span",{className:"cm-spacer"}),h.trim()&&l.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?l.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):l.jsxs("div",{className:"cm-anchor",children:[e.quote&&l.jsxs("div",{className:"cm-quote",children:[e.prefix&&l.jsx("span",{className:"cm-ctx",children:e.prefix}),l.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&l.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&l.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,o,u){if(o===t.length)return i===e.length?_S:$7;var f=`${i},${o}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(o),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,o+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(o)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),o=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=o.current.get(D))==null?void 0:I.value)&&(o.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{o.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{o.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=o.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=o.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),o=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,o,[e.value,e.children,o],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=o.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(o,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...o}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...o,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),o=ka(u=>!u.search);return!n&&!o?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,o=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||o.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,o=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&o.current){let m=u.current,y=o.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(o,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:o,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:o},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...o}=e;return b.createElement(ot.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),o=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());o.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return l.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[l.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),l.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return l.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return l.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return l.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"picon",children:l.jsx(ge,{name:e.icon})}),l.jsxs("span",{className:"ptext",children:[l.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&l.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&l.jsx("span",{className:"ploc",children:n})]}),!r&&l.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[o,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=o.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(o,m,{limit:oq}).hits,[o,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return l.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:l.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[l.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),l.jsxs(sq,{shouldFilter:!1,loop:!0,children:[l.jsxs("div",{id:"palette-inputwrap",children:[l.jsx(ge,{name:"search"}),l.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:o,onValueChange:u})]}),l.jsx(aq,{children:h?y.length===0?l.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return l.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:l.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>l.jsx(iq,{heading:x,children:j.map(S=>l.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:l.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),l.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=o=>(o.session?"s\0"+o.session:"n\0"+o.note)+"\0"+(o.device?.id??""),n=new Map;e.forEach((o,u)=>{if(!o.note&&!o.session)return;const f=n.get(t(o));if(f){f.entries.push(o),f.idx.push(u);return}n.set(t(o),{note:o.note??"",session:o.session,entries:[o],idx:[u]})});const r=[],i=new Set;return e.forEach((o,u)=>{const f=o.note||o.session?n.get(t(o)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const o of e)r++,n.add(o.path),xi(o)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=o=>o.seq?(o.device?.id??"")+"\0"+o.seq:o.time+"\0"+o.path+"\0"+o.kind+"\0"+(o.device?.id??""),r=new Set,i=[];for(const o of[...e,...t]){const u=n(o);r.has(u)||(r.add(u),i.push(o))}return i.sort((o,u)=>Date.parse(u.time)-Date.parse(o.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let o=n.get(i);o||(o={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,o)),!o.agent&&xi(r)&&(o.agent=Mf(r.note)),t&&r.user===t&&(o.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const o of e){const u=t[o.path],f=ay(o.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:o.path,reads:h,days:f})}return i.sort((o,u)=>u.reads-o.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=o=>{let u=o.dir?0:Date.parse(o.time||"")||0;for(const f of o.children||[])u=Math.max(u,r(f));return u},i=[];for(const o of e.children||[]){if(!o.dir)continue;const u=hd(t,o.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(o);i.push({name:o.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((o,u)=>u.reads-o.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,o=t.id,u=Eq(o),f=sy(o),h=RN(o),[m,y]=b.useState(""),g=T2(o),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return l.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return l.jsx("div",{className:"home home-empty",children:l.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,o),H=cn("history",o,"",m?{actor:m}:void 0);return l.jsxs("div",{className:"home",children:[l.jsxs("header",{className:"home-head",children:[l.jsx("h1",{className:"home-greet",children:gq(i?.name)}),l.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&l.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[l.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),l.jsx("div",{className:"home-cards",children:R.map(U=>l.jsxs("a",{className:"home-card",...In(L(U.path)),children:[l.jsxs("span",{className:"hc-name",children:[l.jsx(ge,{name:"doc"}),Vd(U.path)]}),l.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),l.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),l.jsxs("div",{className:"home-grid",children:[l.jsxs("div",{className:"home-main",children:[l.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[l.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&l.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?l.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):l.jsx("ul",{className:"home-list",children:T.map(U=>l.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),l.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Recent activity"}),l.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>l.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?l.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?l.jsx("p",{className:"home-none",children:"No changes yet."}):l.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return l.jsxs("li",{className:"home-fe",children:[l.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:l.jsx(ge,{name:Y?"sparkle":"users"})}),l.jsxs("div",{className:"fe-body",children:[l.jsxs("div",{children:[l.jsx("b",{className:"fe-who",children:ae})," ",l.jsx("span",{className:"fe-what",children:le})]}),W?l.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?l.jsx("span",{className:"fe-path del",children:Z.path}):l.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&l.jsx("span",{className:"fe-dev",children:Z.device.name})]}),l.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):l.jsx("p",{className:"home-none",children:"Loading…"})]})]}),l.jsxs("aside",{className:"home-side",children:[l.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[l.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?l.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):l.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&l.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),l.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[l.jsxs("h2",{className:"home-h",children:[l.jsx(ge,{name:"terminal"}),"Connect another device"]}),l.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),l.jsx(Jl,{code:kf(window.location.origin,{project:t})}),l.jsx("a",{className:"home-more",...In(cn("install",o)),children:"Full setup guide →"})]}),A.length>0&&l.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[l.jsxs("div",{className:"home-row",children:[l.jsx("h2",{className:"home-h",children:"Where reads go"}),l.jsx("a",{className:"home-more",...In(cn("dashboard",o)),children:"Insights →"})]}),l.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>l.jsxs("li",{className:"fresh-"+U.fresh,children:[l.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[l.jsx("span",{children:U.name}),l.jsx("span",{className:"hb-n",children:U.reads})]}),l.jsx("span",{className:"hb-track",children:l.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),l.jsxs("div",{className:"home-legend",children:[l.jsx("span",{className:"fresh-fresh",children:"fresh"}),l.jsx("span",{className:"fresh-aging",children:"aging"}),l.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&l.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:l.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,o,u;return e.kind==="conflict"?(n="alert",u="conflict",r=l.jsxs(l.Fragment,{children:["Sync conflict on ",l.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,o="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=l.jsxs(l.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",l.jsx("b",{children:Vd(e.path)})]}),i=e.path,o="Reply"):(n="clock",u="stale",r=l.jsxs(l.Fragment,{children:[l.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,o="Review"),l.jsxs("li",{className:"home-attn-row "+u,children:[l.jsx("span",{className:"ha-icon","aria-hidden":"true",children:l.jsx(ge,{name:n})}),l.jsxs("div",{className:"ha-text",children:[l.jsx("span",{className:"ha-title",children:r}),l.jsx("span",{className:"ha-sub",children:i})]}),l.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:o})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?l.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?l.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,o]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return l.jsxs("div",{className:"insights",children:[l.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsxs("div",{className:"dl-empty in-blank",children:[l.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),l.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&l.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?l.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return l.jsxs("div",{className:"insights",children:[l.jsxs("div",{className:"in-top",children:[l.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?l.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),l.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>l.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&l.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),l.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),l.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),l.jsx(Pq,{pts:S,th:i,setTh:o,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),l.jsxs("div",{className:"in-split",children:[l.jsxs("section",{className:"in-sec in-sec-map",children:[l.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),l.jsxs("section",{className:"in-sec in-sec-hot",children:[l.jsx("h2",{className:"in-h2",children:"Hot path"}),l.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),l.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),l.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&l.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return l.jsxs("section",{className:"in-sec","data-sec":e.id,children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&l.jsx("p",{className:"in-sub",children:e.sub})]}),l.jsxs("div",{className:"in-sec-tools",children:[e.aside,l.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?l.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],o=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:o("human"),agent:o("agent"),share:o("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return l.jsxs("div",{className:"in-kpis",children:[l.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[l.jsx("div",{className:"in-kpi-l",children:"Reads"}),l.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),l.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?l.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),l.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>l.jsxs("span",{"data-kind":x,children:[l.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[l.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),l.jsxs("div",{className:"in-kpi-v",children:[m,"% ",l.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),l.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:l.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[l.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),l.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&l.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),l.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),l.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[l.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),l.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&l.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),l.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const o=Math.round(Number(r));return Number.isFinite(o)&&o>=1?o:i};return l.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[l.jsxs("label",{children:["Stale after"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),l.jsx("span",{"aria-hidden":!0,children:"·"}),l.jsxs("label",{children:["hot ≥"," ",l.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return l.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?l.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,o)=>Number(o.empty)-Number(i.empty)||o.reads*Math.max(1,o.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return l.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[l.jsxs("div",{className:"in-sec-head",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"in-h2",children:"Fix these first"}),l.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),l.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?l.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):l.jsxs("table",{className:"in-fix-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads · 30d"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Why it's here"}),l.jsx("th",{children:l.jsx("span",{className:"sr-only",children:"Action"})})]})}),l.jsx("tbody",{children:n.map(i=>{const o=i.path.lastIndexOf("/");return l.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[l.jsxs("td",{className:"in-fx-file",children:[l.jsx(AN,{p:i}),l.jsxs("span",{className:"in-fx-name",children:[l.jsx("span",{children:i.path.slice(o+1)}),o>0&&l.jsx("small",{children:i.path.slice(0,o+1)})]})]}),l.jsxs("td",{className:"in-fx-reads",children:[l.jsx("span",{className:"in-fx-track",children:l.jsx(Fq,{p:i,max:r,lens:e.lens})}),l.jsx("span",{className:"in-fx-n",children:i.reads})]}),l.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),l.jsx("td",{className:"in-fx-why",children:Lq(i)}),l.jsx("td",{className:"in-fx-act",children:i.empty?l.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):l.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&l.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const o=e.reduce((m,y)=>m+y.value,0);if(!o||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/o*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),o=n.get(i);o?o.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const o=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:o.reduce((u,f)=>u+f.reads,0),days:qq((o.length?o:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,o)=>i+o[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=o===null?e:e.filter(_=>DN(_.path,f)===o),w=o===null?Bq(e,f):Gq(g,o||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=l.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[l.jsx("button",{className:o===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),o!==null&&l.jsxs(l.Fragment,{children:[l.jsx("span",{"aria-hidden":!0,children:"›"}),l.jsx("span",{className:"cur",children:o||"(root)"}),o&&i(o)&&l.jsx("button",{className:"in-tm-open",onClick:()=>r(o),children:"Open folder"})]}),o===null&&l.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:o===null?"Folder":"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Files"}),l.jsx("th",{children:"Last change"}),l.jsx("th",{children:"Flag"})]})}),l.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>l.jsxs("tr",{children:[l.jsx("td",{children:_.label}),l.jsx("td",{children:_.reads}),l.jsx("td",{children:_.files.length}),l.jsx("td",{children:vc(_.days)}),l.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return l.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,l.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":o===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return l.jsxs("g",{children:[l.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:l.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&l.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&l.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),l.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return l.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",l.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((o,u)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",o]},o))}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),l.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const o=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return o.some(u=>u.top.length)?l.jsx(l.Fragment,{children:o.map(({k:u,total:f,top:h})=>l.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):l.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsxs("th",{children:[Dg[t]," reads"]}),l.jsx("th",{children:"Last change"})]})}),l.jsx("tbody",{children:n.map(o=>l.jsxs("tr",{children:[l.jsx("td",{children:o.path}),l.jsx("td",{children:o[t]}),l.jsx("td",{children:o.orphan?"deleted":vc(o.days)})]},o.path))})]});return l.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:l.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:l.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[l.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&l.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(o=>{const u=()=>o.orphan?e.onOpenHistory(o.path):e.onOpenFile(o.path),f={danger:o[t]>=e.th.hot&&o.danger,empty:o.empty};return l.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(o),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[l.jsxs("span",{className:"in-hp-line",children:[l.jsxs("span",{className:"in-hp-name"+(o.danger||o.empty?" danger":""),children:[l.jsx(AN,{p:{danger:o.danger||f.danger,empty:o.empty}}),o.path]}),o.orphan&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),l.jsx("span",{className:"in-hp-count",children:o[t]})]}),l.jsx("span",{className:"in-hp-bar",children:l.jsx("span",{className:"in-hp-"+t,style:{width:(o[t]/r*100).toFixed(1)+"%"}})})]},o.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const o={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>o.l+m+N/f*(960-o.l-o.r-2*m),g=N=>340-o.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-o.t-o.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-o.r,top:o.t+8,bottom:340-o.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"File"}),l.jsx("th",{children:"Reads"}),l.jsx("th",{children:"Days since change"}),l.jsx("th",{children:"Verdict"})]})}),l.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>l.jsxs("tr",{children:[l.jsx("td",{children:N.path}),l.jsx("td",{children:N.reads}),l.jsx("td",{children:Math.round(N.days)}),l.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return l.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:l.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[l.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[l.jsx("rect",{x:y(t.stale),y:o.t,width:Math.max(0,960-o.r-y(t.stale)),height:Math.max(0,g(t.hot)-o.t),className:"in-danger-zone"}),S.map(N=>l.jsxs("text",{x:y(N),y:340-o.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>l.jsx("text",{x:o.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),l.jsx("line",{x1:y(t.stale),y1:o.t,x2:y(t.stale),y2:340-o.b,className:"in-threshold","data-th":"stale"}),l.jsx("line",{x1:o.l,y1:g(t.hot),x2:960-o.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),l.jsx("line",{x1:o.l,y1:340-o.b,x2:960-o.r,y2:340-o.b,className:"in-axis"}),l.jsx("line",{x1:o.l,y1:o.t,x2:o.l,y2:340-o.b,className:"in-axis"}),l.jsx("text",{x:960-o.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),l.jsx("text",{x:12,y:(o.t+340-o.b)/2,className:"in-label",transform:`rotate(-90 12 ${(o.t+340-o.b)/2})`,children:"reads / 30d (log) →"}),l.jsx("text",{x:y(t.stale)+6,y:o.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),l.jsxs("text",{x:y(t.stale)+92,y:o.t+14,className:"in-quad-count",children:["· ",x]}),l.jsx("text",{x:o.l+6,y:o.t+14,className:"in-quad",children:"hot + fresh"}),l.jsx("text",{x:960-o.r-6,y:340-o.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),l.jsx("text",{x:o.l+6,y:340-o.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>l.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:l.jsx("title",{children:Af(N)})},N.path)),j.map(N=>l.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),l.jsxs("p",{className:"in-legend",children:[l.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",l.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",l.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((o,u)=>o+u.total,0);if(!r)return n;if(e.length>=3){const o=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(o/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(o=>o.total=2){const o=t[t.length-1];n.push({icon:"archive",head:`${o.name||"(root)"}${o.name?"/":""} is the least-read folder by agents`,body:`${Hs(o.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return l.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,o=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(o,r),f=t==="human"||t==="share",h=()=>l.jsxs("table",{className:"in-data-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Device"}),r.map(y=>l.jsx("th",{children:y.name||"(root)"},y.name)),l.jsx("th",{children:"Total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("td",{children:y.name}),r.map(g=>l.jsx("td",{children:i(y.d,g.name)},g.name)),l.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=l.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return l.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&l.jsxs("div",{className:"in-cov",children:[l.jsxs("div",{className:"in-matrix-wrap",children:[l.jsxs("table",{className:"in-matrix",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{}),r.map(y=>l.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),l.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),l.jsx("tbody",{children:o.map(y=>l.jsxs("tr",{children:[l.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return l.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),l.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),l.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>l.jsxs("span",{className:"in-tm-key",children:[l.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&l.jsxs("aside",{className:"in-takeaways",children:[l.jsx("h3",{children:"What this tells you"}),u.map(y=>l.jsxs("div",{className:"in-takeaway",children:[l.jsx(sB,{name:y.icon}),l.jsxs("div",{children:[l.jsx("b",{children:y.head}),l.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,o=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&o({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return l.jsxs("div",{className:"hfilters",children:[l.jsxs("label",{className:"hf-search",children:[l.jsx(ge,{name:"search"}),l.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),l.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>l.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>o({actor:N}),children:R},R))}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"laptop"}),l.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;o({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[l.jsx("option",{value:"",children:"All devices"}),j.length>0&&l.jsx("optgroup",{label:"Devices",children:j.map(N=>l.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&l.jsx("optgroup",{label:"People",children:x.map(N=>l.jsx("option",{value:"u:"+N,children:N},N))})]})]}),l.jsxs("span",{className:"hf-pick",children:[l.jsx(ge,{name:"clock"}),l.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&o({range:void 0});return}y(!1),o({range:R,since:void 0,until:void 0})},children:[l.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>l.jsx("option",{value:N,children:R},N)),l.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&l.jsxs("span",{className:"hf-dates",children:[l.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>o({since:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-dash",children:"–"}),l.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>o({until:N.target.value,range:void 0})}),l.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&l.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const o={...e};for(const u of i)delete o[u];return o},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:o,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&o?.()},[S,o]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&l.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&l.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return l.jsx("div",{className:"activity",children:l.jsxs("div",{className:"history",children:[le,be,E||A?l.jsx(mB,{onRetry:U,timedOut:!E}):_&&l.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return l.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[l.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?l.jsxs("div",{className:"empty hempty",children:[l.jsx("span",{className:"hempty-icon",children:l.jsx(ge,{name:"search"})}),l.jsx("b",{children:"No changes match these filters."}),l.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>l.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,l.jsx(ge,{name:"x"})]},ve))}),l.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),l.jsxs("span",{className:"hempty-actions",children:[l.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&l.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):l.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?l.jsxs("div",{className:"hday",children:[l.jsx("b",{children:dy(Ze)}),l.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?l.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):l.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&l.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?l.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&l.jsx(dB,{})]})}function dB(){return l.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[l.jsx(ge,{name:"hist"}),l.jsx("b",{children:"Select a change"}),l.jsx("span",{children:"Its diff, rendered view and full file appear here."}),l.jsxs("span",{className:"ap-keys",children:[l.jsx("kbd",{children:"J"})," ",l.jsx("kbd",{children:"K"})," move · ",l.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return l.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[l.jsx("div",{className:"hday",children:l.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>l.jsxs("div",{className:"hskel-row",children:[l.jsx("span",{className:"hskel-dot"}),l.jsxs("span",{className:"hskel-lines",children:[l.jsx("span",{style:{width:e+"%"}}),l.jsx("span",{style:{width:e/2+"%"}})]}),l.jsx("span",{className:"hskel-time"})]},t)),l.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return l.jsxs("div",{className:"empty hempty herror",role:"alert",children:[l.jsx("span",{className:"hempty-icon herror-icon",children:l.jsx(ge,{name:"alert"})}),l.jsx("b",{children:"Couldn't load activity"}),l.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),l.jsx("span",{className:"hempty-actions",children:l.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[l.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let o="";try{o=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(o?"&tz="+encodeURIComponent(o):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return l.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return l.jsxs("div",{className:"hsum",children:[l.jsxs("div",{className:"hsum-head",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),l.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",l.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),l.jsxs("div",{className:"hsum-legend",children:[l.jsx("span",{className:"agent",children:"Agents"}),l.jsx("span",{className:"human",children:"People"})]})]}),l.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return l.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[l.jsxs("div",{className:"hsum-stack",children:[l.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),l.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),l.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",o=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return l.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[l.jsxs("div",{className:"ap-head",children:[l.jsx(ge,{name:"doc"}),l.jsx("span",{className:"ap-name",children:o}),l.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:l.jsx(ge,{name:"chev"})}),l.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:l.jsx(ge,{name:"chevd"})}),l.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:l.jsx(ge,{name:"x"})})]}),l.jsx("div",{className:"ap-path",children:t.path}),l.jsxs("div",{className:"ap-who",children:[l.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),l.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&l.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[l.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&l.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[l.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&l.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[l.jsx(ge,{name:"link"}),"Copy link"]})]}),l.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),l.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:o,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return l.jsxs("div",{className:"hrun"+(w?" open":""),children:[l.jsxs("div",{className:"hrun-head",children:[l.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:l.jsx(ge,{name:w?"chevd":"chev"})}),l.jsx("span",{className:"havatar agent","aria-hidden":"true",children:l.jsx(ge,{name:"terminal"})}),l.jsxs("span",{className:"hrun-title",children:[l.jsxs("span",{className:"hrun-what",children:[l.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),l.jsxs("span",{className:"hrun-sub",children:[l.jsx("span",{className:"hrun-note",children:l.jsx(fN,{text:e.note})}),l.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),l.jsx("span",{className:"hrun-time",children:H}),m&&l.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[l.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&l.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>l.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:o(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&l.jsxs("div",{className:"hrun-reads",children:[l.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>l.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[l.jsx("span",{className:"hkind",children:"read"}),l.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&l.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&l.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=o=>o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),o=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-o}function SB(e){const t=e.width??bB,n=i=>o=>{if(o.button!==0)return;o.preventDefault();const u=o.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=o.clientX;let g=null;u.setPointerCapture(o.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>o=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(o.key!==u&&o.key!==f)return;o.preventDefault();const h=$S(o.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(o.key===u?LS:-LS),h))};return l.jsx(l.Fragment,{children:["left","right"].map(i=>l.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=o?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"clock"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),l.jsx("span",{children:"This is not the current file."})]}),l.jsxs("div",{className:"vb-actions",children:[l.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),l.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"alert"})}),l.jsxs("div",{className:"vb-text",children:[l.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),l.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?l.jsxs(l.Fragment,{children:["The other version lives at ",l.jsx("code",{children:t.original})]}):l.jsx(l.Fragment,{children:"The other version kept the original name."})]})]}),n&&l.jsx("div",{className:"vb-actions",children:l.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:o}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!o),w=!i||!!o,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!o&&!!t.reads?.enabled),{data:E}=hE(i&&o?o?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!o&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&o&&Z&&!L&&pq(o.id,M)},[i,o,Z,M,L]),b.useEffect(()=>{(!i||o)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,o,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,o?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,o?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,o?.id,Ne)),ds()},[o?.id]),re=b.useCallback(ie=>gt(cn("history",o?.id,ie)),[o?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!o&&(Z||U)&&Fn(o.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!o&&Fn(Ut(M)??o.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,o?.id,L,!0,r.editing))},[M,o?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,o?.id,L,!1,r.editing),{replace:!0})},[M,o?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(o?.id,i&&!!o),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",o?.id]})},[f,o?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&o?pr?.mounts.find(ie=>ie.project===o.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!o,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!o&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!o&&Fn(o?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",l.jsxs(l.Fragment,{children:[l.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),l.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>l.jsxs("div",{className:"undo-row",children:[l.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&l.jsx("span",{className:"undo-after",children:"changed after this run"}),l.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&l.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&l.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&l.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&o){const Le=o.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:o.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&o&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!o||Le.id!==o.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,o,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?o?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?o?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!o&&t.upload.enabled&&Fn(o.perm,"write"),Io=b.useCallback(ie=>!!o&&Fn(Ut(ie?ie+"/":"")??o.perm,"write"),[o,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,o?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,o?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&o&&Fn(o.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&o?ie=>re(ie):void 0,insights:i&&o?ie=>gt(cn("dashboard",o.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,o,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=l.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:o?cn("install",o.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=l.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:o?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,o?.id,Ne),onFilters:ie=>gt(cn("history",o?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?l.jsx(uN,{}):l.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=l.jsxs("div",{className:"notfound",children:[l.jsx("h1",{children:"Couldn't find that"}),l.jsxs("p",{children:[l.jsx("code",{children:M})," isn't in this project right now."]}),l.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),l.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=l.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!o,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=l.jsxs(l.Fragment,{children:[L&&l.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&l.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=l.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:o?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?l.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=l.jsx(Nq,{project:o,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=l.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"vbanner",role:"status",children:[l.jsx("span",{className:"vb-icon",children:l.jsx(ge,{name:"link"})}),l.jsxs("div",{className:"vb-text",children:[l.jsxs("b",{children:["Moved from ",le.from]}),l.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?l.jsxs(l.Fragment,{children:[l.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&l.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||o?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?o.name:null,Cc=l.jsx(ci,{nav:t.desktop?l.jsxs("span",{id:"nav-btns",children:[l.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:l.jsx(ge,{name:"chevl"})}),l.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:l.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:l.jsxs(l.Fragment,{children:[l.jsx(jV,{people:x,path:M}),Vn&&l.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[l.jsx(ge,{name:"comment"})," ",l.jsx("span",{className:"lbl",children:"Comments"}),z>0&&l.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&l.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[l.jsx(ge,{name:"hist"})," ",l.jsx("span",{className:"lbl",children:"History"})]}),An&&l.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,o?.id,L,r.full,!0));return}const ie=Ln(M,o?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&l.jsx(ge,{name:"pencil"})," ",l.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&l.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&l.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[l.jsx(ge,{name:"link"})," ",l.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&l.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:l.jsx(ge,{name:"expand"})}),Kr&&l.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&l.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&l.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:l.jsx(ge,{name:"dots"})}),Te&&l.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&l.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&l.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&l.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&l.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&l.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!o&&l.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",o?.id,M))},children:"Insights"})]})]})});return l.jsxs(l.Fragment,{children:[l.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:l.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,l.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:l.jsxs(l.Fragment,{children:[!i&&l.jsx(F2,{}),Sc.trim()?l.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):l.jsxs(l.Fragment,{children:[rn&&l.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&l.jsxs("div",{className:"sb-section files-head",children:[l.jsx("span",{children:"Files"}),l.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:l.jsx(ge,{name:"sort"})}),Fa&&l.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:l.jsx(ge,{name:"fileplus"})})]}),l.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?l.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[l.jsx(ge,{name:"shrink"}),l.jsx("span",{className:"lbl",children:"Exit"}),l.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:l.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&l.jsx(b7,{shares:En,canRevoke:!!o&&Fn(o.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&l.jsx(SB,{width:rt,onChange:kt})]})}),je&&o&&l.jsx(x7,{project:o,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,o.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&l.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(o?.perm,"admin")}),l.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[o,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?l.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return l.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=l.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?l.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return l.jsx(li,{vault:W,topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return l.jsx(ri,{to:"/setup"});if(!M)return l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=o?.kind==="hub"?{crumb:"Signup & access",body:l.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Organization not found"}),l.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:l.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?l.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):l.jsxs(li,{vault:W,projectsNav:l.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:l.jsx(ci,{}),children:[l.jsx(go,{children:l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"Project not found"}),l.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),l.jsx("p",{children:l.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?l.jsx(lU,{projects:g}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No agent access on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?l.jsx(GU,{url:e.billing.url}):l.jsxs("div",{className:"empty",children:[l.jsx("h3",{children:"No billing on this hub"}),l.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:l.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:l.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return l.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return l.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return l.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:o?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return l.jsxs(l.Fragment,{children:[l.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:l.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"rail-mark",children:l.jsx(Sv,{size:20})}),l.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:l.jsx(PU,{pid:M.id,menu:P}),orgBar:l.jsxs(l.Fragment,{children:[l.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!o&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),l.jsx(li,{vault:l.jsx(mf,{name:"BearDrive",beta:!0}),topbar:l.jsx(ci,{}),children:l.jsx(go,{children:l.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?l.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):l.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:l.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return l.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?l.jsx(kB,{config:e}):l.jsx(MB,{config:e}):l.jsx(li,{vault:l.jsx(mf,{name:"…",showSignout:!1}),topbar:l.jsx(ci,{}),children:l.jsx("div",{className:"empty",children:"Loading…"})}),l.jsx(VL,{}),l.jsx(ZL,{}),l.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},o=e.path;if(!o||e.view||e.version||e.editing||!t(o))return[...r,i];const u=encodeURIComponent(o);return[...r,{queryKey:["render",n,o,""],url:n+"render?path="+u},i,{queryKey:["comments",n,o],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?l.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[l.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),l.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),l.jsx("p",{className:"mb-4",children:l.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),l.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(l.jsx(b.StrictMode,{children:l.jsx(LB,{children:l.jsx(NM,{client:$N,children:l.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,l as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-2j3g1r__.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-B7FU_dFL.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` +`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` +`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!l,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&o.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&o.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,l.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,o as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-jBqmYsT3.js b/internal/webapp/static/assets/sharedfile-jBqmYsT3.js deleted file mode 100644 index 7a4b295b..00000000 --- a/internal/webapp/static/assets/sharedfile-jBqmYsT3.js +++ /dev/null @@ -1,16 +0,0 @@ -import{H as ht,h as dn,i as Ut,k as Fo,f as yr,e as kr,l as gn,m as Bo}from"./index-BROkyUpj.js";const Z=()=>new Map,ws=e=>{const t=Z();return e.forEach((n,s)=>{t.set(s,n)}),t},mt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Vo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},jo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Ft=()=>new Set,ns=e=>e[e.length-1],Ho=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return At((this._observers.get(t)||Z()).values()).forEach(s=>s(...n))}destroy(){this._observers=Z()}}class Jo{constructor(){this._observers=Z()}on(t,n){mt(this._observers,t,Ft).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return At((this._observers.get(t)||Z()).values()).forEach(s=>s(...n))}destroy(){this._observers=Z()}}const ct=Math.floor,kn=Math.abs,Rs=(e,t)=>ee>t?e:t,Wo=Math.pow,Qr=e=>e!==0?e<0:1/e<0,Sr=1,br=2,ss=4,rs=8,je=32,Dt=64,et=128,Fn=31,ms=63,Xt=127,Yo=2147483647,En=Number.MAX_SAFE_INTEGER,_r=Number.MIN_SAFE_INTEGER,zo=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&ct(e)===e),Zr=String.fromCharCode,Go=e=>e.toLowerCase(),qo=/^\s*/g,Xo=e=>e.replace(qo,""),Ko=/([A-Z])/g,Er=(e,t)=>Xo(e.replace(Ko,n=>`${t}${Go(n)}`)),Qo=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rHe.encode(e),tl=He?Zo:Qo;let Be=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Be&&Be.decode(new Uint8Array).length===1&&(Be=null);const el=(e,t)=>Po(t,()=>e).join("");class Ke{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const G=()=>new Ke,Us=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Us(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ys=J,b=(e,t)=>{for(;t>Xt;)J(e,et|Xt&t),t=ct(t/128);J(e,Xt&t)},Ms=(e,t)=>{const n=Qr(t);for(n&&(t=-t),J(e,(t>ms?et:0)|(n?Dt:0)|ms&t),t=ct(t/64);t>0;)J(e,(t>Xt?et:0)|Xt&t),t=ct(t/128)},ks=new Uint8Array(3e4),sl=ks.length/3,rl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;b(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Rs(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ee(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},$=(e,t)=>{b(e,t.byteLength),Bn(e,t)},vs=(e,t)=>{nl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},ol=(e,t)=>vs(e,4).setFloat32(0,t,!1),ll=(e,t)=>vs(e,8).setFloat64(0,t,!1),cl=(e,t)=>vs(e,8).setBigInt64(0,t,!1),Cr=new DataView(new ArrayBuffer(4)),al=e=>(Cr.setFloat32(0,e),Cr.getFloat32(0)===e),Pe=(e,t)=>{switch(typeof t){case"string":J(e,119),Kt(e,t);break;case"number":zo(t)&&kn(t)<=Yo?(J(e,125),Ms(e,t)):al(t)?(J(e,124),ol(e,t)):(J(e,123),ll(e,t));break;case"bigint":J(e,122),cl(e,t);break;case"object":if(t===null)J(e,126);else if(ye(t)){J(e,117),b(e,t.length);for(let n=0;n0&&b(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Ar=e=>{e.count>0&&(Ms(e.encoder,e.count===1?e.s:-e.s),e.count>1&&b(e.encoder,e.count-2))};class Sn{constructor(){this.encoder=new Ke,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Ar(this),this.count=1,this.s=t)}toUint8Array(){return Ar(this),M(this.encoder)}}const Ir=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ms(e.encoder,t),e.count>1&&b(e.encoder,e.count-2)}};class is{constructor(){this.encoder=new Ke,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Ir(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Ir(this),M(this.encoder)}}class hl{constructor(){this.sarr=[],this.s="",this.lensE=new Sn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Ke;return this.sarr.push(this.s),this.s="",Kt(t,this.sarr.join("")),Bn(t,this.lensE.toUint8Array()),M(t)}}const gt=e=>new Error(e),lt=()=>{throw gt("Method unimplemented")},nt=()=>{throw gt("Unexpected case")},ti=gt("Unexpected end of array"),ei=gt("Integer out of Range");class Vn{constructor(t){this.arr=t,this.pos=0}}const jt=e=>new Vn(e),ul=e=>e.pos!==e.arr.length,fl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},z=e=>fl(e,E(e)),ke=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posEn)throw ei}throw ti},Ns=e=>{let t=e.arr[e.pos++],n=t&ms,s=64;const r=(t&Dt)>0?-1:1;if((t&et)===0)return r*n;const i=e.arr.length;for(;e.posEn)throw ei}throw ti},dl=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(ke(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ke(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},gl=e=>Be.decode(z(e)),Nt=Be?gl:dl,$s=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},pl=e=>$s(e,4).getFloat32(0,!1),wl=e=>$s(e,8).getFloat64(0,!1),ml=e=>$s(e,8).getBigInt64(0,!1),yl=[e=>{},e=>null,Ns,pl,wl,ml,e=>!1,e=>!0,Nt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;syl[127-ke(e)](e);class Tr extends Vn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),ul(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class bn extends Vn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ns(this);const t=Qr(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class os extends Vn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Ns(this),n=t&1;this.diff=ct(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class kl{constructor(t){this.decoder=new bn(t),this.str=Nt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Sl=crypto.getRandomValues.bind(crypto),ni=()=>Sl(new Uint32Array(1))[0],bl="10000000-1000-4000-8000"+-1e11,_l=()=>bl.replace(/[018]/g,e=>(e^ni()&15>>e/4).toString(16)),Bt=Date.now,xr=e=>new Promise(e);Promise.all.bind(Promise);const Lr=e=>e===void 0?null:e;class El{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let si=new El,Fs=!0;try{typeof localStorage<"u"&&localStorage&&(si=localStorage,Fs=!1)}catch{}const ri=si,Cl=e=>Fs||addEventListener("storage",e),Dl=e=>Fs||removeEventListener("storage",e),We=Symbol("Equality"),ii=(e,t)=>e===t||!!e?.[We]?.(t)||!1,Al=e=>typeof e=="object",Il=Object.assign,Tl=Object.keys,xl=(e,t)=>{for(const n in e)t(e[n],n)},Ll=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Cn=e=>Tl(e).length,Ol=e=>{for(const t in e)return!1;return!0},Qe=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Bs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Rl=(e,t)=>e===t||Cn(e)===Cn(t)&&Qe(e,(n,s)=>(n!==void 0||Bs(t,s))&&ii(t[s],n)),Ul=Object.freeze,oi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&oi(e[t])}return Ul(e)},Vs=(e,t,n=0)=>{try{for(;ne,fe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[We]!=null)return e[We](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var li={};const Vt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ci=typeof window<"u"&&typeof document<"u"&&!Vt;let ut;const Nl=()=>{if(ut===void 0)if(Vt){ut=Z();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");ut.set(`--${Er(t,"-")}`,n),ut.set(`-${Er(t,"-")}`,n)}})):ut=Z();return ut},Ss=e=>Nl().has(e),Dn=e=>Lr(Vt?li[e.toUpperCase().replaceAll("-","_")]:ri.getItem(e)),ai=e=>Ss("--"+e)||Dn(e)!==null,$l=ai("production"),Fl=Vt&&vl(li.FORCE_COLOR,["true","1","2"]),Bl=Fl||!Ss("--no-colors")&&!ai("no-color")&&(!Vt||process.stdout.isTTY)&&(!Vt||Ss("--color")||Dn("COLORTERM")!==null||(Dn("TERM")||"").includes("color")),hi=e=>new Uint8Array(e),Vl=(e,t,n)=>new Uint8Array(e,t,n),jl=e=>new Uint8Array(e),Hl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Jl=e=>{const t=atob(e),n=hi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Vl(t.buffer,t.byteOffset,t.byteLength)},Yl=ci?Hl:Pl,zl=ci?Jl:Wl,Gl=e=>{const t=hi(e.byteLength);return t.set(e),t};class ql{constructor(t,n){this.left=t,this.right=n}}const Ct=(e,t)=>new ql(e,t),Xl=(e,t)=>e.forEach(n=>t(n.left,n.right)),Or=e=>e.next()>=.5,ls=(e,t,n)=>ct(e.next()*(n+1-t)+t),ui=(e,t,n)=>ct(e.next()*(n+1-t)+t),js=(e,t,n)=>ui(e,t,n),Kl=e=>Zr(js(e,97,122)),Ql=(e,t=0,n=20)=>{const s=js(e,t,n);let r="";for(let i=0;it[js(e,0,t.length-1)],Zl=Symbol("0schema");class tc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(el(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const bs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[We]?ii(e,t):ye(e)?xs(e,n=>Ls(t,s=>bs(n,s))):Al(e)?Qe(e,(n,s)=>bs(n,t[s])):!1;class X{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),bs(n,s)}equals(t){return this.constructor===t.constructor&&fe(this.shape,t.shape)}[Zl](){return!0}[We](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){lt()}get nullable(){return Ie(this,Wn)}get optional(){return new gi(this)}cast(t){return Rr(t,this),t}expect(t){return Rr(t,this),t}}class Hs extends X{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const j=(e,t=null)=>new Hs(e,t);j(Hs);class Ps extends X{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const Y=e=>new Ps(e);j(Ps);class jn extends X{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Hn=(...e)=>new jn(e),fi=j(jn),ec=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),di=e=>{if(Se.check(e))return[ec(e)];if(fi.check(e))return e.shape.map(t=>t+"");if(Ei.check(e))return["[+-]?\\d+.?\\d*"];if(Ci.check(e))return[".*"];if(An.check(e))return e.shape.map(di).flat(1);nt()};class nc extends X{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}j(nc);const sc=Symbol("optional");class gi extends X{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[sc](){return!0}}const rc=j(gi);class ic extends X{check(t,n){return n?.extend(null,"never",typeof t),!1}}j(ic);class Pn extends X{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Pn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):Qe(this.shape,(s,r)=>{const i=this._isPartial&&!Bs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const oc=e=>new Pn(e),lc=j(Pn),cc=Y(e=>e!=null&&(e.constructor===Object||e.constructor==null));class pi extends X{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&Qe(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const wi=(e,t)=>new pi(e,t),ac=j(pi);class mi extends X{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&Qe(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const hc=(...e)=>new mi(e);j(mi);class yi extends X{constructor(t){super(),this.shape=t.length===1?t[0]:new Js(t)}check(t,n){const s=ye(t)&&xs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const ki=(...e)=>new yi(e),uc=j(yi),fc=Y(e=>ye(e));class Si extends X{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const dc=(e,t=null)=>new Si(e,t);j(Si);const gc=dc(X);class pc extends X{constructor(t){super(),this.len=t.length-1,this.args=hc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const wc=j(pc),mc=Y(e=>typeof e=="function");class yc extends X{constructor(t){super(),this.shape=t}check(t,n){const s=xs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}j(yc,e=>e.shape.length>0);class Js extends X{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ls(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ie=(...e)=>e.findIndex(t=>An.check(t))>=0?Ie(...e.map(t=>Ye(t)).map(t=>An.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Js(e),An=j(Js),bi=()=>!0,In=Y(bi),kc=j(Ps,e=>e.shape===bi),Ws=Y(e=>typeof e=="bigint"),Sc=Y(e=>e===Ws),_i=Y(e=>typeof e=="symbol");Y(e=>e===_i);const de=Y(e=>typeof e=="number"),Ei=Y(e=>e===de),Se=Y(e=>typeof e=="string"),Ci=Y(e=>e===Se),Jn=Y(e=>typeof e=="boolean"),bc=Y(e=>e===Jn),Di=Hn(void 0);j(jn,e=>e.shape.length===1&&e.shape[0]===void 0);Hn(void 0);const Wn=Hn(null),_c=j(jn,e=>e.shape.length===1&&e.shape[0]===null);j(Uint8Array);j(Hs,e=>e.shape===Uint8Array);const Ec=Ie(de,Se,Wn,Di,Ws,Jn,_i);(()=>{const e=ki(In),t=wi(Se,In),n=Ie(de,Se,Wn,Jn,e,t);return e.shape=n,t.shape.values=n,n})();const Ye=e=>{if(gc.check(e))return e;if(cc.check(e)){const t={};for(const n in e)t[n]=Ye(e[n]);return oc(t)}else{if(fc.check(e))return Ie(...e.map(Ye));if(Ec.check(e))return Hn(e);if(mc.check(e))return j(e)}nt()},Rr=$l?()=>{}:(e,t)=>{const n=new tc;if(!t.check(e,n))throw gt(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Cc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ye(t),h:n}),this}else(t){return this.if(In,t)}done(){return(t,n)=>{for(let s=0;snew Cc(e),Ai=Dc(In).if(Ei,(e,t)=>ls(t,_r,En)).if(Ci,(e,t)=>Ql(t)).if(bc,(e,t)=>Or(t)).if(Sc,(e,t)=>BigInt(ls(t,_r,En))).if(An,(e,t)=>oe(t,cs(t,e.shape))).if(lc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(rc.check(r)){if(Or(t))continue;r=r.shape}n[s]=Ai(r,t)}return n}).if(uc,(e,t)=>{const n=[],s=ui(t,0,42);for(let r=0;rcs(t,e.shape)).if(_c,(e,t)=>null).if(wc,(e,t)=>{const n=oe(t,e.res);return()=>n}).if(kc,(e,t)=>oe(t,cs(t,[de,Se,Wn,Di,Ws,Jn,ki(de),wi(Ie("a","b","c"),de)]))).if(ac,(e,t)=>{const n={},s=ls(t,0,3);for(let r=0;rAi(Ye(t),e),yt=typeof document<"u"?document:{},Ac=e=>yt.createElement(e),Ic=()=>yt.createDocumentFragment();Y(e=>e.nodeType===Nc);const Tc=e=>yt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const xc=(e,t)=>(Xl(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Lc=e=>{const t=Ic();for(let n=0;n(Ii(e,Lc(t)),e),Ph=(e,t=[],n=[])=>Oc(xc(Ac(e),t),n);Y(e=>e.nodeType===Uc);const Jh=Tc;Y(e=>e.nodeType===Mc);const Rc=e=>Vo(e,(t,n)=>`${n}:${t};`).join(""),Ii=(e,t)=>e.appendChild(t),Uc=yt.ELEMENT_NODE,Mc=yt.TEXT_NODE;yt.CDATA_SECTION_NODE;yt.COMMENT_NODE;const vc=yt.DOCUMENT_NODE;yt.DOCUMENT_TYPE_NODE;const Nc=yt.DOCUMENT_FRAGMENT_NODE;Y(e=>e.nodeType===vc);const It=Symbol,Ti=It(),xi=It(),$c=It(),Fc=It(),Bc=It(),Li=It(),Vc=It(),Ys=It(),jc=It(),Hc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=Z();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Oi(e)),Ui.forEach(t=>t.print(e))},Ri=(...e)=>{console.warn(...Oi(e)),e.unshift(Ys),Ui.forEach(t=>t.print(e))},Ui=Ft(),Mi=e=>({[Symbol.iterator](){return this},next:e}),Yc=(e,t)=>Mi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),as=(e,t)=>Mi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Yn{constructor(t,n){this.clock=t,this.len=n}}class Te{constructor(){this.clients=new Map}}const be=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=ct((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&zc(n,t.clock)!==null},zs=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Yn(r.clock,ee(r.len,i.clock+i.len-r.clock)):(s{const t=new Te;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{mt(e.clients,t,()=>[]).push(new Yn(n,s))},Gc=()=>new Te,qc=e=>{const t=Gc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},xe=(e,t)=>{b(e.restEncoder,t.clients.size),At(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),b(e.restEncoder,n);const r=s.length;b(e.restEncoder,r);for(let i=0;i{const t=new Te,n=E(e.restDecoder);for(let s=0;s0){const o=mt(t.clients,r,()=>[]);for(let l=0;l{const s=new Te,r=E(e.restDecoder);for(let i=0;i0){const i=new Qt;return b(i.restEncoder,0),xe(i,s),i.toUint8Array()}return null},vi=ni;class ne extends Os{constructor({guid:t=_l(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=vi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Gi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=xr(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>xr(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&O(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(At(this.subdocs).map(t=>t.guid))}transact(t,n=null){return O(this,t,n)}get(t,n=W){const s=mt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==W&&r!==n)if(r===W){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,we)}getText(t=""){return this.get(t,Ce)}getMap(t=""){return this.get(t,Ee)}getXmlElement(t=""){return this.get(t,De)}getXmlFragment(t=""){return this.get(t,Zt)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,At(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ne({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,O(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Ni{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class $i extends Ni{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return ke(this.restDecoder)}readString(){return Nt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Je(this.restDecoder)}readBuf(){return Gl(z(this.restDecoder))}readJSON(){return JSON.parse(Nt(this.restDecoder))}readKey(){return Nt(this.restDecoder)}}class Xc{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class _e extends Xc{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new os(z(t)),this.clientDecoder=new bn(z(t)),this.leftClockDecoder=new os(z(t)),this.rightClockDecoder=new os(z(t)),this.infoDecoder=new Tr(z(t),ke),this.stringDecoder=new kl(z(t)),this.parentInfoDecoder=new Tr(z(t),ke),this.typeRefDecoder=new bn(z(t)),this.lenDecoder=new bn(z(t))}readLeftID(){return new ge(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ge(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Je(this.restDecoder)}readBuf(){return z(this.restDecoder)}readJSON(){return Je(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ee(s,t[0].id.clock);const r=pt(t,s);b(e.restEncoder,t.length-r),e.writeClient(n),b(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{F(t,i)>r&&s.set(i,r)}),zn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),b(e.restEncoder,s.size),At(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{Kc(e,t.clients.get(r),r,i)})},Qc=(e,t)=>{const n=Z(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=At(n.keys()).sort((f,g)=>f-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Gi,c=new Map,a=(f,g)=>{const y=c.get(f);(y==null||y>g)&&c.set(f,g)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const g=f.id.client,y=n.get(g);y?(y.i--,l.clients.set(g,y.refs.slice(y.i)),n.delete(g),y.i=0,y.refs=[]):l.clients.set(g,[f]),r=r.filter(S=>S!==g)}s.length=0};for(;;){if(u.constructor!==it){const g=mt(h,u.id.client,()=>F(t,u.id.client))-u.id.clock;if(g<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,F(t,y)),d();else{u=S.refs[S.i++];continue}}else(g===0||g0)u=s.pop();else if(o!==null&&o.i0){const f=new Qt;return qs(f,l,new Map),b(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ta=(e,t)=>qs(e,t.doc.store,t.beforeState),ea=(e,t,n,s=new _e(e))=>O(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=Qc(s,o),a=Zc(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=xn([u.update,a.update])}}else l.pendingStructs=a;const h=Ur(s,r,l);if(l.pendingDs){const d=new _e(jt(l.pendingDs));E(d.restDecoder);const f=Ur(d,r,l);h&&f?l.pendingDs=xn([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Vi(r.doc,d)}},n,!1),Vi=(e,t,n,s=_e)=>{const r=jt(t);ea(r,e,n,new s(r))},ji=(e,t,n)=>Vi(e,t,n,$i),na=(e,t,n=new Map)=>{qs(e,t.store,n),xe(e,qc(t.store))},sa=(e,t=new Uint8Array([0]),n=new Qt)=>{const s=Pi(t);na(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ea(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===tn)return ba(r.map((i,o)=>o===0?i:Da(i)));if(n.constructor===Qt)return xn(r)}return r[0]},Hi=(e,t)=>sa(e,t,new tn),ra=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sra(new Ni(jt(e))),Ji=(e,t)=>(b(e.restEncoder,t.size),At(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{b(e.restEncoder,n),b(e.restEncoder,s)}),e),ia=(e,t)=>Ji(e,zn(t.store)),oa=(e,t=new Bi)=>(e instanceof Map?Ji(t,e):ia(t,e),t.toUint8Array()),la=e=>oa(e,new Fi);class ca{constructor(){this.l=[]}}const Mr=()=>new ca,vr=(e,t)=>e.l.push(t),Nr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Wi=(e,t,n)=>Vs(e.l,[t,n]);class ge{constructor(t,n){this.client=t,this.clock=n}}const ue=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new ge(e,t),Yi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw nt()},Tn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class zi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Wh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},aa=e=>new zi(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ha{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ua=(e,t,n=0)=>new ha(e,t,n),pn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Yi(e):s=D(e._item.id.client,e._item.id.clock),new zi(s,r,t,n)},Yh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return pn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return pn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return pn(e,s.lastId,n);s=s.right}return pn(e,null,n)},fa=(e,t)=>{const n=pe(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},da=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(F(s,r.client)<=r.clock)return null;const u=n?As(s,r):fa(s,r),h=u.item;if(!(h instanceof R))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(F(s,i.client)<=i.clock)return null;const{item:u}=n?As(s,i):{item:pe(s,i)};if(u instanceof R&&u.content instanceof kt)c=u.content.type;else return null}else throw nt();l>=0?a=c._length:a=0}return ua(c,a,e.assoc)},zh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ue(e.item,t.item)&&ue(e.type,t.type)&&e.assoc===t.assoc,ae=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Ze(t.ds,e.id),Es=(e,t)=>{const n=mt(e.meta,Es,Ft),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Gi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const zn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},F=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},qi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw nt()}n.push(t)},pt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=ct(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[pt(n,t.clock)]},pe=ga,Cs=(e,t,n)=>{const s=pt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Cs(e,n,t.clock)]},$r=(e,t,n)=>{const s=t.clients.get(n.client),r=pt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==rt&&s.splice(r+1,0,vn(e,i,n.clock-i.id.clock+1)),i},pa=(e,t,n)=>{const s=e.clients.get(t.id.client);s[pt(s,t.id.clock)]=n},Xi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Cs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!jo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(zs(t.deleteSet),ta(e,t),xe(e,t.deleteSet),!0),Br=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&mt(e.changed,t,Ft).add(n)},_n=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof R&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ma=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=pt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Rs(r.length-1,1+pt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+_n(r,c)}})},Ki=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Wi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ba(n)})}),Vs(l,[])}finally{s.gc&&ma(i,r,s.gcFilter),ya(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),g=ee(pt(f,d),1);for(let y=f.length-1;y>=g;)y-=1+_n(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),g=pt(f,d);g+11||g>0&&_n(f,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Wc(Ys,Ti,"[yjs] ",xi,Li,"Changed the client-id because another client seems to be using it."),s.clientID=vi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new tn;Fr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new Qt;Fr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):Ki(e,t+1)}}},O=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new wa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&Ki(r,0)}}return o};class ka{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Vr=(e,t,n)=>{be(e,n.deletions,s=>{s instanceof R&&t.scope.some(r=>r===e.doc||Tn(r,s))&&sr(s,!1)})},jr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;O(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;be(l,a.insertions,f=>{if(f instanceof R){if(f.redone!==null){let{item:g,diff:y}=As(c,f.id);y>0&&(g=Q(l,D(g.id.client,g.id.clock+y))),f=g}!f.deleted&&i.some(g=>g===l.doc||Tn(g,f))&&h.push(f)}}),be(l,a.deletions,f=>{f instanceof R&&i.some(g=>g===l.doc||Tn(g,f))&&!Ze(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=wo(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const g=h[f];e.deleteFilter(g)&&(g.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class Gh extends Os{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=ye(t)?t[0].doc:t instanceof ne?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Te;c.afterState.forEach((S,w)=>{const _=c.beforeState.get(w)||0,L=S-_;L>0&&ze(d,w,_,L)});const f=Bt();let g=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=_s([S.deletions,c.deleteSet]),S.insertions=_s([S.insertions,d])}else h.push(new ka(c.deleteSet,d)),g=!0;!a&&!u&&(this.lastChange=f),be(c,c.deleteSet,S=>{S instanceof R&&this.scope.some(w=>w===c.doc||Tn(w,S))&&sr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=ye(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof W?s.doc!==this.doc:s!==this.doc)&&Ri("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Vr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Vr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=jr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=jr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Sa(e){const t=E(e.restDecoder);for(let n=0;nxn(e,$i,tn),_a=(e,t)=>{if(e.constructor===rt){const{client:n,clock:s}=e.id;return new rt(D(n,s+t),e.length-t)}else if(e.constructor===it){const{client:n,clock:s}=e.id;return new it(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new R(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},xn=(e,t=_e,n=Qt)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(jt(u)));let r=s.map(u=>new Xs(u,!0)),i=null;const o=new n,l=new Ks(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const g=d.curr.id.clock-f.curr.id.clock;return g===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===it?1:-1:g}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Mt(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===it?i.struct.length-=g:d=_a(d,g)),i.struct.mergeWith(d)||(Mt(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==it;d=u.next())Mt(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Mt(l,i.struct,i.offset),i=null),Qs(l);const c=s.map(u=>Gs(u)),a=_s(c);return xe(o,a),o.toUint8Array()},Ea=(e,t,n=_e,s=Qt)=>{const r=Pi(t),i=new s,o=new Ks(i),l=new n(jt(e)),c=new Xs(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===it){c.next();continue}if(u.id.clock+u.length>d)for(Mt(o,u,ee(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Mt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}Qs(o);const a=Gs(l);return xe(i,a),i.toUint8Array()},Qi=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:M(e.encoder.restEncoder)}),e.encoder.restEncoder=G(),e.written=0)},Mt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Qi(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Qs=e=>{Qi(e);const t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n{const r=new n(jt(e)),i=new Xs(r,!1),o=new s,l=new Ks(o);for(let a=i.curr;a!==null;a=i.next())Mt(l,t(a),0);Qs(l);const c=Gs(r);return xe(o,c),o.toUint8Array()},Da=e=>Ca(e,Ml,_e,tn),Hr="You must not compute changes after the event-handler fired.";class Gn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Aa(this.currentTarget,this.target))}deletes(t){return Ze(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw gt(Hr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ns(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ns(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ns(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw gt(Hr);const n=this.target,s=Ft(),r=Ft(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Aa=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},q=()=>{Ri("Invalid access: Add Yjs type to a document before reading data.")},Zi=80;let Zs=0;class Ia{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Zs++}}const Ta=e=>{e.timestamp=Zs++},to=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Zs++},xa=(e,t,n)=>{if(e.length>=Zi){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>kn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&kn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ee(t,r.index+n))}},Xn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;mt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Wi(s._eH,n,t)};class W{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Mr(),this._dEH=Mr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw lt()}clone(){throw lt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){vr(this._eH,t)}observeDeep(t){vr(this._dEH,t)}unobserve(t){Nr(this._eH,t)}unobserveDeep(t){Nr(this._dEH,t)}toJSON(){}}const eo=(e,t,n)=>{e.doc??q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},no=e=>{e.doc??q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return qe(e,(s,r)=>{n.push(t(s,r,e))}),n},La=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},ro=(e,t)=>{e.doc??q();const n=qn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new te(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new en(new Uint8Array(h))),r.integrate(e,0);break;case ne:r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new nn(h)),r.integrate(e,0);break;default:if(h instanceof W)r=new R(D(o,F(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new kt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},io=()=>gt("Length exceeded!"),oo=(e,t,n,s)=>{if(n>t._length)throw io();if(n===0)return t._searchMarker&&Ge(t._searchMarker,n,s.length),Ln(e,t,null,s);const r=n,i=qn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Ln(e,t,r,n)},lo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=qn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw io();t._searchMarker&&Ge(t._searchMarker,r,-i+s)},On=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},tr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new te([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new te([s]);break;case Uint8Array:l=new en(s);break;case ne:l=new nn(s);break;default:if(s instanceof W)l=new kt(s);else throw new Error("Unexpected content type")}new R(D(o,F(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},er=(e,t)=>{e.doc??q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},co=e=>{const t={};return e.doc??q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},ao=(e,t)=>{e.doc??q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ra=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&ae(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},wn=e=>(e.doc??q(),Yc(e._map.entries(),t=>!t[1].deleted));class Ua extends Gn{}class we extends W{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new we;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new we}clone(){const t=new we;return t.insert(0,this.toArray().map(n=>n instanceof W?n.clone():n)),t}get length(){return this.doc??q(),this._length}_callObserver(t,n){super._callObserver(t,n),Xn(this,t,new Ua(this,t))}insert(t,n){this.doc!==null?O(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?O(this.doc,n=>{Oa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?O(this.doc,s=>{lo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return ro(this,t)}toArray(){return no(this)}slice(t=0,n=this.length){return eo(this,t,n)}toJSON(){return this.map(t=>t instanceof W?t.toJSON():t)}map(t){return so(this,t)}forEach(t){qe(this,t)}[Symbol.iterator](){return La(this)}_write(t){t.writeTypeRef(rh)}}const Ma=e=>new we;class va extends Gn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ee extends W{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return this.forEach((n,s)=>{t.set(s,n instanceof W?n.clone():n)}),t}_callObserver(t,n){Xn(this,t,new va(this,t,n))}toJSON(){this.doc??q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof W?r.toJSON():r}}),t}get size(){return[...wn(this)].length}keys(){return as(wn(this),t=>t[0])}values(){return as(wn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return as(wn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return er(this,t)}has(t){return ao(this,t)}clear(){this.doc!==null?O(this.doc,t=>{this.forEach(function(n,s,r){On(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ih)}}const Na=e=>new Ee,vt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Rl(e,t);class Ds{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&nt(),this.right.content.constructor===H?this.right.deleted||Le(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Pr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===H?t.right.deleted||Le(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?qn(t,n):null;if(i){const o=new Ds(i.p.left,i.p,i.index,r);return Pr(e,o,n-i.index)}else{const o=new Ds(null,t._start,0,r);return Pr(e,o,n)}},ho=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===H&&vt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new R(D(i,F(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new H(l,o));u.integrate(e,0),n.right=u,n.forward()})},Le=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},uo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===H&&vt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},fo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!vt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new R(D(i,F(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new H(l,c)),n.right.integrate(e,0),n.forward()}}return o},hs=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;uo(n,r);const l=fo(e,t,n,r),c=s.constructor===String?new wt(s):s instanceof W?new kt(s):new se(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ge(t._searchMarker,n.index,c.getLength()),u=new R(D(o,F(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),ho(e,t,n,l)},Jr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;uo(n,r);const l=fo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===H));){if(!n.right.deleted)switch(n.right.content.constructor){case H:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(vt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new R(D(o,F(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new wt(c)),n.right.integrate(e,0),n.forward()}ho(e,t,n,l)},go=(e,t,n,s,r)=>{let i=t;const o=Z();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===H){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===H){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Le(r,a)}}t=t.right}return l},$a=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===H){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Fa=e=>{let t=0;return O(e.doc,n=>{let s=e._start,r=e._start,i=Z();const o=ws(i);for(;r;)r.deleted===!1&&(r.content.constructor===H?Le(o,r.content):(t+=go(n,s,r,i,o),i=ws(o),s=r)),r=r.right}),t},Ba=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&Xi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===H&&o.constructor!==rt&&t.add(o.parent)})}O(n,s=>{be(e,e.deleteSet,r=>{if(r instanceof rt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===H?t.add(i):$a(s,r)});for(const r of t)Fa(r)})},Wr=(e,t,n)=>{const s=n,r=ws(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case kt:case se:case wt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];O(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((g,y)=>{g!==null&&(f.attributes[y]=g)}))),a="";break;case"retain":u>0&&(f={retain:u},Ol(c)||(f.attributes=Il({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case kt:case se:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case wt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case H:{const{key:f,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;vt(y,g)?g!==null&&o.delete(s):(l==="retain"&&d(),vt(g,i.get(f)??null)?delete c[f]:c[f]=g)}}else if(this.deletes(o)){i.set(f,g);const y=r.get(f)??null;vt(y,g)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,g);const y=c[f];y!==void 0&&(vt(y,g)?y!==null&&o.delete(s):(l==="retain"&&d(),g===null?delete c[f]:c[f]=g))}o.deleted||(l==="insert"&&d(),Le(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ce extends W{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ce}clone(){const t=new Ce;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Va(this,t,n);Xn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===wt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?O(this.doc,s=>{const r=new Ds(null,this._start,0,new Map);for(let i=0;i0)&&hs(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Jr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Wr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??q();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((g,y)=>{d=!0,h[y]=g});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(ae(c,t)||n!==void 0&&ae(c,n))switch(c.content.constructor){case wt:{const h=i.get("ychange");t!==void 0&&!ae(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!ae(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case kt:case se:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,g)=>{d[g]=f})}r.push(h);break}case H:ae(c,t)&&(a(),Le(i,c.content));break}c=c.right}a()};return t||n?O(o,h=>{t&&Es(h,t),n&&Es(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),hs(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!s);hs(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?O(s,r=>{Wr(r,mn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?O(r,i=>{const o=mn(i,this,t,!1);o.right!==null&&Jr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return er(this,t)}getAttributes(){return co(this)}_write(t){t.writeTypeRef(oh)}}const ja=e=>new Ce;class us{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??q()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===De||n.constructor===Zt)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Zt extends W{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Zt}clone(){const t=new Zt;return t.insert(0,this.toArray().map(n=>n instanceof W?n.clone():n)),t}get length(){return this.doc??q(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new us(this,t)}querySelector(t){t=t.toUpperCase();const s=new us(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),At(new us(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Xn(this,t,new Ja(this,n,t))}toString(){return so(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),qe(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?O(this.doc,s=>{oo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)O(this.doc,s=>{const r=t&&t instanceof W?t._item:t;Ln(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw gt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?O(this.doc,s=>{lo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return no(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return ro(this,t)}slice(t=0,n=this.length){return eo(this,t,n)}forEach(t){qe(this,t)}_write(t){t.writeTypeRef(ch)}}const Ha=e=>new Zt;class De extends Zt{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new De(this.nodeName)}clone(){const t=new De(this.nodeName),n=this.getAttributes();return xl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof W?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?O(this.doc,n=>{On(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{tr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return er(this,t)}hasAttribute(t){return ao(this,t)}getAttributes(t){return t?Ra(this,t):co(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return qe(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(lh),t.writeKey(this.nodeName)}}const Pa=e=>new De(e.readKey());class Ja extends Gn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Rn extends Ee{constructor(t){super(),this.hookName=t}_copy(){return new Rn(this.hookName)}clone(){const t=new Rn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(ah),t.writeKey(this.hookName)}}const Wa=e=>new Rn(e.readKey());class Un extends Ce{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Un}clone(){const t=new Un;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(hh)}}const Ya=e=>new Un;class nr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw lt()}mergeWith(t){return!1}write(t,n,s){throw lt()}integrate(t,n){throw lt()}}const za=0;class rt extends nr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),qi(t.doc.store,this)}write(t,n){t.writeInfo(za),t.writeLen(this.length-n)}getMissing(t,n){return null}}class en{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new en(this.content)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Ga=e=>new en(e.readBuf());class Xe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Xe(this.len)}splice(t){const n=new Xe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){ze(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const qa=e=>new Xe(e.readLen()),po=(e,t)=>new ne({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class nn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new nn(po(this.doc.guid,this.opts))}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const Xa=e=>new nn(po(e.readString(),e.readAny()));class se{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new se(this.embed)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const Ka=e=>new se(e.readJSON());class H{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new H(this.key,this.value)}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const Qa=e=>new H(e.readKey(),e.readJSON());class Mn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Mn(this.arr)}splice(t){const n=new Mn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const nh=e=>new wt(e.readString()),sh=[Ma,Na,ja,Pa,Ha,Wa,Ya],rh=0,ih=1,oh=2,lh=3,ch=4,ah=5,hh=6;class kt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new kt(this.type._copy())}splice(t){throw lt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const uh=e=>new kt(sh[e.readTypeRef()](e)),As=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=pe(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof R);return{item:r,diff:s}},sr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},vn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new R(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Yr=(e,t)=>Ls(e,n=>Ze(n.deletions,t)),wo=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Q(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||wo(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Q(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Q(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Q(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||Ze(s,h.right.id)||Yr(i.undoStack,h.right.id)||Yr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Q(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const g=F(l,c),y=D(c,g),S=new R(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,sr(S,!0),S.integrate(e,0),S};class R extends nr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?br:0}set marker(t){(this.info&rs)>0!==t&&(this.info^=rs)}get marker(){return(this.info&rs)>0}get keep(){return(this.info&Sr)>0}set keep(t){this.keep!==t&&(this.info^=Sr)}get countable(){return(this.info&br)>0}get deleted(){return(this.info&ss)>0}set deleted(t){this.deleted!==t&&(this.info^=ss)}markDeleted(){this.info|=ss}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=F(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=F(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ge&&this.id.client!==this.parent.client&&this.parent.clock>=F(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=$r(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Q(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===rt||this.right&&this.right.constructor===rt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===R?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===R&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ge){const s=pe(n,this.parent);s.constructor===rt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=$r(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ue(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),ze(t.deleteSet,this.id.client,this.id.clock,this.length),Br(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw nt();this.content.gc(t),n?pa(t,this,new rt(this.id,this.length)):this.content=new Xe(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Fn|(s===null?0:et)|(r===null?0:Dt)|(i===null?0:je);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Yi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===ge?(t.writeParentInfo(!1),t.writeLeftID(l)):nt();i!==null&&t.writeString(i)}this.content.write(t,n)}}const mo=(e,t)=>fh[t&Fn](e),fh=[()=>{nt()},qa,Za,Ga,nh,Ka,Qa,uh,eh,Xa,()=>{nt()}],dh=10;class it extends nr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){nt()}write(t,n){t.writeInfo(dh),b(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const yo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},ko="__ $YJS$ __";yo[ko]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");yo[ko]=!0;const So=new Map;class gh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:zl(n.newValue||"")}),Cl(this._onChange)}postMessage(t){ri.setItem(this.room,Yl(jl(t)))}close(){Dl(this._onChange)}}const ph=typeof BroadcastChannel>"u"?gh:BroadcastChannel,rr=e=>mt(So,e,()=>{const t=Ft(),n=new ph(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),wh=(e,t)=>(rr(e).subs.add(t),t),mh=(e,t)=>{const n=rr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),So.delete(e)),s},he=(e,t,n=null)=>{const s=rr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},bo=0,ir=1,_o=2,Is=(e,t)=>{b(e,bo);const n=la(t);$(e,n)},Eo=(e,t,n)=>{b(e,ir),$(e,Hi(t,n))},yh=(e,t,n)=>Eo(t,n,z(e)),Co=(e,t,n,s)=>{try{ji(t,z(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},kh=(e,t)=>{b(e,_o),$(e,t)},Sh=Co,bh=(e,t,n,s,r)=>{const i=E(e);switch(i){case bo:yh(e,t,n);break;case ir:Co(e,n,s,r);break;case _o:Sh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},_h=0,Eh=(e,t,n)=>{E(e)===_h&&n(t,Nt(e))},fs=3e4;class Do extends Jo{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Bt();this.getLocalState()!==null&&fs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&fs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&or(this,s,"timeout")},ct(fs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Bt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),fe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const or=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Ve=(e,t,n=e.states)=>{const s=t.length,r=G();b(r,s);for(let i=0;i{const s=jt(t),r=Bt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Dh=e=>Ll(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Gt=0,Ao=3,me=1,Ah=2,sn=[];sn[Gt]=(e,t,n,s,r)=>{b(e,Gt);const i=bh(t,e,n.doc,n);s&&i===ir&&!n.synced&&(n.synced=!0)};sn[Ao]=(e,t,n,s,r)=>{b(e,me),$(e,Ve(n.awareness,Array.from(n.awareness.getStates().keys())))};sn[me]=(e,t,n,s,r)=>{Ch(n.awareness,z(t),n)};sn[Ah]=(e,t,n,s,r)=>{Eh(t,n.doc,(i,o)=>Ih(n,o))};const zr=3e4,Ih=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),Io=(e,t,n)=>{const s=jt(t),r=G(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Th=e=>!(e.code>=4400&&e.code<4500),Ts=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,or(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(To,Rs(Wo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},To=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Bt();const s=Io(e,new Uint8Array(n.data),!0);Us(s)>1&&t.send(M(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Ts(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Bt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=G();if(b(n,Gt),Is(n,e.doc),t.send(M(n)),e.awareness.getLocalState()!==null){const s=G();b(s,me),$(s,Ve(e.awareness,[e.doc.clientID])),t.send(M(s))}},e.emit("status",[{status:"connecting"}])}},ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&he(e.bcChannel,t,e)};class xh extends Os{constructor(t,n,s,{connect:r=!0,awareness:i=new Do(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Th}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=sn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=G();b(f,Gt),Is(f,s),this.ws.send(M(f))}},a)),this._bcSubscriber=(f,g)=>{if(g!==this){const y=Io(this,new Uint8Array(f),!1);Us(y)>1&&he(this.bcChannel,M(y),this)}},this._updateHandler=(f,g)=>{if(g!==this){const y=G();b(y,Gt),kh(y,f),ds(this,M(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:g,removed:y},S)=>{const w=f.concat(g).concat(y),_=G();b(_,me),$(_,Ve(i,w)),ds(this,M(_))},this._exitHandler=()=>{or(this.awareness,[s.clientID],"app closed")},Vt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&zr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=da(aa(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new xh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Oh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Hi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Gr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,L=new Int32Array(2*w+1);for(let I=-w;I<=w;I+=2){let x;w===0?x=0:I===-w||I!==w&&_[I-1+w-1]<_[I+1+w-1]?x=_[I+1+w-1]:x=_[I-1+w-1]+1;let v=x-I;for(;x=r&&v>=i){u=w;break}}a.push(L)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const _=a[w-1],L=d-f,I=L===-w||L!==w&&_[L-1+w-1]<_[L+1+w-1]?L+1:L-1,x=_[I+w-1],v=x-I,N=I===L+1?x:x+1,K=I===L+1?v+1:v;for(;d>N&&f>K;)d--,f--,h.push(d,f);d=x,f=v}for(;d>0&&f>0;)d--,f--,h.push(d,f);const g=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const _=h[w],L=h[w+1];(_>y||L>S)&&g.push({aS:n+y,aE:n+_,bS:n+S,bE:n+L}),y=_+1,S=L+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` -`)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Nh(e,t)<=0?e+t:t+e:null}function $n(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=ft(e,s),l=ft(t,s),c=ft(n,s),a=dt(o,i),u=[...Ae(a,dt(l,i)).map(S=>({h:S,toks:l,side:0})),...Ae(a,dt(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,_)=>S.slice(w,_).join(""),d=(S,w,_,L)=>{let I="",x=_;for(const v of S)v.side===w&&(I+=h(o,x,v.h.aS)+h(v.toks,v.h.bS,v.h.bE),x=v.h.aE);return I+h(o,x,L)};let f="",g=0,y=0;for(;yN.side)).size===1){f+=d(S,S[0].side,w,_);continue}const I=d(S,0,w,_),x=d(S,1,w,_);if(I===x){f+=I;continue}if(w===_){const N=$h(I,x,s!==gs,o.length===0);if(N===null){if(!r)return null;f+=x;continue}f+=N;continue}if(s===gs)return null;const v=s===Nn?$n(h(o,w,_),I,x,gs):$n(h(o,w,_),I,x,s+1,r);if(v===null){if(!r)return null;f+=x;continue}f+=v}return f+h(o,g,o.length)}const qt=e=>e===""||e.endsWith(` -`)?e:e+` -`;function xo(e,t,n,s){let r=t.endsWith(` -`);return r===e.endsWith(` -`)&&(r=n.endsWith(` -`)),s===""||r===s.endsWith(` -`)?s:r?s+` -`:s.slice(0,-1)}function le(e,t,n){const s=$n(qt(e),qt(t),qt(n),$t);return s===null?{ok:!1}:{ok:!0,text:xo(e,t,n,s)}}function qh(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=$n(qt(e),qt(t),qt(n),$t,!0)??qt(n);return xo(e,t,n,s)}function qr(e,t){if(e===t)return[];const n=[],s=new Map,r=ft(e,$t),i=ft(t,$t),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?g.charCodeAt(w-1):0;L>=55296&&L<=56319&&w--;const I=_>0?g.charCodeAt(g.length-_):0;I>=56320&&I<=57343&&_--,S+=w,g=g.slice(w,g.length-_),y=y.slice(w,y.length-_),(g.length||y.length)&&s.push({index:S,deleteCount:g.length,insertText:y}),a=d,u=f}}function ps(e,t,n){const s=new Map,r=dt(ft(t,$t),s),i=Ae(dt(ft(e,$t),s),r),o=Ae(r,dt(ft(n,$t),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function yn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const Xr=700,ce=[2e3,4e3,8e3,15e3],Kr=2e3,Bh=4,Vh=32e3,jh=32;function Xh(e){let t=e.seed,n=e.baseSha;const s=(p,k)=>{t=p,r=k,Rt(k);const m=Tt.lastIndexOf(p);m>=0?Tt.splice(0,m+1):Tt.length=0};let r=e.baseSha;const i=p=>{if(!p)return;const k=[];for(let m=p;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(p,k=St)=>{const m=i(k);return r&&r===n&&t.length>Vh?{base:n,text:p,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:p,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,g=!1,y=!1,S=!1,w=null,_=null,L=0;const I=(p=Date.now())=>{const k=Math.max(p,L+1e3);return L=k,Fo(e.path,e.who||"browser",new Date(k))},x=new Map;let v=0,N=!1,K=null,Ht=0,Oe=!1,St=null,Pt=!1;const Tt=[],lr=p=>{Tt.at(-1)!==p&&(Tt.push(p),Tt.length>jh&&Tt.shift())};let bt=!1,Re=null,Jt=0;const Ue=()=>{bt=!1,Re=null},Kn=p=>{Jt===p&&Ue()};let tt=0,ot=0,rn=null,Wt=null,Qn=!1,_t=null,Me=!1,Yt=null,st=null;const U=p=>e.onState?.(p),on=p=>e.apiBase+"upload/content?path="+encodeURIComponent(p),xt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let ln=null,Zn=0;const ve=()=>{clearTimeout(ln??void 0),ln=null},cn=p=>{if(!(p instanceof ht?p.status>=500||p.status===429:!0)||h||a)return;ve();const m=ce[Math.min(Zn,ce.length-1)];Zn++,ln=setTimeout(()=>{ln=null,!h&&!a&&Ne()},m)},cr=()=>{ve(),Zn=0},an=()=>{ve(),Yt&&clearTimeout(Yt),Yt=setTimeout(()=>{Ne()},Xr)},zt=p=>{if(h)return f=p,!0;const k=B();if(k===p)return!0;const m=qr(k,p);if(fr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Ne=()=>{if(a)return Promise.resolve();if(g)return y?Promise.resolve():Fe();if(Wt)return Qn=!0,Wt;const p=(async()=>{try{await Lo()}finally{Wt=null}})();return Wt=p,p},Lo=async()=>{let p=0;for(;;){if(Qn=!1,P||a||S)return;const k=B();if(k===t&&!Pt){U("clean");return}U("saving"),e.onWriting?.();const m=l||c?await Oo(k):await Uo(k);if(m==="stop")return;if(m==="rebased"){if(++p>Bh){await hn(B(),n??"");return}continue}if(!Qn){U(B()===t&&!Pt?"clean":"dirty");return}}};let Lt=!1;const Oo=async p=>{_t=p,Me=!1;let k;try{k=await dn(on(e.path),p,n,Lt)}catch(m){return _t=null,m instanceof ht&&m.status===422&&yn(m)?(Lt=!1,$e(p),"stop"):m instanceof ht&&m.status===409?await ar(t,!1)?"rebased":"stop":(U("error"),cn(m),"stop")}return _t=null,Lt=!1,cr(),k.merged?await ar(p,!0)?"rebased":"stop":(Me||s(p,k.sha),e.onSaved?.(p),"done")},ar=async(p,k)=>{let m;try{m=await yr(kr(e.apiBase,e.path))}catch(V){return U("error"),B()!==t&&cn(V),!1}if(m.kind!=="text")return U("error"),!1;const A=B(),C=le(p,m.text,A);return!C.ok||!zt(C.text)?(k&&s(m.text,m.sha),await hn(A,m.sha??""),!1):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ro=p=>{if(p.update&&T.applyRemoteUpdate(p.update),typeof p.text!="string"){St=null;return}let k=null;for(let m=St;m!==null;m=m.prev)if(m.sent!==m.from&&ps(m.from,m.sent,p.text)){k=m;break}if(St=null,k){Pt=!0;const m=le(k.sent,p.text,B());m.ok&&zt(m.text)?(t=p.text,r=void 0,Rt(p.sha)):(t=k.sent,r=void 0)}},Uo=async p=>{_t=p,Me=!1;let k;const m=St;try{St={sent:p,from:t,prev:m},k=await Ut(xt,{...o(p,m),...Lt?{confirm_shrink:!0}:{}})}catch(C){if(_t=null,C instanceof ht&&[400,401,403,404,405,409,413].includes(C.status)&&(St=m),C instanceof ht&&(C.status===404||C.status===405))return c=!0,"rebased";if(C instanceof ht&&C.status===422&&yn(C))return Lt=!1,$e(p),"stop";if(C instanceof ht&&C.status===409&&!a){let V={};try{V=JSON.parse(C.body)}catch{}const at=typeof V.text=="string"?V.text:null;if(at!==null){const mr=le(t,at,B());if(mr.ok&&zt(mr.text))return t=at,r=void 0,Rt(V.sha),"rebased"}N=!0;const ie=B(),wr=await hn(ie,V.sha??"");return h?"stop":wr?(cn(wr.err),"stop"):(N=!1,B()!==ie?"rebased":"stop")}return U(a?"dirty":"error"),cn(C),"stop"}if(_t=null,Lt=!1,cr(),k.update&&T.applyRemoteUpdate(k.update),St=null,Pt=!1,a)return"stop";const A=le(p,k.text,B());return A.ok&&zt(A.text)&&(Me||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let P=null;const $e=p=>{P||h||!e.onShrinkRefused||(U("error"),P={was:gn(t),now:gn(p),confirm:async()=>{if(!h){if(a){U("saving"),e.onWriting?.();const k=tt,m=Jt;try{const A=await Ut(xt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),ts(k,m);const C=!bt&&ot>=tt;U(C?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&ot{if(!h)try{const k=await yr(kr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),zt(k.text),P=null,a&&!u){if(await re(!1),h)return;U(ot>=tt&&!bt?"clean":"dirty");return}ot=tt,d&&(d=0,e.onPending?.(0)),Ue(),U("clean")}catch{U("error")}finally{P=null}}},e.onShrinkRefused(P))};let Ot=null;const Mo=()=>{Ot&&clearTimeout(Ot),Ot=setTimeout(()=>{const p=B();Bo(gn(t),gn(p))&&$e(p)},Xr)},hn=async(p,k,m=I())=>{const A=++v;x.set(m,p);try{return await dn(on(m),p),A===v&&!a&&(t=p,r=void 0,k&&(n=k),U("clean")),e.onConflictCopy?.(m),null}catch(C){return A===v&&!a&&U("error"),{err:C}}finally{x.get(m)===p&&x.delete(m)}},ts=(p,k)=>{ot=Math.max(ot,p),Kn(k),!(h||u)&&(d=tt-ot,e.onPending?.(d))},vo=()=>{h||u||P||st||(st=setTimeout(()=>{st=null,!u&&!h&&re(!1)},Kr))},re=p=>{if(clearTimeout(st??void 0),st=null,p){if(ot>=tt)return Promise.resolve();const m=tt,A=Jt;return Ut(xt,{update:T.encodeState(),base:n},!0).then(C=>{Rt(C.sha),ts(m,A)})}if(rn)return rn;const k=(async()=>{try{for(;!u&&!h&&!P&&ot{g=!1,w=null,_=null,Ht=0,clearTimeout(K??void 0),K=null,Pt=!1,a=!0,lr(T.text.toString()),p?.(),Oe&&(Oe=!1,e.onReady(T))},Fe=async()=>{if(h||a||y||S)return;if(clearTimeout(K??void 0),K=null,Yt&&clearTimeout(Yt),Yt=null,Wt){S=!0;try{for(;Wt;)await Wt}finally{S=!1}if(h||a)return;if(!u){B()!==t&&an();return}}if(St!==null&&!c){let at;S=!0;try{at=await Ut(xt,{peek:!0})}catch{if(h||a)return;const ie=ce[Math.min(Ht,ce.length-1)];Ht++,K=setTimeout(()=>{K=null,Fe()},ie);return}finally{S=!1}if(h||a)return;if(Ro(at),!u){(B()!==t||Pt)&&an();return}}const p=e.soloText?.();if(p===void 0||p===t)return es();const k=T.text.toString(),m=le(t,k,p);if(m.ok)return es(()=>T.applySplices(qr(k,m.text)));g=!0,(w===null||_!==p)&&(w=I(),_=p),y=!0;let A;try{A=await hn(p,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==p?(w=null,_=null,Fe()):es(()=>{t=T.text.toString()});const C=A.err;if(C instanceof ht&&!(C.status>=500||C.status===429))return;const V=ce[Math.min(Ht,ce.length-1)];Ht++,K=setTimeout(()=>{K=null,Fe()},V)},T=new Lh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),p=>{u=p==="live",p==="solo"&&(l=!0),u&&(st&&clearTimeout(st),st=null,ve(),a||Fe(),ot=tt,d&&(d=0,e.onPending?.(0))),e.onCollab?.(p)},()=>{a?e.onReady(T):Oe=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),hr=(p,k)=>{const m=a?T.text.toString():null;if(m!==null&&lr(m),!T.isRemote(k?.origin)){if(U("dirty"),a){bt=!0,Re=m,Jt+=1,u||(tt+=1,d=tt-ot,e.onPending?.(d),clearTimeout(st??void 0),st=setTimeout(()=>{st=null,!u&&!h&&re(!1)},Kr)),Mo();return}an()}};T.text.observe(hr);const ur=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",ur),Rh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const B=()=>f!==null?f:fr()?T.text.toString():e.soloText?.()??"",fr=()=>a||l&&T.text.length>0,Rt=p=>{p&&(n=p)},No=(p,k,m)=>{if(m?.held)return s(p,k),"same";if(p===t||p===_t)return Rt(k),"same";const A=B();if(p===A)return s(p,k),a&&(Ue(),U("clean")),"same";if(a){const V=t;return Tt.includes(p)||ps(V,p,A)?(s(p,k),bt&&(Re===null||p===Re||ps(V,Re,p))&&(Ue(),U("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(p,k),zt(p),Ue(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const C=le(t,p,A);return C.ok?(_t!==null&&(Me=!0),s(p,k),zt(C.text),C.text!==p?an():_t===null&&U("clean"),C.text===A?"same":"merged"):"blocked"};let un=null;const $o=()=>{if(!a)return Ne();if(P||h)return Promise.resolve();if(!u)return d>0?re(!1):Promise.resolve();if(!bt)return Promise.resolve();if(un)return un;const p=Jt;U("saving");const k=(async()=>{try{const m=await Ut(xt,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),Kn(p),U(bt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof ht&&m.status===422&&yn(m)&&(clearTimeout(Ot??void 0),Ot=null,$e(B()),P))return;U(bt?"dirty":"clean")}finally{un=null}})();return un=k,k};let Et=null;const fn=p=>()=>{Et===p&&(Et=null)},dr=(p,k)=>{if(P)return;if(a){const A=!u&&d>0;if(!A&&!(u&&bt))return;const C="room\0"+T.text.toString();if(Et===C)return;Et=C;const V=Jt;(A?re(!0):Ut(xt,{update:T.encodeState()},!0).then(ie=>Rt(ie.sha))).then(()=>Kn(V),fn(C));return}if(g||N){const A="park\0"+p;if(Et===A)return;Et=A;let C=w!==null&&_===p?w:null;for(const[V,at]of x)C===null&&at===p&&(C=V);C??=I(),dn(on(C),p,void 0,!1,!0).catch(fn(A));return}if(!p||p===t)return;const m="text\0"+p;if(Et!==m){if((l||c)&&!k){Ne();return}Et=m,l||c?dn(on(e.path),p,n,Lt,!0).catch(fn(m)):Ut(xt,o(p),!0).catch(fn(m))}},gr=()=>{h||dr(B(),!0)},pr=()=>{Et=null};return typeof window<"u"&&(window.addEventListener("pagehide",gr),window.addEventListener("pageshow",pr)),{collab:T,current:B,merge:No,rebase:Rt,saveNow:$o,askingShrink:()=>P!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",gr),window.removeEventListener("pageshow",pr)),clearTimeout(Yt??void 0),clearTimeout(Ot??void 0),ve(),clearTimeout(K??void 0),K=null;const p=B();h=!0,f=p,P?e.onShrinkWithdrawn?.(P):dr(p,!1),clearTimeout(st??void 0),T.awareness.off("change",ur),T.text.unobserve(hr),T.destroy()}}}export{ne as D,Xr as S,Gh as U,Yh as a,aa as b,da as c,qr as d,zh as e,Rs as f,ee as g,Ph as h,Ct as i,qh as m,Xh as o,Wh as r,Jh as t}; diff --git a/internal/webapp/static/assets/sharedfile-s3I9dExU.js b/internal/webapp/static/assets/sharedfile-s3I9dExU.js new file mode 100644 index 00000000..f2eb7d96 --- /dev/null +++ b/internal/webapp/static/assets/sharedfile-s3I9dExU.js @@ -0,0 +1,16 @@ +import{H as ht,h as Je,i as Nt,k as Ho,f as br,e as _r,l as mn,m as Jo}from"./index-xYv7N57r.js";const tt=()=>new Map,Ss=e=>{const t=tt();return e.forEach((n,s)=>{t.set(s,n)}),t},kt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Po=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Wo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},jt=()=>new Set,ls=e=>e[e.length-1],Yo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Lt((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}class Go{constructor(){this._observers=tt()}on(t,n){kt(this._observers,t,jt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Lt((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}const ft=Math.floor,En=Math.abs,Ns=(e,t)=>ee>t?e:t,qo=Math.pow,ei=e=>e!==0?e<0:1/e<0,Er=1,Cr=2,cs=4,as=8,Ye=32,xt=64,nt=128,Hn=31,bs=63,te=127,Xo=2147483647,In=Number.MAX_SAFE_INTEGER,Dr=Number.MIN_SAFE_INTEGER,Ko=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&ft(e)===e),ni=String.fromCharCode,Qo=e=>e.toLowerCase(),Zo=/^\s*/g,tl=e=>e.replace(Zo,""),el=/([A-Z])/g,Ar=(e,t)=>tl(e.replace(el,n=>`${t}${Qo(n)}`)),nl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rze.encode(e),rl=ze?sl:nl;let Pe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Pe&&Pe.decode(new Uint8Array).length===1&&(Pe=null);const il=(e,t)=>zo(t,()=>e).join("");class nn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const X=()=>new nn,$s=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array($s(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},_s=Y,_=(e,t)=>{for(;t>te;)Y(e,nt|te&t),t=ft(t/128);Y(e,te&t)},Fs=(e,t)=>{const n=ei(t);for(n&&(t=-t),Y(e,(t>bs?nt:0)|(n?xt:0)|bs&t),t=ft(t/64);t>0;)Y(e,(t>te?nt:0)|te&t),t=ft(t/128)},Es=new Uint8Array(3e4),ll=Es.length/3,cl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ns(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ie(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},F=(e,t)=>{_(e,t.byteLength),Jn(e,t)},Bs=(e,t)=>{ol(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},hl=(e,t)=>Bs(e,4).setFloat32(0,t,!1),ul=(e,t)=>Bs(e,8).setFloat64(0,t,!1),fl=(e,t)=>Bs(e,8).setBigInt64(0,t,!1),Ir=new DataView(new ArrayBuffer(4)),dl=e=>(Ir.setFloat32(0,e),Ir.getFloat32(0)===e),Ge=(e,t)=>{switch(typeof t){case"string":Y(e,119),ee(e,t);break;case"number":Ko(t)&&En(t)<=Xo?(Y(e,125),Fs(e,t)):dl(t)?(Y(e,124),hl(e,t)):(Y(e,123),ul(e,t));break;case"bigint":Y(e,122),fl(e,t);break;case"object":if(t===null)Y(e,126);else if(be(t)){Y(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const xr=e=>{e.count>0&&(Fs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class Cn{constructor(){this.encoder=new nn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(xr(this),this.count=1,this.s=t)}toUint8Array(){return xr(this),v(this.encoder)}}const Lr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Fs(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class hs{constructor(){this.encoder=new nn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Lr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Lr(this),v(this.encoder)}}class gl{constructor(){this.sarr=[],this.s="",this.lensE=new Cn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new nn;return this.sarr.push(this.s),this.s="",ee(t,this.sarr.join("")),Jn(t,this.lensE.toUint8Array()),v(t)}}const wt=e=>new Error(e),ut=()=>{throw wt("Method unimplemented")},st=()=>{throw wt("Unexpected case")},si=wt("Unexpected end of array"),ri=wt("Integer out of Range");class Pn{constructor(t){this.arr=t,this.pos=0}}const Pt=e=>new Pn(e),pl=e=>e.pos!==e.arr.length,wl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},q=e=>wl(e,E(e)),_e=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posIn)throw ri}throw si},Vs=e=>{let t=e.arr[e.pos++],n=t&bs,s=64;const r=(t&xt)>0?-1:1;if((t&nt)===0)return r*n;const i=e.arr.length;for(;e.posIn)throw ri}throw si},ml=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(_e(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(_e(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},yl=e=>Pe.decode(q(e)),Bt=Pe?yl:ml,js=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},kl=e=>js(e,4).getFloat32(0,!1),Sl=e=>js(e,8).getFloat64(0,!1),bl=e=>js(e,8).getBigInt64(0,!1),_l=[e=>{},e=>null,Vs,kl,Sl,bl,e=>!1,e=>!0,Bt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;s_l[127-_e(e)](e);class Or extends Pn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),pl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Dn extends Pn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vs(this);const t=ei(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class us extends Pn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Vs(this),n=t&1;this.diff=ft(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class El{constructor(t){this.decoder=new Dn(t),this.str=Bt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Cl=crypto.getRandomValues.bind(crypto),ii=()=>Cl(new Uint32Array(1))[0],Dl="10000000-1000-4000-8000"+-1e11,Al=()=>Dl.replace(/[018]/g,e=>(e^ii()&15>>e/4).toString(16)),Ht=Date.now,Rr=e=>new Promise(e);Promise.all.bind(Promise);const Ur=e=>e===void 0?null:e;class Il{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let oi=new Il,Hs=!0;try{typeof localStorage<"u"&&localStorage&&(oi=localStorage,Hs=!1)}catch{}const li=oi,Tl=e=>Hs||addEventListener("storage",e),xl=e=>Hs||removeEventListener("storage",e),Xe=Symbol("Equality"),ci=(e,t)=>e===t||!!e?.[Xe]?.(t)||!1,Ll=e=>typeof e=="object",Ol=Object.assign,Rl=Object.keys,Ul=(e,t)=>{for(const n in e)t(e[n],n)},Ml=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Tn=e=>Rl(e).length,vl=e=>{for(const t in e)return!1;return!0},sn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Js=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Nl=(e,t)=>e===t||Tn(e)===Tn(t)&&sn(e,(n,s)=>(n!==void 0||Js(t,s))&&ci(t[s],n)),$l=Object.freeze,ai=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&ai(e[t])}return $l(e)},Ps=(e,t,n=0)=>{try{for(;ne,pe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Xe]!=null)return e[Xe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var hi={};const Jt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ui=typeof window<"u"&&typeof document<"u"&&!Jt;let dt;const Vl=()=>{if(dt===void 0)if(Jt){dt=tt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");dt.set(`--${Ar(t,"-")}`,n),dt.set(`-${Ar(t,"-")}`,n)}})):dt=tt();return dt},Cs=e=>Vl().has(e),xn=e=>Ur(Jt?hi[e.toUpperCase().replaceAll("-","_")]:li.getItem(e)),fi=e=>Cs("--"+e)||xn(e)!==null,jl=fi("production"),Hl=Jt&&Bl(hi.FORCE_COLOR,["true","1","2"]),Jl=Hl||!Cs("--no-colors")&&!fi("no-color")&&(!Jt||process.stdout.isTTY)&&(!Jt||Cs("--color")||xn("COLORTERM")!==null||(xn("TERM")||"").includes("color")),di=e=>new Uint8Array(e),Pl=(e,t,n)=>new Uint8Array(e,t,n),Wl=e=>new Uint8Array(e),Yl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Gl=e=>{const t=atob(e),n=di(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Pl(t.buffer,t.byteOffset,t.byteLength)},Xl=ui?Yl:zl,Kl=ui?Gl:ql,Ql=e=>{const t=di(e.byteLength);return t.set(e),t};class Zl{constructor(t,n){this.left=t,this.right=n}}const Tt=(e,t)=>new Zl(e,t),tc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Mr=e=>e.next()>=.5,fs=(e,t,n)=>ft(e.next()*(n+1-t)+t),gi=(e,t,n)=>ft(e.next()*(n+1-t)+t),Ws=(e,t,n)=>gi(e,t,n),ec=e=>ni(Ws(e,97,122)),nc=(e,t=0,n=20)=>{const s=Ws(e,t,n);let r="";for(let i=0;it[Ws(e,0,t.length-1)],sc=Symbol("0schema");class rc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(il(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Ds=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Xe]?ci(e,t):be(e)?Us(e,n=>Ms(t,s=>Ds(n,s))):Ll(e)?sn(e,(n,s)=>Ds(n,t[s])):!1;class Q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Ds(n,s)}equals(t){return this.constructor===t.constructor&&pe(this.shape,t.shape)}[sc](){return!0}[Xe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ut()}get nullable(){return Le(this,qn)}get optional(){return new mi(this)}cast(t){return vr(t,this),t}expect(t){return vr(t,this),t}}class Ys extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const j=(e,t=null)=>new Ys(e,t);j(Ys);class zs extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new zs(e);j(zs);class Wn extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Yn=(...e)=>new Wn(e),pi=j(Wn),ic=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),wi=e=>{if(Ee.check(e))return[ic(e)];if(pi.check(e))return e.shape.map(t=>t+"");if(Ai.check(e))return["[+-]?\\d+.?\\d*"];if(Ii.check(e))return[".*"];if(Ln.check(e))return e.shape.map(wi).flat(1);st()};class oc extends Q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(wi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}j(oc);const lc=Symbol("optional");class mi extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[lc](){return!0}}const cc=j(mi);class ac extends Q{check(t,n){return n?.extend(null,"never",typeof t),!1}}j(ac);class zn extends Q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new zn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):sn(this.shape,(s,r)=>{const i=this._isPartial&&!Js(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const hc=e=>new zn(e),uc=j(zn),fc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class yi extends Q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&sn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const ki=(e,t)=>new yi(e,t),dc=j(yi);class Si extends Q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&sn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const gc=(...e)=>new Si(e);j(Si);class bi extends Q{constructor(t){super(),this.shape=t.length===1?t[0]:new Gs(t)}check(t,n){const s=be(t)&&Us(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const _i=(...e)=>new bi(e),pc=j(bi),wc=G(e=>be(e));class Ei extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const mc=(e,t=null)=>new Ei(e,t);j(Ei);const yc=mc(Q);class kc extends Q{constructor(t){super(),this.len=t.length-1,this.args=gc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Sc=j(kc),bc=G(e=>typeof e=="function");class _c extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=Us(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}j(_c,e=>e.shape.length>0);class Gs extends Q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ms(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Le=(...e)=>e.findIndex(t=>Ln.check(t))>=0?Le(...e.map(t=>Ke(t)).map(t=>Ln.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Gs(e),Ln=j(Gs),Ci=()=>!0,On=G(Ci),Ec=j(zs,e=>e.shape===Ci),qs=G(e=>typeof e=="bigint"),Cc=G(e=>e===qs),Di=G(e=>typeof e=="symbol");G(e=>e===Di);const we=G(e=>typeof e=="number"),Ai=G(e=>e===we),Ee=G(e=>typeof e=="string"),Ii=G(e=>e===Ee),Gn=G(e=>typeof e=="boolean"),Dc=G(e=>e===Gn),Ti=Yn(void 0);j(Wn,e=>e.shape.length===1&&e.shape[0]===void 0);Yn(void 0);const qn=Yn(null),Ac=j(Wn,e=>e.shape.length===1&&e.shape[0]===null);j(Uint8Array);j(Ys,e=>e.shape===Uint8Array);const Ic=Le(we,Ee,qn,Ti,qs,Gn,Di);(()=>{const e=_i(On),t=ki(Ee,On),n=Le(we,Ee,qn,Gn,e,t);return e.shape=n,t.shape.values=n,n})();const Ke=e=>{if(yc.check(e))return e;if(fc.check(e)){const t={};for(const n in e)t[n]=Ke(e[n]);return hc(t)}else{if(wc.check(e))return Le(...e.map(Ke));if(Ic.check(e))return Yn(e);if(bc.check(e))return j(e)}st()},vr=jl?()=>{}:(e,t)=>{const n=new rc;if(!t.check(e,n))throw wt(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Tc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ke(t),h:n}),this}else(t){return this.if(On,t)}done(){return(t,n)=>{for(let s=0;snew Tc(e),xi=xc(On).if(Ai,(e,t)=>fs(t,Dr,In)).if(Ii,(e,t)=>nc(t)).if(Dc,(e,t)=>Mr(t)).if(Cc,(e,t)=>BigInt(fs(t,Dr,In))).if(Ln,(e,t)=>ae(t,ds(t,e.shape))).if(uc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(cc.check(r)){if(Mr(t))continue;r=r.shape}n[s]=xi(r,t)}return n}).if(pc,(e,t)=>{const n=[],s=gi(t,0,42);for(let r=0;rds(t,e.shape)).if(Ac,(e,t)=>null).if(Sc,(e,t)=>{const n=ae(t,e.res);return()=>n}).if(Ec,(e,t)=>ae(t,ds(t,[we,Ee,qn,Ti,qs,Gn,_i(we),ki(Le("a","b","c"),we)]))).if(dc,(e,t)=>{const n={},s=fs(t,0,3);for(let r=0;rxi(Ke(t),e),St=typeof document<"u"?document:{},Lc=e=>St.createElement(e),Oc=()=>St.createDocumentFragment();G(e=>e.nodeType===Vc);const Rc=e=>St.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Uc=(e,t)=>(tc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Mc=e=>{const t=Oc();for(let n=0;n(Li(e,Mc(t)),e),zh=(e,t=[],n=[])=>vc(Uc(Lc(e),t),n);G(e=>e.nodeType===$c);const Gh=Rc;G(e=>e.nodeType===Fc);const Nc=e=>Po(e,(t,n)=>`${n}:${t};`).join(""),Li=(e,t)=>e.appendChild(t),$c=St.ELEMENT_NODE,Fc=St.TEXT_NODE;St.CDATA_SECTION_NODE;St.COMMENT_NODE;const Bc=St.DOCUMENT_NODE;St.DOCUMENT_TYPE_NODE;const Vc=St.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Bc);const Ot=Symbol,Oi=Ot(),Ri=Ot(),jc=Ot(),Hc=Ot(),Jc=Ot(),Ui=Ot(),Pc=Ot(),Xs=Ot(),Wc=Ot(),Yc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=tt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Mi(e)),Ni.forEach(t=>t.print(e))},vi=(...e)=>{console.warn(...Mi(e)),e.unshift(Xs),Ni.forEach(t=>t.print(e))},Ni=jt(),$i=e=>({[Symbol.iterator](){return this},next:e}),Xc=(e,t)=>$i(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),gs=(e,t)=>$i(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Xn{constructor(t,n){this.clock=t,this.len=n}}class Oe{constructor(){this.clients=new Map}}const Ce=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=ft((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Kc(n,t.clock)!==null},Ks=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Xn(r.clock,ie(r.len,i.clock+i.len-r.clock)):(s{const t=new Oe;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{kt(e.clients,t,()=>[]).push(new Xn(n,s))},Qc=()=>new Oe,Zc=e=>{const t=Qc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Re=(e,t)=>{_(e.restEncoder,t.clients.size),Lt(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Oe,n=E(e.restDecoder);for(let s=0;s0){const o=kt(t.clients,r,()=>[]);for(let l=0;l{const s=new Oe,r=E(e.restDecoder);for(let i=0;i0){const i=new ne;return _(i.restEncoder,0),Re(i,s),i.toUint8Array()}return null},Fi=ii;class oe extends vs{constructor({guid:t=Al(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Fi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Ki,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Rr(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Rr(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&O(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Lt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return O(this,t,n)}get(t,n=z){const s=kt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,ke)}getText(t=""){return this.get(t,Ie)}getMap(t=""){return this.get(t,Ae)}getXmlElement(t=""){return this.get(t,Te)}getXmlFragment(t=""){return this.get(t,se)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Lt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new oe({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,O(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Bi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class Vi extends Bi{readLeftID(){return C(E(this.restDecoder),E(this.restDecoder))}readRightID(){return C(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return _e(this.restDecoder)}readString(){return Bt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return qe(this.restDecoder)}readBuf(){return Ql(q(this.restDecoder))}readJSON(){return JSON.parse(Bt(this.restDecoder))}readKey(){return Bt(this.restDecoder)}}class ta{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class De extends ta{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new us(q(t)),this.clientDecoder=new Dn(q(t)),this.leftClockDecoder=new us(q(t)),this.rightClockDecoder=new us(q(t)),this.infoDecoder=new Or(q(t),_e),this.stringDecoder=new El(q(t)),this.parentInfoDecoder=new Or(q(t),_e),this.typeRefDecoder=new Dn(q(t)),this.lenDecoder=new Dn(q(t))}readLeftID(){return new me(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new me(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return qe(this.restDecoder)}readBuf(){return q(this.restDecoder)}readJSON(){return qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ie(s,t[0].id.clock);const r=mt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{B(t,i)>r&&s.set(i,r)}),Kn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),Lt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ea(e,t.clients.get(r),r,i)})},na=(e,t)=>{const n=tt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=Lt(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Ki,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(S=>S!==p)}s.length=0};for(;;){if(u.constructor!==lt){const p=kt(h,u.id.client,()=>B(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,B(t,y)),d();else{u=S.refs[S.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new ne;return Zs(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ra=(e,t)=>Zs(e,t.doc.store,t.beforeState),ia=(e,t,n,s=new De(e))=>O(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=na(s,o),a=sa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=Un([u.update,a.update])}}else l.pendingStructs=a;const h=Nr(s,r,l);if(l.pendingDs){const d=new De(Pt(l.pendingDs));E(d.restDecoder);const f=Nr(d,r,l);h&&f?l.pendingDs=Un([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Ji(r.doc,d)}},n,!1),Ji=(e,t,n,s=De)=>{const r=Pt(t);ia(r,e,n,new s(r))},Pi=(e,t,n)=>Ji(e,t,n,Vi),oa=(e,t,n=new Map)=>{Zs(e,t.store,n),Re(e,Zc(t.store))},la=(e,t=new Uint8Array([0]),n=new ne)=>{const s=Yi(t);oa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ia(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===on)return Da(r.map((i,o)=>o===0?i:xa(i)));if(n.constructor===ne)return Un(r)}return r[0]},Wi=(e,t)=>la(e,t,new on),ca=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sca(new Bi(Pt(e))),zi=(e,t)=>(_(e.restEncoder,t.size),Lt(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),aa=(e,t)=>zi(e,Kn(t.store)),ha=(e,t=new Hi)=>(e instanceof Map?zi(t,e):aa(t,e),t.toUint8Array()),ua=e=>ha(e,new ji);class fa{constructor(){this.l=[]}}const $r=()=>new fa,Fr=(e,t)=>e.l.push(t),Br=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Gi=(e,t,n)=>Ps(e.l,[t,n]);class me{constructor(t,n){this.client=t,this.clock=n}}const ge=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new me(e,t),qi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw st()},Rn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Xi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const qh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},da=e=>new Xi(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ga{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const pa=(e,t,n=0)=>new ga(e,t,n),yn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=qi(e):s=C(e._item.id.client,e._item.id.clock),new Xi(s,r,t,n)},Xh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return yn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return yn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return yn(e,s.lastId,n);s=s.right}return yn(e,null,n)},wa=(e,t)=>{const n=ye(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},ma=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(B(s,r.client)<=r.clock)return null;const u=n?Ls(s,r):wa(s,r),h=u.item;if(!(h instanceof R))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(B(s,i.client)<=i.clock)return null;const{item:u}=n?Ls(s,i):{item:ye(s,i)};if(u instanceof R&&u.content instanceof bt)c=u.content.type;else return null}else throw st();l>=0?a=c._length:a=0}return pa(c,a,e.assoc)},Kh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ge(e.item,t.item)&&ge(e.type,t.type)&&e.assoc===t.assoc,fe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!rn(t.ds,e.id),Is=(e,t)=>{const n=kt(e.meta,Is,jt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Ki{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Kn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},B=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Qi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw st()}n.push(t)},mt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=ft(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[mt(n,t.clock)]},ye=ya,Ts=(e,t,n)=>{const s=mt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ts(e,n,t.clock)]},Vr=(e,t,n)=>{const s=t.clients.get(n.client),r=mt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ot&&s.splice(r+1,0,Bn(e,i,n.clock-i.id.clock+1)),i},ka=(e,t,n)=>{const s=e.clients.get(t.id.client);s[mt(s,t.id.clock)]=n},Zi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ts(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Wo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ks(t.deleteSet),ra(e,t),Re(e,t.deleteSet),!0),Hr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&kt(e.changed,t,jt).add(n)},An=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof R&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ba=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=mt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ns(r.length-1,1+mt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+An(r,c)}})},to=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Gi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ja(n)})}),Ps(l,[])}finally{s.gc&&ba(i,r,s.gcFilter),_a(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ie(mt(f,d),1);for(let y=f.length-1;y>=p;)y-=1+An(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=mt(f,d);p+11||p>0&&An(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(qc(Xs,Oi,"[yjs] ",Ri,Ui,"Changed the client-id because another client seems to be using it."),s.clientID=Fi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new on;jr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new ne;jr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):to(e,t+1)}}},O=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Sa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&to(r,0)}}return o};class Ea{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Jr=(e,t,n)=>{Ce(e,n.deletions,s=>{s instanceof R&&t.scope.some(r=>r===e.doc||Rn(r,s))&&lr(s,!1)})},Pr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;O(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Ce(l,a.insertions,f=>{if(f instanceof R){if(f.redone!==null){let{item:p,diff:y}=Ls(c,f.id);y>0&&(p=Z(l,C(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||Rn(p,f))&&h.push(f)}}),Ce(l,a.deletions,f=>{f instanceof R&&i.some(p=>p===l.doc||Rn(p,f))&&!rn(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=ko(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class Qh extends vs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=be(t)?t[0].doc:t instanceof oe?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Oe;c.afterState.forEach((S,w)=>{const b=c.beforeState.get(w)||0,L=S-b;L>0&&Qe(d,w,b,L)});const f=Ht();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=As([S.deletions,c.deleteSet]),S.insertions=As([S.insertions,d])}else h.push(new Ea(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Ce(c,c.deleteSet,S=>{S instanceof R&&this.scope.some(w=>w===c.doc||Rn(w,S))&&lr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=be(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&vi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Jr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Jr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Pr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Pr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ca(e){const t=E(e.restDecoder);for(let n=0;nUn(e,Vi,on),Aa=(e,t)=>{if(e.constructor===ot){const{client:n,clock:s}=e.id;return new ot(C(n,s+t),e.length-t)}else if(e.constructor===lt){const{client:n,clock:s}=e.id;return new lt(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new R(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Un=(e,t=De,n=ne)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Pt(u)));let r=s.map(u=>new tr(u,!0)),i=null;const o=new n,l=new er(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===lt?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)$t(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===lt?i.struct.length-=p:d=Aa(d,p)),i.struct.mergeWith(d)||($t(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==lt;d=u.next())$t(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&($t(l,i.struct,i.offset),i=null),nr(l);const c=s.map(u=>Qs(u)),a=As(c);return Re(o,a),o.toUint8Array()},Ia=(e,t,n=De,s=ne)=>{const r=Yi(t),i=new s,o=new er(i),l=new n(Pt(e)),c=new tr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===lt){c.next();continue}if(u.id.clock+u.length>d)for($t(o,u,ie(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)$t(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}nr(o);const a=Qs(l);return Re(i,a),i.toUint8Array()},eo=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=X(),e.written=0)},$t=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&eo(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},nr=e=>{eo(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Pt(e)),i=new tr(r,!1),o=new s,l=new er(o);for(let a=i.curr;a!==null;a=i.next())$t(l,t(a),0);nr(l);const c=Qs(r);return Re(o,c),o.toUint8Array()},xa=e=>Ta(e,Fl,De,on),Wr="You must not compute changes after the event-handler fired.";class Qn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=La(this.currentTarget,this.target))}deletes(t){return rn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw wt(Wr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ls(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ls(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ls(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw wt(Wr);const n=this.target,s=jt(),r=jt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const La=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},K=()=>{vi("Invalid access: Add Yjs type to a document before reading data.")},no=80;let sr=0;class Oa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=sr++}}const Ra=e=>{e.timestamp=sr++},so=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=sr++},Ua=(e,t,n)=>{if(e.length>=no){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>En(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&En(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ie(t,r.index+n))}},ts=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;kt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Gi(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=$r(),this._dEH=$r(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ut()}clone(){throw ut()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Fr(this._eH,t)}observeDeep(t){Fr(this._dEH,t)}unobserve(t){Br(this._eH,t)}unobserveDeep(t){Br(this._dEH,t)}toJSON(){}}const ro=(e,t,n)=>{e.doc??K(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},io=e=>{e.doc??K();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??K();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return tn(e,(s,r)=>{n.push(t(s,r,e))}),n},Ma=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},lo=(e,t)=>{e.doc??K();const n=Zn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new re(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ln(new Uint8Array(h))),r.integrate(e,0);break;case oe:r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new cn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new bt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},co=()=>wt("Length exceeded!"),ao=(e,t,n,s)=>{if(n>t._length)throw co();if(n===0)return t._searchMarker&&Ze(t._searchMarker,n,s.length),Mn(e,t,null,s);const r=n,i=Zn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Mn(e,t,r,n)},ho=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Zn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw co();t._searchMarker&&Ze(t._searchMarker,r,-i+s)},vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},rr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new re([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new re([s]);break;case Uint8Array:l=new ln(s);break;case oe:l=new cn(s);break;default:if(s instanceof z)l=new bt(s);else throw new Error("Unexpected content type")}new R(C(o,B(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},ir=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},uo=e=>{const t={};return e.doc??K(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},fo=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted},Na=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&fe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},kn=e=>(e.doc??K(),Xc(e._map.entries(),t=>!t[1].deleted));class $a extends Qn{}class ke extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new ke;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ke}clone(){const t=new ke;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._length}_callObserver(t,n){super._callObserver(t,n),ts(this,t,new $a(this,t))}insert(t,n){this.doc!==null?O(this.doc,s=>{ao(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?O(this.doc,n=>{va(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?O(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return lo(this,t)}toArray(){return io(this)}slice(t=0,n=this.length){return ro(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return oo(this,t)}forEach(t){tn(this,t)}[Symbol.iterator](){return Ma(this)}_write(t){t.writeTypeRef(ch)}}const Fa=e=>new ke;class Ba extends Qn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ae extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ae}clone(){const t=new Ae;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ts(this,t,new Ba(this,t,n))}toJSON(){this.doc??K();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...kn(this)].length}keys(){return gs(kn(this),t=>t[0])}values(){return gs(kn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return gs(kn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??K(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return ir(this,t)}has(t){return fo(this,t)}clear(){this.doc!==null?O(this.doc,t=>{this.forEach(function(n,s,r){vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ah)}}const Va=e=>new Ae,Ft=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Nl(e,t);class xs{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&st(),this.right.content.constructor===J?this.right.deleted||Ue(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Yr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===J?t.right.deleted||Ue(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Zn(t,n):null;if(i){const o=new xs(i.p.left,i.p,i.index,r);return Yr(e,o,n-i.index)}else{const o=new xs(null,t._start,0,r);return Yr(e,o,n)}},go=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===J&&Ft(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new R(C(i,B(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new J(l,o));u.integrate(e,0),n.right=u,n.forward()})},Ue=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},po=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===J&&Ft(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},wo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Ft(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new R(C(i,B(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new J(l,c)),n.right.integrate(e,0),n.forward()}}return o},ps=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;po(n,r);const l=wo(e,t,n,r),c=s.constructor===String?new yt(s):s instanceof z?new bt(s):new le(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ze(t._searchMarker,n.index,c.getLength()),u=new R(C(o,B(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),go(e,t,n,l)},zr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;po(n,r);const l=wo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===J));){if(!n.right.deleted)switch(n.right.content.constructor){case J:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Ft(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new R(C(o,B(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new yt(c)),n.right.integrate(e,0),n.forward()}go(e,t,n,l)},mo=(e,t,n,s,r)=>{let i=t;const o=tt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===J){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===J){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Ue(r,a)}}t=t.right}return l},ja=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===J){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ha=e=>{let t=0;return O(e.doc,n=>{let s=e._start,r=e._start,i=tt();const o=Ss(i);for(;r;)r.deleted===!1&&(r.content.constructor===J?Ue(o,r.content):(t+=mo(n,s,r,i,o),i=Ss(o),s=r)),r=r.right}),t},Ja=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&Zi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===J&&o.constructor!==ot&&t.add(o.parent)})}O(n,s=>{Ce(e,e.deleteSet,r=>{if(r instanceof ot||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===J?t.add(i):ja(s,r)});for(const r of t)Ha(r)})},Gr=(e,t,n)=>{const s=n,r=Ss(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case bt:case le:case yt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];O(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},vl(c)||(f.attributes=Ol({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case bt:case le:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case yt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case J:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Ft(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Ft(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Ft(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Ft(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),Ue(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ie extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??K(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ie}clone(){const t=new Ie;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Pa(this,t,n);ts(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??K();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===yt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?O(this.doc,s=>{const r=new xs(null,this._start,0,new Map);for(let i=0;i0)&&ps(s,this,r,l,o.attributes||{})}else o.retain!==void 0?zr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Gr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??K();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(fe(c,t)||n!==void 0&&fe(c,n))switch(c.content.constructor){case yt:{const h=i.get("ychange");t!==void 0&&!fe(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!fe(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case bt:case le:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case J:fe(c,t)&&(a(),Ue(i,c.content));break}c=c.right}a()};return t||n?O(o,h=>{t&&Is(h,t),n&&Is(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ps(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!s);ps(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?O(s,r=>{Gr(r,Sn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!1);o.right!==null&&zr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return ir(this,t)}getAttributes(){return uo(this)}_write(t){t.writeTypeRef(hh)}}const Wa=e=>new Ie;class ws{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??K()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Te||n.constructor===se)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class se extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new se}clone(){const t=new se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new ws(this,t)}querySelector(t){t=t.toUpperCase();const s=new ws(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Lt(new ws(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ts(this,t,new Ga(this,n,t))}toString(){return oo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),tn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?O(this.doc,s=>{ao(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)O(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Mn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw wt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?O(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return io(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return lo(this,t)}slice(t=0,n=this.length){return ro(this,t,n)}forEach(t){tn(this,t)}_write(t){t.writeTypeRef(fh)}}const Ya=e=>new se;class Te extends se{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Te(this.nodeName)}clone(){const t=new Te(this.nodeName),n=this.getAttributes();return Ul(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return ir(this,t)}hasAttribute(t){return fo(this,t)}getAttributes(t){return t?Na(this,t):uo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return tn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(uh),t.writeKey(this.nodeName)}}const za=e=>new Te(e.readKey());class Ga extends Qn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Nn extends Ae{constructor(t){super(),this.hookName=t}_copy(){return new Nn(this.hookName)}clone(){const t=new Nn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(dh),t.writeKey(this.hookName)}}const qa=e=>new Nn(e.readKey());class $n extends Ie{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new $n}clone(){const t=new $n;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(gh)}}const Xa=e=>new $n;class or{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ut()}mergeWith(t){return!1}write(t,n,s){throw ut()}integrate(t,n){throw ut()}}const Ka=0;class ot extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Qi(t.doc.store,this)}write(t,n){t.writeInfo(Ka),t.writeLen(this.length-n)}getMissing(t,n){return null}}class ln{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ln(this.content)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Qa=e=>new ln(e.readBuf());class en{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new en(this.len)}splice(t){const n=new en(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Qe(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Za=e=>new en(e.readLen()),yo=(e,t)=>new oe({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class cn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new cn(yo(this.doc.guid,this.opts))}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const th=e=>new cn(yo(e.readString(),e.readAny()));class le{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new le(this.embed)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const eh=e=>new le(e.readJSON());class J{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new J(this.key,this.value)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const nh=e=>new J(e.readKey(),e.readJSON());class Fn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Fn(this.arr)}splice(t){const n=new Fn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const oh=e=>new yt(e.readString()),lh=[Fa,Va,Wa,za,Ya,qa,Xa],ch=0,ah=1,hh=2,uh=3,fh=4,dh=5,gh=6;class bt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new bt(this.type._copy())}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const ph=e=>new bt(lh[e.readTypeRef()](e)),Ls=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ye(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof R);return{item:r,diff:s}},lr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Bn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new R(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},qr=(e,t)=>Ms(e,n=>rn(n.deletions,t)),ko=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Z(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||ko(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Z(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||rn(s,h.right.id)||qr(i.undoStack,h.right.id)||qr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Z(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=B(l,c),y=C(c,p),S=new R(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,lr(S,!0),S.integrate(e,0),S};class R extends or{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Cr:0}set marker(t){(this.info&as)>0!==t&&(this.info^=as)}get marker(){return(this.info&as)>0}get keep(){return(this.info&Er)>0}set keep(t){this.keep!==t&&(this.info^=Er)}get countable(){return(this.info&Cr)>0}get deleted(){return(this.info&cs)>0}set deleted(t){this.deleted!==t&&(this.info^=cs)}markDeleted(){this.info|=cs}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=B(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=B(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===me&&this.id.client!==this.parent.client&&this.parent.clock>=B(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Vr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Z(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ot||this.right&&this.right.constructor===ot)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===R?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===R&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===me){const s=ye(n,this.parent);s.constructor===ot?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Vr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ge(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Qe(t.deleteSet,this.id.client,this.id.clock,this.length),Hr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw st();this.content.gc(t),n?ka(t,this,new ot(this.id,this.length)):this.content=new en(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Hn|(s===null?0:nt)|(r===null?0:xt)|(i===null?0:Ye);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=qi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===me?(t.writeParentInfo(!1),t.writeLeftID(l)):st();i!==null&&t.writeString(i)}this.content.write(t,n)}}const So=(e,t)=>wh[t&Hn](e),wh=[()=>{st()},Za,sh,Qa,oh,eh,nh,ph,ih,th,()=>{st()}],mh=10;class lt extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){st()}write(t,n){t.writeInfo(mh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},_o="__ $YJS$ __";bo[_o]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");bo[_o]=!0;const Eo=new Map;class yh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Kl(n.newValue||"")}),Tl(this._onChange)}postMessage(t){li.setItem(this.room,Xl(Wl(t)))}close(){xl(this._onChange)}}const kh=typeof BroadcastChannel>"u"?yh:BroadcastChannel,cr=e=>kt(Eo,e,()=>{const t=jt(),n=new kh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Sh=(e,t)=>(cr(e).subs.add(t),t),bh=(e,t)=>{const n=cr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Eo.delete(e)),s},de=(e,t,n=null)=>{const s=cr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Co=0,ar=1,Do=2,Os=(e,t)=>{_(e,Co);const n=ua(t);F(e,n)},Ao=(e,t,n)=>{_(e,ar),F(e,Wi(t,n))},_h=(e,t,n)=>Ao(t,n,q(e)),Io=(e,t,n,s)=>{try{Pi(t,q(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Eh=(e,t)=>{_(e,Do),F(e,t)},Ch=Io,Dh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Co:_h(e,t,n);break;case ar:Io(e,n,s,r);break;case Do:Ch(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ah=0,Ih=(e,t,n)=>{E(e)===Ah&&n(t,Bt(e))},ms=3e4;class To extends Go{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Ht();this.getLocalState()!==null&&ms/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&ms<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&hr(this,s,"timeout")},ft(ms/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Ht()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),pe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const hr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},We=(e,t,n=e.states)=>{const s=t.length,r=X();_(r,s);for(let i=0;i{const s=Pt(t),r=Ht(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},xh=e=>Ml(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Qt=0,xo=3,Se=1,Lh=2,an=[];an[Qt]=(e,t,n,s,r)=>{_(e,Qt);const i=Dh(t,e,n.doc,n);s&&i===ar&&!n.synced&&(n.synced=!0)};an[xo]=(e,t,n,s,r)=>{_(e,Se),F(e,We(n.awareness,Array.from(n.awareness.getStates().keys())))};an[Se]=(e,t,n,s,r)=>{Th(n.awareness,q(t),n)};an[Lh]=(e,t,n,s,r)=>{Ih(t,n.doc,(i,o)=>Oh(n,o))};const Xr=3e4,Oh=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Lo=(e,t,n)=>{const s=Pt(t),r=X(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Rh=e=>!(e.code>=4400&&e.code<4500),Rs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,hr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Oo,Ns(qo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Oo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Ht();const s=Lo(e,new Uint8Array(n.data),!0);$s(s)>1&&t.send(v(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Rs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Ht(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=X();if(_(n,Qt),Os(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){const s=X();_(s,Se),F(s,We(e.awareness,[e.doc.clientID])),t.send(v(s))}},e.emit("status",[{status:"connecting"}])}},ys=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&de(e.bcChannel,t,e)};class Uh extends vs{constructor(t,n,s,{connect:r=!0,awareness:i=new To(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Rh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=an.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=X();_(f,Qt),Os(f,s),this.ws.send(v(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=Lo(this,new Uint8Array(f),!1);$s(y)>1&&de(this.bcChannel,v(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=X();_(y,Qt),Eh(y,f),ys(this,v(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},S)=>{const w=f.concat(p).concat(y),b=X();_(b,Se),F(b,We(i,w)),ys(this,v(b))},this._exitHandler=()=>{hr(this.awareness,[s.clientID],"app closed")},Jt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Xr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=ma(da(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Uh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},vh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Wi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Kr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,L=new Int32Array(2*w+1);for(let x=-w;x<=w;x+=2){let I;w===0?I=0:x===-w||x!==w&&b[x-1+w-1]=r&&U>=i){u=w;break}}a.push(L)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],L=d-f,x=L===-w||L!==w&&b[L-1+w-1]N&&f>ct;)d--,f--,h.push(d,f);d=I,f=U}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],L=h[w+1];(b>y||L>S)&&p.push({aS:n+y,aE:n+b,bS:n+S,bE:n+L}),y=b+1,S=L+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +`)||i[o.length]===` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Vh(e,t)<=0?e+t:t+e:null}function jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=gt(e,s),l=gt(t,s),c=gt(n,s),a=pt(o,i),u=[...xe(a,pt(l,i)).map(S=>({h:S,toks:l,side:0})),...xe(a,pt(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,b)=>S.slice(w,b).join(""),d=(S,w,b,L)=>{let x="",I=b;for(const U of S)U.side===w&&(x+=h(o,I,U.h.aS)+h(U.toks,U.h.bS,U.h.bE),I=U.h.aE);return x+h(o,I,L)};let f="",p=0,y=0;for(;yN.side)).size===1){f+=d(S,S[0].side,w,b);continue}const x=d(S,0,w,b),I=d(S,1,w,b);if(x===I){f+=x;continue}if(w===b){const N=jh(x,I,s!==ks,o.length===0);if(N===null){if(!r)return null;f+=I;continue}f+=N;continue}if(s===ks)return null;const U=s===Vn?jn(h(o,w,b),x,I,ks):jn(h(o,w,b),x,I,s+1,r);if(U===null){if(!r)return null;f+=I;continue}f+=U}return f+h(o,p,o.length)}const Zt=e=>e===""||e.endsWith(` +`)?e:e+` +`;function Ro(e,t,n,s){let r=t.endsWith(` +`);return r===e.endsWith(` +`)&&(r=n.endsWith(` +`)),s===""||r===s.endsWith(` +`)?s:r?s+` +`:s.slice(0,-1)}function he(e,t,n){const s=jn(Zt(e),Zt(t),Zt(n),Vt);return s===null?{ok:!1}:{ok:!0,text:Ro(e,t,n,s)}}function Zh(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=jn(Zt(e),Zt(t),Zt(n),Vt,!0)??Zt(n);return Ro(e,t,n,s)}function Qr(e,t){if(e===t)return[];const n=[],s=new Map,r=gt(e,Vt),i=gt(t,Vt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;L>=55296&&L<=56319&&w--;const x=b>0?p.charCodeAt(p.length-b):0;x>=56320&&x<=57343&&b--,S+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:S,deleteCount:p.length,insertText:y}),a=d,u=f}}function bn(e,t,n){const s=new Map,r=pt(gt(t,Vt),s),i=xe(pt(gt(e,Vt),s),r),o=xe(r,pt(gt(n,Vt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function _n(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const Zr=700,ue=[2e3,4e3,8e3,15e3],ti=2e3,Jh=4,Ph=32e3,Wh=32;function tu(e){let t=e.seed,n=e.baseSha;const s=(g,k)=>{t=g,r=k,Dt(k);const m=Rt.lastIndexOf(g);m>=0?Rt.splice(0,m+1):Rt.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(g,k=_t)=>{const m=i(k);return r&&r===n&&t.length>Ph?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,S=!1,w=null,b=null,L="",x=0;const I=(g=Date.now())=>{const k=Math.max(g,x+1e3);return x=k,Ho(e.path,e.who||"browser",new Date(k))},U=new Map;let N=0,ct=!1,rt=null,Wt=0,es=!1,_t=null,Yt=!1;const Rt=[],ur=g=>{Rt.at(-1)!==g&&(Rt.push(g),Rt.length>Wh&&Rt.shift())};let Et=!1,Me=null,zt=0;const ve=()=>{Et=!1,Me=null},ns=g=>{zt===g&&ve()};let et=0,at=0,hn=null,Gt=null,ss=!1,Ct=null,Ne=!1,qt=null,it=null;const M=g=>e.onState?.(g),$e=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ut=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let un=null,rs=0;const Fe=()=>{clearTimeout(un??void 0),un=null},fn=g=>{if(!(g instanceof ht?g.status>=500||g.status===429:!0)||h||a)return;Fe();const m=ue[Math.min(rs,ue.length-1)];rs++,un=setTimeout(()=>{un=null,!h&&!a&&Be()},m)},fr=()=>{Fe(),rs=0},dn=()=>{Fe(),qt&&clearTimeout(qt),qt=setTimeout(()=>{Be()},Zr)},Xt=g=>{if(h)return f=g,!0;const k=V();if(k===g)return!0;const m=Qr(k,g);if(mr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Be=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():je();if(Gt)return ss=!0,Gt;const g=(async()=>{try{await Uo()}finally{Gt=null}})();return Gt=g,g},Uo=async()=>{let g=0;for(;;){if(ss=!1,P||a||S)return;const k=V();if(k===t&&!Yt){M("clean");return}if(M("saving"),e.onWriting?.(),ct){if(w!==null&&b===k){if(await gn(k,L)==="stop")return;continue}ct=!1}const m=l||c?await Mo(k):await No(k);if(m==="stop")return;if(m==="rebased"){if(++g>Jh){await gn(V(),n??"");return}continue}if(!ss){M(V()===t&&!Yt?"clean":"dirty");return}}};let Mt=!1;const Mo=async g=>{Ct=g,Ne=!1;let k;try{k=await Je($e(e.path),g,n,Mt)}catch(m){return Ct=null,m instanceof ht&&m.status===422&&_n(m)?(Mt=!1,Ve(g),"stop"):m instanceof ht&&m.status===409?await dr(t,!1)?"rebased":"stop":(M("error"),fn(m),"stop")}return Ct=null,Mt=!1,fr(),k.merged?await dr(g,!0)?"rebased":"stop":(Ne||s(g,k.sha),e.onSaved?.(g),"done")},dr=async(g,k)=>{let m;try{m=await br(_r(e.apiBase,e.path))}catch(H){return M("error"),V()!==t&&fn(H),!1}if(m.kind!=="text")return M("error"),!1;const A=V(),D=he(g,m.text,A);return!D.ok||!Xt(D.text)?(k&&Dt(m.sha),await gn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},vo=g=>{if(g.update&&T.applyRemoteUpdate(g.update),typeof g.text!="string"){_t=null;return}let k=null;for(let m=_t;m!==null;m=m.prev)if(m.sent!==m.from&&bn(m.from,m.sent,g.text)){k=m;break}if(_t=null,k){Yt=!0;const m=he(k.sent,g.text,V());m.ok&&Xt(m.text)?(t=g.text,r=void 0,Dt(g.sha)):(t=k.sent,r=void 0)}},No=async g=>{Ct=g,Ne=!1;let k;const m=_t;try{_t={sent:g,from:t,prev:m},k=await Nt(Ut,{...o(g,m),...Mt?{confirm_shrink:!0}:{}})}catch(D){if(Ct=null,D instanceof ht&&[400,401,403,404,405,409,413].includes(D.status)&&(_t=m),D instanceof ht&&(D.status===404||D.status===405))return c=!0,"rebased";if(D instanceof ht&&D.status===422&&_n(D))return Mt=!1,Ve(g),"stop";if(D instanceof ht&&D.status===409&&!a){let H={};try{H=JSON.parse(D.body)}catch{}const $=typeof H.text=="string"?H.text:null;if($!==null){const W=he(t,$,V());if(W.ok&&Xt(W.text))return t=$,r=void 0,Dt(H.sha),"rebased"}return gn(V(),H.sha??"")}return M(a?"dirty":"error"),fn(D),"stop"}if(Ct=null,Mt=!1,fr(),k.update&&T.applyRemoteUpdate(k.update),_t=null,Yt=!1,a)return"stop";const A=he(g,k.text,V());return A.ok&&Xt(A.text)&&(Ne||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let P=null;const Ve=g=>{P||h||!e.onShrinkRefused||(M("error"),P={was:mn(t),now:mn(g),confirm:async()=>{if(!h){if(a){M("saving"),e.onWriting?.();const k=et,m=zt;try{const A=await Nt(Ut,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),is(k,m);const D=!Et&&at>=et;M(D?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&at{if(!h)try{const k=await br(_r(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Xt(k.text),P=null,a&&!u){if(await ce(!1),h)return;M(at>=et&&!Et?"clean":"dirty");return}at=et,d&&(d=0,e.onPending?.(0)),ve(),M("clean")}catch{M("error")}finally{P=null}}},e.onShrinkRefused(P))};let vt=null;const $o=()=>{vt&&clearTimeout(vt),vt=setTimeout(()=>{const g=V();Jo(mn(t),mn(g))&&Ve(g)},Zr)},gr=async(g,k,m=I())=>{const A=++N;U.set(m,g);try{return await Je($e(m),g),A===N&&!a&&(t=g,r=void 0,k&&(n=k),M("clean")),e.onConflictCopy?.(m),null}catch(D){return A===N&&!a&&M("error"),{err:D}}finally{U.get(m)===g&&U.delete(m)}},gn=async(g,k)=>{(w===null||b!==g)&&(w=I(),b=g);const m=w;L=k,ct=!0;const A=await gr(g,k,m);return h?"stop":A?(fn(A.err),"stop"):(ct=!1,w===m&&(w=null,b=null,L=""),V()!==g?"rebased":"stop")},is=(g,k)=>{at=Math.max(at,g),ns(k),!(h||u)&&(d=et-at,e.onPending?.(d))},Fo=()=>{h||u||P||it||(it=setTimeout(()=>{it=null,!u&&!h&&ce(!1)},ti))},ce=g=>{if(clearTimeout(it??void 0),it=null,g){if(at>=et)return Promise.resolve();const m=et,A=zt;return Nt(Ut,{update:T.encodeState(),base:n},!0).then(D=>{Dt(D.sha),is(m,A)})}if(hn)return hn;const k=(async()=>{try{for(;!u&&!h&&!P&&at{p=!1,w=null,b=null,Wt=0,clearTimeout(rt??void 0),rt=null,Yt=!1,a=!0,ur(T.text.toString()),g?.(),es&&(es=!1,e.onReady(T))},je=async()=>{if(h||a||y||S)return;if(clearTimeout(rt??void 0),rt=null,qt&&clearTimeout(qt),qt=null,Gt){S=!0;try{for(;Gt;)await Gt}finally{S=!1}if(h||a)return;if(!u){V()!==t&&dn();return}}if(_t!==null&&!c){let $;S=!0;try{$=await Nt(Ut,{peek:!0})}catch{if(h||a)return;const W=ue[Math.min(Wt,ue.length-1)];Wt++,rt=setTimeout(()=>{rt=null,je()},W);return}finally{S=!1}if(h||a)return;if(vo($),!u){(V()!==t||Yt)&&dn();return}}const g=e.soloText?.();if(g===void 0||g===t)return os();const k=T.text.toString(),m=he(t,k,g);if(m.ok)return os(()=>T.applySplices(Qr(k,m.text)));p=!0,(w===null||b!==g)&&(w=I(),b=g),y=!0;let A;try{A=await gr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,je()):os(()=>{t=T.text.toString()});const D=A.err;if(D instanceof ht&&!(D.status>=500||D.status===429))return;const H=ue[Math.min(Wt,ue.length-1)];Wt++,rt=setTimeout(()=>{rt=null,je()},H)},T=new Mh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(it&&clearTimeout(it),it=null,Fe(),a||je(),at=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(T):es=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),pr=(g,k)=>{const m=a?T.text.toString():null;if(m!==null&&ur(m),!T.isRemote(k?.origin)){if(M("dirty"),a){Et=!0,Me=m,zt+=1,u||(et+=1,d=et-at,e.onPending?.(d),clearTimeout(it??void 0),it=setTimeout(()=>{it=null,!u&&!h&&ce(!1)},ti)),$o();return}dn()}};T.text.observe(pr);const wr=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",wr),Nh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const V=()=>f!==null?f:mr()?T.text.toString():e.soloText?.()??"",mr=()=>a||l&&T.text.length>0,Dt=g=>{g&&(n=g)},Bo=(g,k,m)=>{if(m?.held)return s(g,k),"same";if(g===t||g===Ct)return Dt(k),"same";const A=V();if(g===A)return s(g,k),a&&(ve(),M("clean")),"same";if(a){const H=t;return Rt.includes(g)||bn(H,g,A)?(s(g,k),Et&&(Me===null||g===Me||bn(H,Me,g))&&(ve(),M("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(g,k),Xt(g),ve(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const D=he(t,g,A);return D.ok?(Ct!==null&&(Ne=!0),s(g,k),Xt(D.text),D.text!==g?dn():Ct===null&&M("clean"),D.text===A?"same":"merged"):"blocked"};let pn=null;const Vo=()=>{if(!a)return Be();if(P||h)return Promise.resolve();if(!u)return d>0?ce(!1):Promise.resolve();if(!Et)return Promise.resolve();if(pn)return pn;const g=zt;M("saving");const k=(async()=>{try{const m=await Nt(Ut,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),ns(g),M(Et?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof ht&&m.status===422&&_n(m)&&(clearTimeout(vt??void 0),vt=null,Ve(V()),P))return;M(Et?"dirty":"clean")}finally{pn=null}})();return pn=k,k};let At=null;const wn=g=>()=>{At===g&&(At=null)},yr=(g,k)=>{if(P)return;if(a){const $=!u&&d>0;if(!$&&!(u&&Et))return;const W="room\0"+T.text.toString();if(At===W)return;At=W;const It=zt;($?ce(!0):Nt(Ut,{update:T.encodeState()},!0).then(Kt=>Dt(Kt.sha))).then(()=>ns(It),wn(W));return}if(p||ct){const $="park\0"+g;if(At===$)return;At=$;let W=w!==null&&b===g?w:null;for(const[It,He]of U)W===null&&He===g&&(W=It);W??=I(),Je($e(W),g,void 0,!1,!0).catch(wn($));return}if(!g||g===t)return;const m="text\0"+g;if(At===m)return;if((l||c)&&!k){Be();return}At=m;const A=t,D=$=>{if(!($ instanceof ht&&$.status===409))return wn(m)();let W={};try{const Kt=JSON.parse($.body);Kt&&typeof Kt=="object"&&(W=Kt)}catch{}if(typeof W.text=="string"&&(W.text===g||bn(A,g,W.text)))return;ct=!0;let It=w!==null&&b===g?w:null;for(const[Kt,jo]of U)It===null&&jo===g&&(It=Kt);It??=I(),w=It,b=g;const He=It;Je($e(He),g,void 0,!1,!0).then(()=>{ct=!1,e.onConflictCopy?.(He)},wn(m))},H=$=>{$.parked&&e.onConflictCopy?.($.parked)};l||c?Je($e(e.path),g,n,Mt,!0,!0).then(H,D):Nt(Ut,{...o(g),park_on_conflict:!0},!0).then(H,D)},kr=()=>{h||yr(V(),!0)},Sr=()=>{At=null};return typeof window<"u"&&(window.addEventListener("pagehide",kr),window.addEventListener("pageshow",Sr)),{collab:T,current:V,merge:Bo,rebase:Dt,saveNow:Vo,askingShrink:()=>P!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",kr),window.removeEventListener("pageshow",Sr)),clearTimeout(qt??void 0),clearTimeout(vt??void 0),Fe(),clearTimeout(rt??void 0),rt=null;const g=V();h=!0,f=g,P?e.onShrinkWithdrawn?.(P):yr(g,!1),clearTimeout(it??void 0),T.awareness.off("change",wr),T.text.unobserve(pr),T.destroy()}}}export{oe as D,Zr as S,Qh as U,Xh as a,da as b,ma as c,Qr as d,Kh as e,Ns as f,ie as g,zh as h,Tt as i,Zh as m,tu as o,qh as r,Gh as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 0d83db82..8fd45982 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + diff --git a/internal/webapp/upload.go b/internal/webapp/upload.go index 25752167..cb4f5721 100644 --- a/internal/webapp/upload.go +++ b/internal/webapp/upload.go @@ -708,6 +708,11 @@ const ( // noMergeHeader asks a conditional write to be refused on a stale base // rather than merged: a co-editing room settles its own (ycollab.go). noMergeHeader = "X-Bdrive-No-Merge" + // parkOnConflictHeader asks a conditional write that can be neither + // taken nor merged to be kept beside the file as a conflict copy, in + // this request: a closing tab's keepalive request is the last code it + // runs, so it cannot answer a 409 by parking its text itself. + parkOnConflictHeader = "X-Bdrive-Park-On-Conflict" // maxUploadMergeBytes bounds what a stale conditional write reads into // memory to merge; the same bound a device merges under. maxUploadMergeBytes = 4 << 20 @@ -765,6 +770,17 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R s.reconcileGrants(r.Context(), project, rs.Backend) } base := strings.Trim(r.Header.Get("If-Match"), `"`) + // If-None-Match: * creates p or refuses: a conflict copy named for a + // second that another one already took must never replace it. + createOnly := base == "" && r.Header.Get("If-None-Match") == "*" + if createOnly { + if head, ok := s.headBlob(r.Context(), v, p); ok && head != blob { + writeJSONStatus(w, http.StatusConflict, map[string]any{ + "error": "this file already exists", "sha": head, "path": p, + }) + return + } + } if base != "" { if head, ok := s.headBlob(r.Context(), v, p); ok && head != base && head != blob { if handled, now := s.mergeStaleUpload(w, r, v, p, base, head, tmp, size); handled { @@ -772,6 +788,9 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R } else if now != "" { head = now } + if s.parkStaleUpload(w, r, v, up, p, head, tmp, size, blob, -1) { + return + } writeJSONStatus(w, http.StatusConflict, map[string]any{ "error": "this file changed since you last read it", "sha": head, @@ -884,9 +903,12 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R // source the base also rides into the append, which checks it against the // journals the op lands on — the only place a write from another hub // process is guaranteed to be seen. - if rs, ok := up.(*RemoteSource); ok { + switch rs, ok := up.(*RemoteSource); { + case createOnly: + err = s.createAbsent(r.Context(), v, up, p, tmp, size, blob, s.requestUser(r)) + case ok: err = rs.uploadIf(r.Context(), p, tmp, s.requestUser(r), "", base) - } else { + default: err = up.Upload(r.Context(), p, tmp, size, s.requestUser(r), "") } var stale *staleWriteError @@ -901,6 +923,10 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R head = now } } + // Quota already passed for these bytes above. + if !createOnly && s.parkStaleUpload(w, r, v, up, p, head, tmp, size, blob, billed) { + return + } writeJSONStatus(w, http.StatusConflict, map[string]any{ "error": stale.Error(), "sha": head, "path": p, }) @@ -935,6 +961,103 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head}) } +// parkStaleUpload keeps a conditional write that lost its base, and could not +// be merged, beside the file as a conflict copy — only when the request asks +// for it (parkOnConflictHeader). handled says a response was written: ok +// naming the copy, or the refusal that kept it from being stored. billed is +// what quota already admitted for these bytes, or -1 when nobody asked yet. +// +// A copy is named to the second, and two tabs of one account can close in +// the same one: each name is created only if it is free (createAbsent), and a +// taken one moves the copy a second on, so neither replaces the other. +func (s *Server) parkStaleUpload(w http.ResponseWriter, r *http.Request, v *volume, up Uploader, p, head string, tmp *os.File, size int64, blob string, billed int64) (handled bool) { + if r.Header.Get(parkOnConflictHeader) == "" || size == 0 { + return false + } + who := s.requestUser(r) + ctx := r.Context() + project := projectID(r) + org := s.orgOf(project) + if billed < 0 { + billed = size + if rs, ok := v.source.(*RemoteSource); ok { + var err error + if billed, err = billableBytes(ctx, rs.Backend, "blobs/"+blob, size); err != nil { + storageErr(w, http.StatusBadGateway, "could not check the stored object", err) + return true + } + } + if err := s.quota().CheckWrite(org, billed+s.reservedBytes(org)); err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return true + } + } + t0 := time.Now() + parked := "" + for i := range maxConflictNameTries { + name := conflictPath(p, who, t0.Add(time.Duration(i)*time.Second)) + if !s.writablePath(w, r, name) { + return true + } + unlock := s.lockPath(project, name) + err := s.createAbsent(ctx, v, up, name, tmp, size, blob, who) + unlock() + var stale *staleWriteError + if errors.As(err, &stale) { + continue // that second's copy is somebody else's + } + if err != nil { + http.Error(w, fmt.Sprintf("store: %v", err), http.StatusBadGateway) + return true + } + parked = name + break + } + if parked == "" { + writeJSONStatus(w, http.StatusConflict, map[string]any{ + "error": "no free conflict copy name", "sha": head, "path": p, + }) + return true + } + if billed > 0 { + s.quota().RecordUsage(org, billed) + } + v.invalidate() + s.dataWrote(ctx, project) + s.captureChange(r, "browser", 1, 0) + s.publishChange(r, "browser", []string{parked}, 1, 0) + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "parked": parked}) + return true +} + +// maxConflictNameTries bounds how many seconds past now a conflict copy's +// name moves while earlier ones are taken. +const maxConflictNameTries = 64 + +// createAbsent stores tmp (blob, size) at p only if p does not exist or +// already holds blob; otherwise it is a *staleWriteError naming what p holds. +// On a journal-backed source the absence rides into the append itself, so a +// second hub process creating p at the same moment is refused there too. On +// any other source the caller holds p's path lock. +func (s *Server) createAbsent(ctx context.Context, v *volume, up Uploader, p string, tmp *os.File, size int64, blob string, who User) error { + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return err + } + if rs, ok := up.(*RemoteSource); ok { + // Blob before journal, always. + if err := rs.Backend.Put(ctx, "blobs/"+blob, tmp, size); err != nil { + return fmt.Errorf("push blob: %w", err) + } + return rs.commitIfBase(ctx, p, blob, size, who, "", &commitBase{path: p, mustBeAbsent: true, blob: blob}) + } + // A directory names a version by mtime and size, never content, so any + // file already there is taken. + if head, ok := s.headBlob(ctx, v, p); ok { + return &staleWriteError{head: head} + } + return up.Upload(ctx, p, tmp, size, who, "") +} + // validMergedText reports whether a clean three-way text merge of path is // still a well-formed file of its kind. Two edits that each keep a .json // document valid can merge into one that is not (two keys added at one diff --git a/internal/webapp/upload_landed_test.go b/internal/webapp/upload_landed_test.go index 52a30308..1c02dbc9 100644 --- a/internal/webapp/upload_landed_test.go +++ b/internal/webapp/upload_landed_test.go @@ -2,9 +2,12 @@ package webapp import ( "encoding/json" + "fmt" "net/http" + "net/http/httptest" "strings" "testing" + "time" ) func putSHA(t *testing.T, h http.Handler, url, body, ifMatch string) string { @@ -147,3 +150,198 @@ func TestUploadMergeRejectsInvalidCombinedJSON(t *testing.T) { t.Fatalf("file = %q, want the landed {\"a\": 1} left untouched", got) } } + +/* +A closing tab's last save that clashes with the file is kept as a conflict copy +by the hub, in that one request: the page is gone before it could answer a 409 +with a second PUT. Asked for with X-Bdrive-Park-On-Conflict, and only ever as a +last resort — a stale save that merges cleanly still merges. +*/ +func TestUploadContentParkOnConflictWritesCopyInOneRequest(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + const path = "notes.md" + url := "/api/p/" + p.ID + "/upload/content?path=" + path + file := "/api/p/" + p.ID + "/file?path=" + path + const base = "l1\nl2\nl3\n" + const head = "l1 from somebody else\nl2\nl3\n" + baseSha := putSHA(t, h, url, base, "") + putSHA(t, h, url, head, baseSha) + + parkPut := func(body string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + r := httptest.NewRequest("PUT", url, strings.NewReader(body)) + r.Header.Set("If-Match", baseSha) + r.Header.Set(parkOnConflictHeader, "1") + h.ServeHTTP(rec, r) + return rec + } + type answer struct { + OK bool `json:"ok"` + SHA string `json:"sha"` + Merged bool `json:"merged"` + Parked string `json:"parked"` + } + + const mine = "l1 from the closing tab\nl2\nl3\n" + rec := parkPut(mine) + if rec.Code != http.StatusOK { + t.Fatalf("clashing save: %d %s", rec.Code, rec.Body) + } + var out answer + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !out.OK || out.Merged || !strings.HasPrefix(out.Parked, path+".bdrive-conflict-") { + t.Fatalf("answer %s: want ok naming a conflict copy", rec.Body) + } + if out.SHA != shaOf(head) { + t.Fatalf("answered sha %s, want the head the file stays on", out.SHA) + } + if got := get(t, h, file).Body.String(); got != head { + t.Fatalf("file = %q, want the head %q", got, head) + } + if got := get(t, h, "/api/p/"+p.ID+"/file?path="+out.Parked).Body.String(); got != mine { + t.Fatalf("copy = %q, want the caller's %q", got, mine) + } + + // Different lines: merged onto the file, nothing parked. + rec = parkPut("l1\nl2\nl3 from the closing tab\n") + if rec.Code != http.StatusOK { + t.Fatalf("mergeable save: %d %s", rec.Code, rec.Body) + } + out = answer{} + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !out.Merged || out.Parked != "" { + t.Fatalf("mergeable save answered %s: want merged, nothing parked", rec.Body) + } + if got, want := get(t, h, file).Body.String(), "l1 from somebody else\nl2\nl3 from the closing tab\n"; got != want { + t.Fatalf("file = %q, want the merge %q", got, want) + } + if cc := conflictTexts(t, srv, p.ID, path); len(cc) != 1 { + t.Fatalf("%d conflict copies, want only the clash's", len(cc)) + } +} + +// conflictStamp checks name is a conflict copy of path in the form the sync +// engine recognises — .bdrive-conflict-- — and +// returns its second. +func conflictStamp(t *testing.T, path, name string) time.Time { + t.Helper() + rest, ok := strings.CutPrefix(name, path+".bdrive-conflict-") + i := strings.LastIndex(rest, "-") + if !ok || i <= 0 { + t.Fatalf("%q is not a conflict copy of %s", name, path) + } + at, err := time.Parse("20060102T150405Z", rest[i+1:]) + if err != nil { + t.Fatalf("%q: %v", name, err) + } + return at +} + +// parkAs is a closing tab's save: conditional on base, asking the hub to +// park it if it clashes. It answers the copy's name. +func parkAs(t *testing.T, h http.Handler, url, base, body string) string { + t.Helper() + rec := httptest.NewRecorder() + r := httptest.NewRequest("PUT", url, strings.NewReader(body)) + r.Header.Set("If-Match", base) + r.Header.Set(parkOnConflictHeader, "1") + h.ServeHTTP(rec, r) + if rec.Code != http.StatusOK { + t.Fatalf("park %q: %d %s", body, rec.Code, rec.Body) + } + var out struct { + Parked string `json:"parked"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Parked == "" { + t.Fatalf("park %q answered %s: no copy named", body, rec.Body) + } + return out.Parked +} + +/* +Conflict copies are named to the second, and two tabs of one account can close +in the same one. Each copy is created only under a name nobody holds: the +second tab's moves a second on instead of replacing the first's, and a name +already taken — here, the next few seconds' copies of somebody who parked +before — is never written over either. +*/ +func TestUploadParkOnConflictNeverReplacesACopyFromTheSameSecond(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + const path = "notes.md" + url := "/api/p/" + p.ID + "/upload/content?path=" + path + baseSha := putSHA(t, h, url, "l1\nl2\nl3\n", "") + putSHA(t, h, url, "l1 from somebody else\nl2\nl3\n", baseSha) + + // Every copy here is the anonymous caller's, so the names are shared. + now := time.Now() + squatters := map[string]string{} + for k := range 3 { + name := conflictPath(path, User{}, now.Add(time.Duration(k)*time.Second)) + text := fmt.Sprintf("an earlier copy %d\n", k) + putSHA(t, h, "/api/p/"+p.ID+"/upload/content?path="+name, text, "") + squatters[name] = text + } + + const tab1, tab2 = "l1 from tab one\nl2\nl3\n", "l1 from tab two\nl2\nl3\n" + first := parkAs(t, h, url, baseSha, tab1) + second := parkAs(t, h, url, baseSha, tab2) + if first == second { + t.Fatalf("both tabs parked at %s", first) + } + a, b := conflictStamp(t, path, first), conflictStamp(t, path, second) + if !b.After(a) { + t.Fatalf("second tab's copy %s is not after the first's %s", second, first) + } + cc := conflictTexts(t, srv, p.ID, path) + for name, text := range squatters { + if cc[name] != text { + t.Fatalf("%s = %q, want the copy that was already there", name, cc[name]) + } + } + if cc[first] != tab1 || cc[second] != tab2 { + t.Fatalf("copies %v: want tab one's at %s and tab two's at %s", cc, first, second) + } + if len(cc) != len(squatters)+2 { + t.Fatalf("%d conflict copies, want %d", len(cc), len(squatters)+2) + } +} + +/* +The same across two hub processes: the second process may not have folded the +first's copy yet, so a free-looking name is held to absent in the journal +append itself, where the other process's write is guaranteed to be seen. +*/ +func TestUploadParkOnConflictAcrossProcessesNeverReplacesACopy(t *testing.T) { + a, b, p := newHubPair(t) + ha, hb := a.Handler(), b.Handler() + const path = "notes.md" + url := "/api/p/" + p.ID + "/upload/content?path=" + path + baseSha := putSHA(t, ha, url, "l1\nl2\nl3\n", "") + putSHA(t, ha, url, "l1 from somebody else\nl2\nl3\n", baseSha) + // B reads before A parks, so its snapshot predates A's copy. + if rec := get(t, hb, "/api/p/"+p.ID+"/tree"); rec.Code != http.StatusOK { + t.Fatalf("tree on B: %d", rec.Code) + } + + const tab1, tab2 = "l1 from tab one on A\nl2\nl3\n", "l1 from tab two on B\nl2\nl3\n" + first := parkAs(t, ha, url, baseSha, tab1) + second := parkAs(t, hb, url, baseSha, tab2) + if first == second { + t.Fatalf("both processes parked at %s", first) + } + conflictStamp(t, path, first) + conflictStamp(t, path, second) + for _, s := range []*Server{a, b} { + cc := conflictTexts(t, s, p.ID, path) + if len(cc) != 2 || cc[first] != tab1 || cc[second] != tab2 { + t.Fatalf("copies on %s: %v, want A's at %s and B's at %s", s.Device.ID, cc, first, second) + } + } +} diff --git a/internal/webapp/ycollab.go b/internal/webapp/ycollab.go index 0e3c6114..c6d8bd48 100644 --- a/internal/webapp/ycollab.go +++ b/internal/webapp/ycollab.go @@ -251,6 +251,11 @@ type ycollabSyncReq struct { // room may already have applied it learns from this what landed. Peek bool `json:"peek,omitempty"` PriorSent []string `json:"prior_sent,omitempty"` + // ParkOnConflict asks a text checkpoint that clashes with the live room + // to be kept beside the file as a conflict copy, in this request: a tab + // closing sends one keepalive request and runs no code after it, so it + // cannot answer a 409 with a second request parking its text itself. + ParkOnConflict bool `json:"park_on_conflict,omitempty"` } /* @@ -305,11 +310,9 @@ func (s *Server) handleYCollabSync(v *volume, w http.ResponseWriter, r *http.Req baseText := "" if len(update) == 0 && req.Text != nil { switch { - case req.BaseText != nil && (*req.BaseText != "" || req.Base == "" || req.Base == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"): - // Present, even empty when the file really was blank (no base, - // or the empty SHA-256). An empty base_text beside a non-empty - // blob's sha is a truncated read and falls through to blobText - // so the shrink guard sees the file's real size instead of 409. + case req.BaseText != nil: + // Present, even empty: "" is a real ancestor (a file that + // was blank), never "absent, read the blob instead". baseText = *req.BaseText case req.Base != "": got, ok := s.blobText(ctx, project, req.Base) @@ -375,9 +378,9 @@ func (s *Server) handleYCollabSync(v *volume, w http.ResponseWriter, r *http.Req } var ( - conflict, merged, tooLarge, pendingBusy bool - cur string - applyErr error + conflict, merged, tooLarge, pendingBusy, shrinkRefused bool + cur string + applyErr error // wantUpdate and wantText are the room's document with this request // in it, captured inside Apply: the version that must be on storage // before the answer may say ok. Read after Apply returns, a keystroke @@ -429,12 +432,24 @@ func (s *Server) handleYCollabSync(v *volume, w http.ResponseWriter, r *http.Req } } if cur != anc && cur != want { - out, ok := textmerge.Merge([]byte(anc), []byte(cur), []byte(want)) - if !ok || !validMergedText(path, out) { - conflict = true - return + const emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + if anc == "" && req.Base != "" && req.Base != emptySHA256 && sharpShrink(int64(len(cur)), int64(len(want))) { + if !req.ConfirmShrink { + shrinkRefused = true + return + } + if req.Base != s.rooms().base(room) { + conflict = true + return + } + } else { + out, ok := textmerge.Merge([]byte(anc), []byte(cur), []byte(want)) + if !ok || !validMergedText(path, out) { + conflict = true + return + } + want, merged = string(out), true } - want, merged = string(out), true } if len(want) >= maxSeedBytes { tooLarge = true @@ -469,6 +484,38 @@ func (s *Server) handleYCollabSync(v *volume, w http.ResponseWriter, r *http.Req // process are told here; the relay already has it. _ = s.ydocs().BroadcastUpdate(ctx, room, update) } + if shrinkRefused { + closeIfOpened() + writeJSONStatus(w, http.StatusUnprocessableEntity, map[string]any{ + "error": "this save would empty or sharply shrink the file", + "shrink": true, + "sha": s.rooms().base(room), + "size": len(cur), + }) + return + } + if conflict && !tooLarge && req.ParkOnConflict && req.Text != nil && + strings.TrimSpace(*req.Text) != "" && s.apiMux != nil { + // Through the upload door, as every park is: quota, folder rules, + // the journal, the data index and change frames all apply. Created + // only under a free name: another tab's copy is never replaced. + pw, parked := s.parkNewCopy(ctx, s.requestUser(r), project, path, *req.Text) + closeIfOpened() + if parked == "" { + code := pw.code + if code < 400 { + code = http.StatusBadGateway + } + if ct := pw.hdr.Get("Content-Type"); ct != "" { + w.Header().Set("Content-Type", ct) + } + w.WriteHeader(code) + _, _ = w.Write(pw.body.Bytes()) + return + } + writeJSON(w, map[string]any{"ok": true, "path": path, "sha": s.rooms().base(room), "text": cur, "parked": parked}) + return + } if conflict || tooLarge { closeIfOpened() code, msg := http.StatusConflict, "the same lines changed in the live document" @@ -2155,12 +2202,42 @@ func (s *Server) finishLater(ctx context.Context, room string, who User, text, b // putAs writes one path through the ordinary upload door as a human, with // the base the write is conditional on ("" for unconditional). func (s *Server) putAs(ctx context.Context, who User, project, path, text, base string) *memWriter { + return s.putVia(ctx, who, project, path, text, base, false) +} + +// parkNewCopy writes text as a new conflict copy of path through the upload +// door, as who. A copy is named to the second, and two tabs of one account +// can close in the same one: each name is created only if it is free +// (If-None-Match: *, which a second hub process is held to as well), and a +// taken one moves the copy a second on, so neither replaces the other. +// parked is the name it was written under, "" when it was not. +func (s *Server) parkNewCopy(ctx context.Context, who User, project, path, text string) (pw *memWriter, parked string) { + t0 := time.Now() + for i := range maxConflictNameTries { + name := conflictPath(path, who, t0.Add(time.Duration(i)*time.Second)) + pw = s.putVia(ctx, who, project, name, text, "", true) + if pw.code == http.StatusConflict { + continue + } + if pw.code == http.StatusOK { + parked = name + } + return pw, parked + } + return pw, "" +} + +// putVia is putAs, or with create a write that only creates path. +func (s *Server) putVia(ctx context.Context, who User, project, path, text, base string, create bool) *memWriter { req, err := http.NewRequestWithContext(ctx, http.MethodPut, "/api/p/"+url.PathEscape(project)+"/upload/content?path="+url.QueryEscape(path), strings.NewReader(text)) if err != nil { return &memWriter{code: 0, hdr: http.Header{}} } + if create { + req.Header.Set("If-None-Match", "*") + } if base != "" { req.Header.Set("If-Match", base) // An editor in the room confirmed this exact text shrinking the diff --git a/internal/webapp/ycollab_sync_test.go b/internal/webapp/ycollab_sync_test.go index 36666afd..5980dcd3 100644 --- a/internal/webapp/ycollab_sync_test.go +++ b/internal/webapp/ycollab_sync_test.go @@ -730,6 +730,111 @@ func TestMoveDocLiveSameLineConcurrentKeystrokeKeepsBothEdits(t *testing.T) { } } +// A closing tab's last checkpoint that clashes with the live room is kept as a +// conflict copy by the hub, in that one request — the page is gone before it +// could answer a 409 with a second one. The room keeps its own text, the copy +// holds the caller's, and quota still decides whether the copy is stored. +func TestYCollabSyncParkOnConflictWritesCopyInOneRequest(t *testing.T) { + fastRoom(t, time.Hour, time.Hour) + srv, p, _ := newHub(t, true, nil) + h := srv.Handler() + path := "notes.md" + room := p.ID + "/" + path + t.Cleanup(func() { srv.dropRoom(room) }) + const base = "l1\nl2\nl3\n" + const live = "l1 from the room\nl2\nl3\n" + const mine = "l1 from the closing tab\nl2\nl3\n" + putContent(t, h, "/api/p/"+p.ID+"/upload/content?path="+path, base, "") + + leave := srv.rooms().enter(room) // a socket in the room: it stays open + t.Cleanup(leave) + if err := srv.ydocs().Apply(context.Background(), room, func(doc *crdt.Doc, transact func(func(*crdt.Transaction))) { + txt := doc.GetText("body") + spliceVia(transact, txt, txt.ToString(), live) + }); err != nil { + t.Fatal(err) + } + checkpoint := func(park bool) *httptest.ResponseRecorder { + return syncAs(t, h, p.ID, path, map[string]any{"base": shaOf(base), "base_text": base, "text": mine, "park_on_conflict": park}) + } + + if rec := checkpoint(false); rec.Code != http.StatusConflict { + t.Fatalf("clash without park_on_conflict: %d %s, want 409", rec.Code, rec.Body) + } + if cc := conflictTexts(t, srv, p.ID, path); len(cc) != 0 { + t.Fatalf("a 409 parked %d copies", len(cc)) + } + + rec := checkpoint(true) + if rec.Code != http.StatusOK { + t.Fatalf("clash with park_on_conflict: %d %s", rec.Code, rec.Body) + } + var out struct { + OK bool `json:"ok"` + Text string `json:"text"` + Parked string `json:"parked"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !out.OK || !strings.HasPrefix(out.Parked, path+".bdrive-conflict-") { + t.Fatalf("answer %s: want ok naming the conflict copy", rec.Body) + } + if out.Text != live { + t.Fatalf("answered text %q, want the room's %q", out.Text, live) + } + if got := get(t, h, "/api/p/"+p.ID+"/file?path="+out.Parked).Body.String(); got != mine { + t.Fatalf("copy %s = %q, want the caller's %q", out.Parked, got, mine) + } + if got := roomText(srv, room); got != live { + t.Fatalf("room = %q after the park, want it untouched", got) + } + if got := get(t, h, "/api/p/"+p.ID+"/file?path="+path).Body.String(); got != base { + t.Fatalf("file = %q after the park, want it untouched", got) + } + if cc := conflictTexts(t, srv, p.ID, path); len(cc) != 1 { + t.Fatalf("%d conflict copies, want the one parked", len(cc)) + } + + // A second tab of the same account closes in the same second with a + // different clash: its copy takes the next free name and the first tab's + // copy is not replaced. + const mine2 = "l1 from the second closing tab\nl2\nl3\n" + rec = syncAs(t, h, p.ID, path, map[string]any{"base": shaOf(base), "base_text": base, "text": mine2, "park_on_conflict": true}) + if rec.Code != http.StatusOK { + t.Fatalf("second tab's park: %d %s", rec.Code, rec.Body) + } + var out2 struct { + Parked string `json:"parked"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out2); err != nil { + t.Fatal(err) + } + if out2.Parked == out.Parked { + t.Fatalf("both tabs parked at %s", out.Parked) + } + conflictStamp(t, path, out.Parked) + conflictStamp(t, path, out2.Parked) + cc := conflictTexts(t, srv, p.ID, path) + if len(cc) != 2 || cc[out.Parked] != mine || cc[out2.Parked] != mine2 { + t.Fatalf("conflict copies %v: want the first tab's at %s and the second's at %s", cc, out.Parked, out2.Parked) + } + + // A full org: the copy is refused like any write, and nothing is stored. + srv.Quota = fullQuota{} + t.Cleanup(func() { srv.Quota = nil }) + const again = "l1 from a tab over quota\nl2\nl3\n" + rec = syncAs(t, h, p.ID, path, map[string]any{"base": shaOf(base), "base_text": base, "text": again, "park_on_conflict": true}) + if rec.Code != http.StatusForbidden { + t.Fatalf("park over quota: %d %s, want 403", rec.Code, rec.Body) + } + for cp, txt := range conflictTexts(t, srv, p.ID, path) { + if txt == again { + t.Fatalf("%s holds the over-quota text", cp) + } + } +} + // An update whose result is past maxSeedBytes is refused before the live room // takes it: an applied update cannot be taken back, and a room that large // could be neither snapshotted whole nor seeded again. From 88a19c454d37630bddee71217b28a28d9204bf98 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:07:10 +0900 Subject: [PATCH 04/34] fix(webapp): make client and room conflict-copy writes create-only --- internal/webapp/frontend/src/api/http.ts | 15 +- .../webapp/frontend/src/lib/sharedfile.ts | 103 +++++++++---- .../src/lib/sharedfile_restore.test.ts | 138 +++++++++++++++++- ...{Editor-2j3g1r__.js => Editor-Kfw2qBqm.js} | 2 +- ...dit-B7FU_dFL.js => VisualEdit-C9Fhkd7e.js} | 2 +- .../{index-xYv7N57r.js => index-DTYyCePQ.js} | 6 +- .../static/assets/sharedfile-DCDc5SSp.js | 16 ++ .../static/assets/sharedfile-s3I9dExU.js | 16 -- internal/webapp/static/index.html | 2 +- internal/webapp/upload.go | 123 +++++++++++++--- internal/webapp/upload_landed_test.go | 92 ++++++++++++ internal/webapp/ycollab.go | 49 ++++++- 12 files changed, 482 insertions(+), 82 deletions(-) rename internal/webapp/static/assets/{Editor-2j3g1r__.js => Editor-Kfw2qBqm.js} (99%) rename internal/webapp/static/assets/{VisualEdit-B7FU_dFL.js => VisualEdit-C9Fhkd7e.js} (97%) rename internal/webapp/static/assets/{index-xYv7N57r.js => index-DTYyCePQ.js} (97%) create mode 100644 internal/webapp/static/assets/sharedfile-DCDc5SSp.js delete mode 100644 internal/webapp/static/assets/sharedfile-s3I9dExU.js diff --git a/internal/webapp/frontend/src/api/http.ts b/internal/webapp/frontend/src/api/http.ts index 5884f6f2..165b5c80 100644 --- a/internal/webapp/frontend/src/api/http.ts +++ b/internal/webapp/frontend/src/api/http.ts @@ -250,14 +250,19 @@ export async function putText( // in this same request (`parked` names the copy), since a closing page // never gets to send a second one. parkOnConflict = false, + // Create only: a path that already holds other bytes is refused 409 (a + // conflict copy another tab named in the same second), the same bytes are + // answered 200 unchanged (a retry whose first answer was lost). + ifNoneMatch = false, // `merged`: the hub found the file had moved past `base` and folded this // body into it three ways (upload.go) — the file is NOT exactly `text`. -): Promise<{ sha?: string; merged?: boolean; parked?: string }> { +): Promise<{ sha?: string; merged?: boolean; parked?: string; path?: string; unchanged?: boolean }> { const r = await fetch(url, { method: "PUT", headers: { "Content-Type": "text/plain; charset=utf-8", ...(base ? { "If-Match": base } : {}), + ...(ifNoneMatch ? { "If-None-Match": "*" } : {}), ...(confirmShrink ? { "X-Bdrive-Confirm-Shrink": "1" } : {}), ...(parkOnConflict ? { "X-Bdrive-Park-On-Conflict": "1" } : {}), }, @@ -268,7 +273,13 @@ export async function putText( if (r.status === 401 && !keepalive) toLogin(); if (!r.ok) await fail(r); trackWrite("PUT", url); - return (await r.json().catch(() => ({}))) as { sha?: string; merged?: boolean; parked?: string }; + return (await r.json().catch(() => ({}))) as { + sha?: string; + merged?: boolean; + parked?: string; + path?: string; + unchanged?: boolean; + }; } /* Write into a file's co-editing room over plain HTTP, for a client that is diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index dc1eebac..8ef4839e 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -66,6 +66,12 @@ const OFFLINE_FLUSH_MS = 2_000; // beside the file. A path contended this hard is not a race any more. const MAX_REBASES = 4; +// Conflict-copy names tried past a taken second (another tab of the same +// account parking in the same seconds) before the park counts as failed. On +// the way out fewer: the page may be gone before the answers come back. +const MAX_CONFLICT_TRIES = 64; +const MAX_EXIT_COPY_TRIES = 8; + // Above this, a staging checkpoint names its ancestor by sha alone when it can // (the hub reads the blob) instead of carrying it as text. const INLINE_BASE_MAX = 32_000; @@ -748,35 +754,74 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { two versions cannot be reconciled — merge3 found the same words changed two different ways. So neither version is dropped: theirs is the file, ours goes beside it as `.bdrive-conflict--`, which the - reader already knows how to explain (lib/conflict.ts, ConflictBanner). */ + reader already knows how to explain (lib/conflict.ts, ConflictBanner). + + The copy is written create-only (If-None-Match: *). Another tab of the + same account names its copies on its own clock, so the name may already + hold ITS words: that is a 409, and the next second is tried. A failure + with no answer keeps the name, because the write may have landed: the + retry sends the same bytes to the same name, which the hub answers 200 + unchanged rather than writing a second copy. */ const preserve = async ( text: string, theirs: string, copy = mintConflictPath(), ): Promise<{ err: unknown } | null> => { const seq = ++conflictSeq; - conflictPuts.set(copy, text); - // A newer park started since this one (a join's, over newer typing), or - // the room took the buffer: such a landing settles nothing about `saved`. - try { - await putText(contentURL(copy), text); // unconditional: a new path - if (seq === conflictSeq && !hubHoldsIt) { - saved = text; - savedSha = undefined; - if (theirs) base = theirs; - setState("clean"); + let at = copy; + for (let tries = 1; ; tries++) { + const target = at; + conflictPuts.set(target, text); + // A newer park started since this one (a join's, over newer typing), or + // the room took the buffer: such a landing settles nothing about `saved`. + try { + await putText(contentURL(target), text, undefined, false, false, false, true); + if (seq === conflictSeq && !hubHoldsIt) { + saved = text; + savedSha = undefined; + if (theirs) base = theirs; + setState("clean"); + } + opts.onConflictCopy?.(target); + return null; + } catch (e) { + if (e instanceof HttpError && e.status === 409 && tries < MAX_CONFLICT_TRIES) { + // Taken by other words. A retry of this text must follow the step. + at = mintConflictPath(); + if (parkedName === target && parkedText === text) parkedName = at; + continue; + } + // Could not even park it. Stay dirty and loud rather than pretend. + if (seq === conflictSeq && !hubHoldsIt) setState("error"); + return { err: e }; + } finally { + if (conflictPuts.get(target) === text) conflictPuts.delete(target); } - opts.onConflictCopy?.(copy); - return null; - } catch (e) { - // Could not even park it. Stay dirty and loud rather than pretend. - if (seq === conflictSeq && !hubHoldsIt) setState("error"); - return { err: e }; - } finally { - if (conflictPuts.get(copy) === text) conflictPuts.delete(copy); } }; + /* A conflict copy written on the way out: keepalive, create-only, and + asking the hub to step to the next free second itself — a discarded page + never runs the JS that would try again. An older hub answers a taken name + 409; while the page still lives, the next second is tried from here. */ + const parkOnExit = (copy: string, text: string, key: string, landed?: (path: string) => void) => { + const attempt = (target: string, tries: number) => { + void putText(contentURL(target), text, undefined, false, true, true, true).then( + (out) => landed?.(out.parked ?? target), + (e: unknown) => { + if (e instanceof HttpError && e.status === 409 && tries < MAX_EXIT_COPY_TRIES) { + const next = mintConflictPath(); + if (parkedName === target && parkedText === text) parkedName = next; + attempt(next, tries + 1); + return; + } + exitFailed(key)(); + }, + ); + }; + attempt(copy, 1); + }; + /* Park `parked` beside the file after a clash with head `theirSha`. One name per text: a retry re-writes the same copy. Until it lands the clash is unparked (`stagingConflict`), so leaving parks it keepalive, and a @@ -796,8 +841,9 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { return "stop"; } stagingConflict = false; - // A newer park (a join's, over newer typing) keeps its own name. - if (parkedName === name) { + // A newer park (a join's, over newer typing) keeps its own name. This + // text's name may have stepped past a taken second: compare the text. + if (parkedText === parked) { parkedName = null; parkedText = null; parkedSha = ""; @@ -1265,13 +1311,13 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { const key = "park\u0000" + text; if (exitSent === key) return; exitSent = key; - // The same words as a park already named reuse its name (writing the - // same bytes twice is harmless); newer words get a freshly minted - // one, so no older park still on the wire can land over them. + // The same words as a park already named reuse its name (the same + // bytes again are answered unchanged); newer words get a freshly + // minted one, so no older park still on the wire can land over them. let copy = parkedName !== null && parkedText === text ? parkedName : null; for (const [path, held] of conflictPuts) if (copy === null && held === text) copy = path; copy ??= mintConflictPath(); - void putText(contentURL(copy), text, undefined, false, true).catch(exitFailed(key)); + parkOnExit(copy, text, key); return; } if (!text || text === saved) return; @@ -1304,11 +1350,10 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { copy ??= mintConflictPath(); parkedName = copy; parkedText = text; - const parkedCopy = copy; - void putText(contentURL(parkedCopy), text, undefined, false, true).then(() => { + parkOnExit(copy, text, key, (path) => { stagingConflict = false; - opts.onConflictCopy?.(parkedCopy); - }, exitFailed(key)); + opts.onConflictCopy?.(path); + }); }; const landed = (out: { parked?: string }) => { if (out.parked) opts.onConflictCopy?.(out.parked); diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 6a3c9d00..5e9eecf6 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -1058,7 +1058,7 @@ for (const hubParks of [true, false]) { assert.ok(puts[1].url.includes("notes.md.bdrive-conflict-")); assert.equal(puts[1].body, "B\n"); assert.equal(puts[1].keepalive, true); - assert.equal(puts[1].park, undefined); + assert.equal(puts[1].park, "1"); // create-only, stepped by the hub if taken assert.equal(copies.length, 1); } const sent = puts.length; @@ -1071,6 +1071,142 @@ for (const hubParks of [true, false]) { }); } +/* The hub's create-only PUT (If-None-Match: *): other bytes at the name are a + 409, the same bytes are 200 unchanged. `takenFirst`: another tab of this + account already parked its own words at the first name this tab mints. + `loseFirst`: the first copy is stored, but its answer never arrives. */ +function copyServer(o: { takenFirst?: boolean; loseFirst?: boolean }) { + const store = new Map(); + const log: Array<{ path: string; ifNoneMatch?: string; status: number }> = []; + const handle = (url: RequestInfo | URL, init?: RequestInit): Response => { + const path = decodeURIComponent(String(url).split("path=")[1]); + const headers = (init?.headers ?? {}) as Record; + const body = String(init?.body); + const first = log.length === 0; + if (first && o.takenFirst) store.set(path, "another tab's words\n"); + const had = store.get(path); + let res: Response; + if (headers["If-None-Match"] === "*" && had !== undefined && had !== body) { + res = new Response(JSON.stringify({ error: "exists" }), { status: 409 }); + } else { + store.set(path, body); + res = + first && o.loseFirst + ? new Response("unavailable", { status: 503 }) + : new Response(JSON.stringify({ ok: true, path, sha: "sha-copy", unchanged: had === body }), { status: 200 }); + } + log.push({ path, ifNoneMatch: headers["If-None-Match"], status: res.status }); + return res; + }; + return { store, log, handle }; +} + +for (const scenario of ["taken", "lost"] as const) { + test(`solo clash park is create-only (${scenario === "taken" ? "a taken second steps to the next" : "a lost answer retries the same name, unchanged"})`, async () => { + fakeTimers(); + setSystemTime(new Date("2026-11-11T10:20:30.400Z")); + try { + const server = copyServer(scenario === "taken" ? { takenFirst: true } : { loseFirst: true }); + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const method = init?.method ?? "GET"; + if (method === "GET") return new Response("Z\n", { status: 200, headers: { ETag: `"sha-z"` } }); + if (decodeURIComponent(String(url)).includes("bdrive-conflict")) return server.handle(url, init); + return new Response(JSON.stringify({ error: "changed", sha: "sha-z" }), { status: 409 }); + }) as typeof fetch; + let buffer = "A\n"; + let solo = false; + const states: string[] = []; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/", + path: "notes.md", + seed: "A\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onState: (s) => states.push(s), + onConflictCopy: (c) => copies.push(c), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "B\n"; + await file.saveNow(); + if (scenario === "taken") { + // Refused at the taken name, landed at once at the next second. + same(server.log.map((l) => [l.ifNoneMatch, l.status]), [["*", 409], ["*", 200]]); + const [taken, mine] = server.log.map((l) => l.path); + assert.notEqual(taken, mine); + assert.ok(mine.includes("notes.md.bdrive-conflict-")); + assert.equal(server.store.get(taken), "another tab's words\n"); // never overwritten + assert.equal(server.store.get(mine), "B\n"); + same(copies, [mine]); + assert.equal(states.at(-1), "clean"); + } else { + // Stored, but the answer was lost: unsaved, retried on the backoff. + same(server.log.map((l) => l.status), [503]); + assert.equal(states.at(-1), "error"); + same(copies, []); + await advance(SAVE_RETRY_MS[0]); + same(server.log.map((l) => [l.ifNoneMatch, l.status]), [["*", 503], ["*", 200]]); + assert.equal(server.log[1].path, server.log[0].path); // the same name, not a second copy + assert.equal(server.store.size, 1); + assert.equal(server.store.get(server.log[0].path), "B\n"); + same(copies, [server.log[0].path]); + assert.equal(states.at(-1), "clean"); + } + await advance(60_000); + assert.equal(server.log.length, 2); + file.destroy(); + } finally { + realTimers(); + } + }); +} + +test("late join conflict park steps past a second another tab already took", async () => { + fakeTimers(); + setSystemTime(new Date("2026-11-11T10:20:30.400Z")); + const h = joinHarness(); + try { + h.net.putAnswer = 200; + const server = copyServer({ takenFirst: true }); + const inner = globalThis.fetch; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + const res = server.handle(url, init); + if (res.status !== 200) return res; + } + return inner(url, init); + }) as typeof fetch; + + h.state.buffer = "the dog sat\n"; + h.syncRoom("the bird sat\n"); + await advance(0); + + same(server.log.map((l) => [l.ifNoneMatch, l.status]), [["*", 409], ["*", 200]]); + const [taken, mine] = server.log.map((l) => l.path); + assert.notEqual(taken, mine); + assert.equal(server.store.get(taken), "another tab's words\n"); + assert.equal(server.store.get(mine), "the dog sat\n"); + same(h.copies, [mine]); + same(h.ready, [h.file.collab]); + assert.equal(h.file.current(), "the bird sat\n"); + await advance(60_000); + assert.equal(server.log.length, 2); + h.file.destroy(); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + /* R11: the socket syncs while a staging checkpoint is still on the wire. The room applies the checkpoint (its own item IDs), and the same items reach this tab twice — in the HTTP answer's `update` and on the socket. The join diff --git a/internal/webapp/static/assets/Editor-2j3g1r__.js b/internal/webapp/static/assets/Editor-Kfw2qBqm.js similarity index 99% rename from internal/webapp/static/assets/Editor-2j3g1r__.js rename to internal/webapp/static/assets/Editor-Kfw2qBqm.js index 4c79d9b2..9b59d5ee 100644 --- a/internal/webapp/static/assets/Editor-2j3g1r__.js +++ b/internal/webapp/static/assets/Editor-Kfw2qBqm.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-xYv7N57r.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-s3I9dExU.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DTYyCePQ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-DCDc5SSp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-B7FU_dFL.js b/internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-B7FU_dFL.js rename to internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js index 5823eb68..f8b6f81c 100644 --- a/internal/webapp/static/assets/VisualEdit-B7FU_dFL.js +++ b/internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-xYv7N57r.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-s3I9dExU.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-DTYyCePQ.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-DCDc5SSp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-xYv7N57r.js b/internal/webapp/static/assets/index-DTYyCePQ.js similarity index 97% rename from internal/webapp/static/assets/index-xYv7N57r.js rename to internal/webapp/static/assets/index-DTYyCePQ.js index 0deb497c..33838366 100644 --- a/internal/webapp/static/assets/index-xYv7N57r.js +++ b/internal/webapp/static/assets/index-DTYyCePQ.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-2j3g1r__.js","assets/sharedfile-s3I9dExU.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-B7FU_dFL.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Kfw2qBqm.js","assets/sharedfile-DCDc5SSp.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-C9Fhkd7e.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function lt(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function hn(s){try{var a="",c=null;do a+=lt(s,c),c=s,s=s.return;while(s);return a}catch(d){return` Error generating stack: `+d.message+` `+d.stack}}var Nt=Object.prototype.hasOwnProperty,Ct=e.unstable_scheduleCallback,mn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function vt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function yt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function _t(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function wt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),wt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return wt(J,G,Vc(te),ue);if(te.$$typeof===R)return wt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=wt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var wt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(wt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(wt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Et===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Et.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[sn]=s,a[kn]=c}catch(v){pt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[sn]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kwt&&(C=wt,wt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,wt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>wt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(_t(s,2),Js(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),_t(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(_t(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return Ct(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||vt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1){const u=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return u.status===401&&!i&&Bd(),u.ok||await ko(u),qd("PUT",e),await u.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` +`).replace(lR,"")}function yb(s,a){return a=vb(a),vb(s)===a}function bt(s,a,c,d,p,v){switch(c){case"children":typeof d=="string"?a==="body"||a==="textarea"&&d===""||As(s,d):(typeof d=="number"||typeof d=="bigint")&&a!=="body"&&As(s,""+d);break;case"className":$a(s,"class",d);break;case"tabIndex":$a(s,"tabindex",d);break;case"dir":case"role":case"viewBox":case"width":case"height":$a(s,c,d);break;case"style":Cc(s,d,v);break;case"data":if(a!=="object"){$a(s,"data",d);break}case"src":case"href":if(d===""&&(a!=="a"||c!=="href")){s.removeAttribute(c);break}if(d==null||typeof d=="function"||typeof d=="symbol"||typeof d=="boolean"){s.removeAttribute(c);break}d=it(""+d),s.setAttribute(c,d);break;case"action":case"formAction":if(typeof d=="function"){s.setAttribute(c,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof v=="function"&&(c==="formAction"?(a!=="input"&&bt(s,a,"name",p.name,p,null),bt(s,a,"formEncType",p.formEncType,p,null),bt(s,a,"formMethod",p.formMethod,p,null),bt(s,a,"formTarget",p.formTarget,p,null)):(bt(s,a,"encType",p.encType,p,null),bt(s,a,"method",p.method,p,null),bt(s,a,"target",p.target,p,null)));if(d==null||typeof d=="symbol"||typeof d=="boolean"){s.removeAttribute(c);break}d=it(""+d),s.setAttribute(c,d);break;case"onClick":d!=null&&(s.onclick=$t);break;case"onScroll":d!=null&&We("scroll",s);break;case"onScrollEnd":d!=null&&We("scrollend",s);break;case"dangerouslySetInnerHTML":if(d!=null){if(typeof d!="object"||!("__html"in d))throw Error(r(61));if(c=d.__html,c!=null){if(p.children!=null)throw Error(r(60));s.innerHTML=c}}break;case"multiple":s.multiple=d&&typeof d!="function"&&typeof d!="symbol";break;case"muted":s.muted=d&&typeof d!="function"&&typeof d!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(d==null||typeof d=="function"||typeof d=="boolean"||typeof d=="symbol"){s.removeAttribute("xlink:href");break}c=it(""+d),s.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",c);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":d!=null&&typeof d!="function"&&typeof d!="symbol"?s.setAttribute(c,""+d):s.removeAttribute(c);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":d&&typeof d!="function"&&typeof d!="symbol"?s.setAttribute(c,""):s.removeAttribute(c);break;case"capture":case"download":d===!0?s.setAttribute(c,""):d!==!1&&d!=null&&typeof d!="function"&&typeof d!="symbol"?s.setAttribute(c,d):s.removeAttribute(c);break;case"cols":case"rows":case"size":case"span":d!=null&&typeof d!="function"&&typeof d!="symbol"&&!isNaN(d)&&1<=d?s.setAttribute(c,d):s.removeAttribute(c);break;case"rowSpan":case"start":d==null||typeof d=="function"||typeof d=="symbol"||isNaN(d)?s.removeAttribute(c):s.setAttribute(c,d);break;case"popover":We("beforetoggle",s),We("toggle",s),La(s,"popover",d);break;case"xlinkActuate":ts(s,"http://www.w3.org/1999/xlink","xlink:actuate",d);break;case"xlinkArcrole":ts(s,"http://www.w3.org/1999/xlink","xlink:arcrole",d);break;case"xlinkRole":ts(s,"http://www.w3.org/1999/xlink","xlink:role",d);break;case"xlinkShow":ts(s,"http://www.w3.org/1999/xlink","xlink:show",d);break;case"xlinkTitle":ts(s,"http://www.w3.org/1999/xlink","xlink:title",d);break;case"xlinkType":ts(s,"http://www.w3.org/1999/xlink","xlink:type",d);break;case"xmlBase":ts(s,"http://www.w3.org/XML/1998/namespace","xml:base",d);break;case"xmlLang":ts(s,"http://www.w3.org/XML/1998/namespace","xml:lang",d);break;case"xmlSpace":ts(s,"http://www.w3.org/XML/1998/namespace","xml:space",d);break;case"is":La(s,"is",d);break;case"innerText":case"textContent":break;default:(!(2k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` .`.concat(FT,` { overflow: hidden `).concat(r,`; padding-right: `).concat(f,"px ").concat(r,`; @@ -125,7 +125,7 @@ bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guid `).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-2j3g1r__.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-B7FU_dFL.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Kfw2qBqm.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-C9Fhkd7e.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!l,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&o.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&o.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,l.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,o as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-DCDc5SSp.js b/internal/webapp/static/assets/sharedfile-DCDc5SSp.js new file mode 100644 index 00000000..a68d00a2 --- /dev/null +++ b/internal/webapp/static/assets/sharedfile-DCDc5SSp.js @@ -0,0 +1,16 @@ +import{H as nt,h as gn,i as $t,k as Ho,f as _r,e as Er,l as pn,m as Po}from"./index-DTYyCePQ.js";const tt=()=>new Map,ks=e=>{const t=tt();return e.forEach((n,s)=>{t.set(s,n)}),t},bt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Jo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Wo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Ht=()=>new Set,ls=e=>e[e.length-1],Yo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Ot((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}class Go{constructor(){this._observers=tt()}on(t,n){bt(this._observers,t,Ht).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Ot((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}const dt=Math.floor,bn=Math.abs,Ns=(e,t)=>ee>t?e:t,qo=Math.pow,ni=e=>e!==0?e<0:1/e<0,Cr=1,Dr=2,cs=4,as=8,Pe=32,Lt=64,st=128,Vn=31,bs=63,te=127,Xo=2147483647,Dn=Number.MAX_SAFE_INTEGER,Ar=Number.MIN_SAFE_INTEGER,Ko=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&dt(e)===e),si=String.fromCharCode,Qo=e=>e.toLowerCase(),Zo=/^\s*/g,tl=e=>e.replace(Zo,""),el=/([A-Z])/g,Ir=(e,t)=>tl(e.replace(el,n=>`${t}${Qo(n)}`)),nl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rJe.encode(e),rl=Je?sl:nl;let je=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});je&&je.decode(new Uint8Array).length===1&&(je=null);const il=(e,t)=>zo(t,()=>e).join("");class Ze{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const X=()=>new Ze,$s=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array($s(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},_s=Y,_=(e,t)=>{for(;t>te;)Y(e,st|te&t),t=dt(t/128);Y(e,te&t)},Fs=(e,t)=>{const n=ni(t);for(n&&(t=-t),Y(e,(t>bs?st:0)|(n?Lt:0)|bs&t),t=dt(t/64);t>0;)Y(e,(t>te?st:0)|te&t),t=dt(t/128)},Es=new Uint8Array(3e4),ll=Es.length/3,cl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ns(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ie(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},V=(e,t)=>{_(e,t.byteLength),jn(e,t)},Bs=(e,t)=>{ol(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},hl=(e,t)=>Bs(e,4).setFloat32(0,t,!1),ul=(e,t)=>Bs(e,8).setFloat64(0,t,!1),fl=(e,t)=>Bs(e,8).setBigInt64(0,t,!1),Tr=new DataView(new ArrayBuffer(4)),dl=e=>(Tr.setFloat32(0,e),Tr.getFloat32(0)===e),We=(e,t)=>{switch(typeof t){case"string":Y(e,119),ee(e,t);break;case"number":Ko(t)&&bn(t)<=Xo?(Y(e,125),Fs(e,t)):dl(t)?(Y(e,124),hl(e,t)):(Y(e,123),ul(e,t));break;case"bigint":Y(e,122),fl(e,t);break;case"object":if(t===null)Y(e,126);else if(be(t)){Y(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Lr=e=>{e.count>0&&(Fs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class _n{constructor(){this.encoder=new Ze,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Lr(this),this.count=1,this.s=t)}toUint8Array(){return Lr(this),F(this.encoder)}}const Or=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Fs(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class hs{constructor(){this.encoder=new Ze,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Or(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Or(this),F(this.encoder)}}class gl{constructor(){this.sarr=[],this.s="",this.lensE=new _n}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Ze;return this.sarr.push(this.s),this.s="",ee(t,this.sarr.join("")),jn(t,this.lensE.toUint8Array()),F(t)}}const yt=e=>new Error(e),ft=()=>{throw yt("Method unimplemented")},rt=()=>{throw yt("Unexpected case")},ri=yt("Unexpected end of array"),ii=yt("Integer out of Range");class Hn{constructor(t){this.arr=t,this.pos=0}}const Wt=e=>new Hn(e),pl=e=>e.pos!==e.arr.length,wl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},q=e=>wl(e,E(e)),_e=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posDn)throw ii}throw ri},Vs=e=>{let t=e.arr[e.pos++],n=t&bs,s=64;const r=(t&Lt)>0?-1:1;if((t&st)===0)return r*n;const i=e.arr.length;for(;e.posDn)throw ii}throw ri},ml=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(_e(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(_e(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},yl=e=>je.decode(q(e)),Vt=je?yl:ml,js=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Sl=e=>js(e,4).getFloat32(0,!1),kl=e=>js(e,8).getFloat64(0,!1),bl=e=>js(e,8).getBigInt64(0,!1),_l=[e=>{},e=>null,Vs,Sl,kl,bl,e=>!1,e=>!0,Vt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;s_l[127-_e(e)](e);class Rr extends Hn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),pl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class En extends Hn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vs(this);const t=ni(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class us extends Hn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Vs(this),n=t&1;this.diff=dt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class El{constructor(t){this.decoder=new En(t),this.str=Vt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Cl=crypto.getRandomValues.bind(crypto),oi=()=>Cl(new Uint32Array(1))[0],Dl="10000000-1000-4000-8000"+-1e11,Al=()=>Dl.replace(/[018]/g,e=>(e^oi()&15>>e/4).toString(16)),Pt=Date.now,Ur=e=>new Promise(e);Promise.all.bind(Promise);const Mr=e=>e===void 0?null:e;class Il{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let li=new Il,Hs=!0;try{typeof localStorage<"u"&&localStorage&&(li=localStorage,Hs=!1)}catch{}const ci=li,Tl=e=>Hs||addEventListener("storage",e),xl=e=>Hs||removeEventListener("storage",e),ze=Symbol("Equality"),ai=(e,t)=>e===t||!!e?.[ze]?.(t)||!1,Ll=e=>typeof e=="object",Ol=Object.assign,Rl=Object.keys,Ul=(e,t)=>{for(const n in e)t(e[n],n)},Ml=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},An=e=>Rl(e).length,vl=e=>{for(const t in e)return!1;return!0},tn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ps=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Nl=(e,t)=>e===t||An(e)===An(t)&&tn(e,(n,s)=>(n!==void 0||Ps(t,s))&&ai(t[s],n)),$l=Object.freeze,hi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&hi(e[t])}return $l(e)},Js=(e,t,n=0)=>{try{for(;ne,pe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ze]!=null)return e[ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ui={};const Jt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",fi=typeof window<"u"&&typeof document<"u"&&!Jt;let pt;const Vl=()=>{if(pt===void 0)if(Jt){pt=tt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");pt.set(`--${Ir(t,"-")}`,n),pt.set(`-${Ir(t,"-")}`,n)}})):pt=tt();return pt},Cs=e=>Vl().has(e),In=e=>Mr(Jt?ui[e.toUpperCase().replaceAll("-","_")]:ci.getItem(e)),di=e=>Cs("--"+e)||In(e)!==null,jl=di("production"),Hl=Jt&&Bl(ui.FORCE_COLOR,["true","1","2"]),Pl=Hl||!Cs("--no-colors")&&!di("no-color")&&(!Jt||process.stdout.isTTY)&&(!Jt||Cs("--color")||In("COLORTERM")!==null||(In("TERM")||"").includes("color")),gi=e=>new Uint8Array(e),Jl=(e,t,n)=>new Uint8Array(e,t,n),Wl=e=>new Uint8Array(e),Yl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Gl=e=>{const t=atob(e),n=gi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Jl(t.buffer,t.byteOffset,t.byteLength)},Xl=fi?Yl:zl,Kl=fi?Gl:ql,Ql=e=>{const t=gi(e.byteLength);return t.set(e),t};class Zl{constructor(t,n){this.left=t,this.right=n}}const xt=(e,t)=>new Zl(e,t),tc=(e,t)=>e.forEach(n=>t(n.left,n.right)),vr=e=>e.next()>=.5,fs=(e,t,n)=>dt(e.next()*(n+1-t)+t),pi=(e,t,n)=>dt(e.next()*(n+1-t)+t),Ws=(e,t,n)=>pi(e,t,n),ec=e=>si(Ws(e,97,122)),nc=(e,t=0,n=20)=>{const s=Ws(e,t,n);let r="";for(let i=0;it[Ws(e,0,t.length-1)],sc=Symbol("0schema");class rc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(il(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Ds=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[ze]?ai(e,t):be(e)?Us(e,n=>Ms(t,s=>Ds(n,s))):Ll(e)?tn(e,(n,s)=>Ds(n,t[s])):!1;class Q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Ds(n,s)}equals(t){return this.constructor===t.constructor&&pe(this.shape,t.shape)}[sc](){return!0}[ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ft()}get nullable(){return Le(this,zn)}get optional(){return new yi(this)}cast(t){return Nr(t,this),t}expect(t){return Nr(t,this),t}}class Ys extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const P=(e,t=null)=>new Ys(e,t);P(Ys);class zs extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new zs(e);P(zs);class Pn extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Jn=(...e)=>new Pn(e),wi=P(Pn),ic=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),mi=e=>{if(Ee.check(e))return[ic(e)];if(wi.check(e))return e.shape.map(t=>t+"");if(Ii.check(e))return["[+-]?\\d+.?\\d*"];if(Ti.check(e))return[".*"];if(Tn.check(e))return e.shape.map(mi).flat(1);rt()};class oc extends Q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(mi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}P(oc);const lc=Symbol("optional");class yi extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[lc](){return!0}}const cc=P(yi);class ac extends Q{check(t,n){return n?.extend(null,"never",typeof t),!1}}P(ac);class Wn extends Q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Wn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):tn(this.shape,(s,r)=>{const i=this._isPartial&&!Ps(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const hc=e=>new Wn(e),uc=P(Wn),fc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Si extends Q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&tn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const ki=(e,t)=>new Si(e,t),dc=P(Si);class bi extends Q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&tn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const gc=(...e)=>new bi(e);P(bi);class _i extends Q{constructor(t){super(),this.shape=t.length===1?t[0]:new Gs(t)}check(t,n){const s=be(t)&&Us(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Ei=(...e)=>new _i(e),pc=P(_i),wc=G(e=>be(e));class Ci extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const mc=(e,t=null)=>new Ci(e,t);P(Ci);const yc=mc(Q);class Sc extends Q{constructor(t){super(),this.len=t.length-1,this.args=gc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const kc=P(Sc),bc=G(e=>typeof e=="function");class _c extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=Us(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}P(_c,e=>e.shape.length>0);class Gs extends Q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ms(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Le=(...e)=>e.findIndex(t=>Tn.check(t))>=0?Le(...e.map(t=>Ge(t)).map(t=>Tn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Gs(e),Tn=P(Gs),Di=()=>!0,xn=G(Di),Ec=P(zs,e=>e.shape===Di),qs=G(e=>typeof e=="bigint"),Cc=G(e=>e===qs),Ai=G(e=>typeof e=="symbol");G(e=>e===Ai);const we=G(e=>typeof e=="number"),Ii=G(e=>e===we),Ee=G(e=>typeof e=="string"),Ti=G(e=>e===Ee),Yn=G(e=>typeof e=="boolean"),Dc=G(e=>e===Yn),xi=Jn(void 0);P(Pn,e=>e.shape.length===1&&e.shape[0]===void 0);Jn(void 0);const zn=Jn(null),Ac=P(Pn,e=>e.shape.length===1&&e.shape[0]===null);P(Uint8Array);P(Ys,e=>e.shape===Uint8Array);const Ic=Le(we,Ee,zn,xi,qs,Yn,Ai);(()=>{const e=Ei(xn),t=ki(Ee,xn),n=Le(we,Ee,zn,Yn,e,t);return e.shape=n,t.shape.values=n,n})();const Ge=e=>{if(yc.check(e))return e;if(fc.check(e)){const t={};for(const n in e)t[n]=Ge(e[n]);return hc(t)}else{if(wc.check(e))return Le(...e.map(Ge));if(Ic.check(e))return Jn(e);if(bc.check(e))return P(e)}rt()},Nr=jl?()=>{}:(e,t)=>{const n=new rc;if(!t.check(e,n))throw yt(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Tc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ge(t),h:n}),this}else(t){return this.if(xn,t)}done(){return(t,n)=>{for(let s=0;snew Tc(e),Li=xc(xn).if(Ii,(e,t)=>fs(t,Ar,Dn)).if(Ti,(e,t)=>nc(t)).if(Dc,(e,t)=>vr(t)).if(Cc,(e,t)=>BigInt(fs(t,Ar,Dn))).if(Tn,(e,t)=>ae(t,ds(t,e.shape))).if(uc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(cc.check(r)){if(vr(t))continue;r=r.shape}n[s]=Li(r,t)}return n}).if(pc,(e,t)=>{const n=[],s=pi(t,0,42);for(let r=0;rds(t,e.shape)).if(Ac,(e,t)=>null).if(kc,(e,t)=>{const n=ae(t,e.res);return()=>n}).if(Ec,(e,t)=>ae(t,ds(t,[we,Ee,zn,xi,qs,Yn,Ei(we),ki(Le("a","b","c"),we)]))).if(dc,(e,t)=>{const n={},s=fs(t,0,3);for(let r=0;rLi(Ge(t),e),_t=typeof document<"u"?document:{},Lc=e=>_t.createElement(e),Oc=()=>_t.createDocumentFragment();G(e=>e.nodeType===Vc);const Rc=e=>_t.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Uc=(e,t)=>(tc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Mc=e=>{const t=Oc();for(let n=0;n(Oi(e,Mc(t)),e),qh=(e,t=[],n=[])=>vc(Uc(Lc(e),t),n);G(e=>e.nodeType===$c);const Xh=Rc;G(e=>e.nodeType===Fc);const Nc=e=>Jo(e,(t,n)=>`${n}:${t};`).join(""),Oi=(e,t)=>e.appendChild(t),$c=_t.ELEMENT_NODE,Fc=_t.TEXT_NODE;_t.CDATA_SECTION_NODE;_t.COMMENT_NODE;const Bc=_t.DOCUMENT_NODE;_t.DOCUMENT_TYPE_NODE;const Vc=_t.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Bc);const Rt=Symbol,Ri=Rt(),Ui=Rt(),jc=Rt(),Hc=Rt(),Pc=Rt(),Mi=Rt(),Jc=Rt(),Xs=Rt(),Wc=Rt(),Yc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=tt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...vi(e)),$i.forEach(t=>t.print(e))},Ni=(...e)=>{console.warn(...vi(e)),e.unshift(Xs),$i.forEach(t=>t.print(e))},$i=Ht(),Fi=e=>({[Symbol.iterator](){return this},next:e}),Xc=(e,t)=>Fi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),gs=(e,t)=>Fi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Gn{constructor(t,n){this.clock=t,this.len=n}}class Oe{constructor(){this.clients=new Map}}const Ce=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=dt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Kc(n,t.clock)!==null},Ks=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Gn(r.clock,ie(r.len,i.clock+i.len-r.clock)):(s{const t=new Oe;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{bt(e.clients,t,()=>[]).push(new Gn(n,s))},Qc=()=>new Oe,Zc=e=>{const t=Qc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Re=(e,t)=>{_(e.restEncoder,t.clients.size),Ot(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Oe,n=E(e.restDecoder);for(let s=0;s0){const o=bt(t.clients,r,()=>[]);for(let l=0;l{const s=new Oe,r=E(e.restDecoder);for(let i=0;i0){const i=new ne;return _(i.restEncoder,0),Re(i,s),i.toUint8Array()}return null},Bi=oi;class oe extends vs{constructor({guid:t=Al(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Bi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Qi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ur(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Ur(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ot(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=bt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Se)}getText(t=""){return this.get(t,Ie)}getMap(t=""){return this.get(t,Ae)}getXmlElement(t=""){return this.get(t,Te)}getXmlFragment(t=""){return this.get(t,se)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Ot(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new oe({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Vi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class ji extends Vi{readLeftID(){return C(E(this.restDecoder),E(this.restDecoder))}readRightID(){return C(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return _e(this.restDecoder)}readString(){return Vt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ye(this.restDecoder)}readBuf(){return Ql(q(this.restDecoder))}readJSON(){return JSON.parse(Vt(this.restDecoder))}readKey(){return Vt(this.restDecoder)}}class ta{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class De extends ta{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new us(q(t)),this.clientDecoder=new En(q(t)),this.leftClockDecoder=new us(q(t)),this.rightClockDecoder=new us(q(t)),this.infoDecoder=new Rr(q(t),_e),this.stringDecoder=new El(q(t)),this.parentInfoDecoder=new Rr(q(t),_e),this.typeRefDecoder=new En(q(t)),this.lenDecoder=new En(q(t))}readLeftID(){return new me(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new me(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ye(this.restDecoder)}readBuf(){return q(this.restDecoder)}readJSON(){return Ye(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ie(s,t[0].id.clock);const r=St(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{j(t,i)>r&&s.set(i,r)}),qn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),Ot(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ea(e,t.clients.get(r),r,i)})},na=(e,t)=>{const n=tt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=Ot(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Qi,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(k=>k!==p)}s.length=0};for(;;){if(u.constructor!==at){const p=bt(h,u.id.client,()=>j(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const k=n.get(y)||{refs:[],i:0};if(k.refs.length===k.i)a(y,j(t,y)),d();else{u=k.refs[k.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new ne;return Zs(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ra=(e,t)=>Zs(e,t.doc.store,t.beforeState),ia=(e,t,n,s=new De(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=na(s,o),a=sa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=On([u.update,a.update])}}else l.pendingStructs=a;const h=$r(s,r,l);if(l.pendingDs){const d=new De(Wt(l.pendingDs));E(d.restDecoder);const f=$r(d,r,l);h&&f?l.pendingDs=On([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Ji(r.doc,d)}},n,!1),Ji=(e,t,n,s=De)=>{const r=Wt(t);ia(r,e,n,new s(r))},Wi=(e,t,n)=>Ji(e,t,n,ji),oa=(e,t,n=new Map)=>{Zs(e,t.store,n),Re(e,Zc(t.store))},la=(e,t=new Uint8Array([0]),n=new ne)=>{const s=zi(t);oa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ia(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===nn)return Da(r.map((i,o)=>o===0?i:xa(i)));if(n.constructor===ne)return On(r)}return r[0]},Yi=(e,t)=>la(e,t,new nn),ca=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sca(new Vi(Wt(e))),Gi=(e,t)=>(_(e.restEncoder,t.size),Ot(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),aa=(e,t)=>Gi(e,qn(t.store)),ha=(e,t=new Pi)=>(e instanceof Map?Gi(t,e):aa(t,e),t.toUint8Array()),ua=e=>ha(e,new Hi);class fa{constructor(){this.l=[]}}const Fr=()=>new fa,Br=(e,t)=>e.l.push(t),Vr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},qi=(e,t,n)=>Js(e.l,[t,n]);class me{constructor(t,n){this.client=t,this.clock=n}}const ge=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new me(e,t),Xi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw rt()},Ln=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Ki{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Kh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},da=e=>new Ki(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ga{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const pa=(e,t,n=0)=>new ga(e,t,n),wn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Xi(e):s=C(e._item.id.client,e._item.id.clock),new Ki(s,r,t,n)},Qh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return wn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return wn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return wn(e,s.lastId,n);s=s.right}return wn(e,null,n)},wa=(e,t)=>{const n=ye(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},ma=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(j(s,r.client)<=r.clock)return null;const u=n?Ls(s,r):wa(s,r),h=u.item;if(!(h instanceof M))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(j(s,i.client)<=i.clock)return null;const{item:u}=n?Ls(s,i):{item:ye(s,i)};if(u instanceof M&&u.content instanceof Et)c=u.content.type;else return null}else throw rt();l>=0?a=c._length:a=0}return pa(c,a,e.assoc)},Zh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ge(e.item,t.item)&&ge(e.type,t.type)&&e.assoc===t.assoc,fe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!en(t.ds,e.id),Is=(e,t)=>{const n=bt(e.meta,Is,Ht),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Qi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const qn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},j=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Zi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw rt()}n.push(t)},St=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=dt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[St(n,t.clock)]},ye=ya,Ts=(e,t,n)=>{const s=St(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ts(e,n,t.clock)]},jr=(e,t,n)=>{const s=t.clients.get(n.client),r=St(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ct&&s.splice(r+1,0,$n(e,i,n.clock-i.id.clock+1)),i},Sa=(e,t,n)=>{const s=e.clients.get(t.id.client);s[St(s,t.id.clock)]=n},to=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ts(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Wo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ks(t.deleteSet),ra(e,t),Re(e,t.deleteSet),!0),Pr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&bt(e.changed,t,Ht).add(n)},Cn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ba=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=St(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ns(r.length-1,1+St(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+Cn(r,c)}})},eo=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{qi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Pa(n)})}),Js(l,[])}finally{s.gc&&ba(i,r,s.gcFilter),_a(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ie(St(f,d),1);for(let y=f.length-1;y>=p;)y-=1+Cn(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=St(f,d);p+11||p>0&&Cn(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(qc(Xs,Ri,"[yjs] ",Ui,Mi,"Changed the client-id because another client seems to be using it."),s.clientID=Bi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new nn;Hr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new ne;Hr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):eo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new ka(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&eo(r,0)}}return o};class Ea{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Jr=(e,t,n)=>{Ce(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||Ln(r,s))&&lr(s,!1)})},Wr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Ce(l,a.insertions,f=>{if(f instanceof M){if(f.redone!==null){let{item:p,diff:y}=Ls(c,f.id);y>0&&(p=Z(l,C(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||Ln(p,f))&&h.push(f)}}),Ce(l,a.deletions,f=>{f instanceof M&&i.some(p=>p===l.doc||Ln(p,f))&&!en(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=ko(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class tu extends vs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=be(t)?t[0].doc:t instanceof oe?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(k=>c.changedParentTypes.has(k)||k===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Oe;c.afterState.forEach((k,w)=>{const b=c.beforeState.get(w)||0,O=k-b;O>0&&qe(d,w,b,O)});const f=Pt();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const k=h[h.length-1];k.deletions=As([k.deletions,c.deleteSet]),k.insertions=As([k.insertions,d])}else h.push(new Ea(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Ce(c,c.deleteSet,k=>{k instanceof M&&this.scope.some(w=>w===c.doc||Ln(w,k))&&lr(k,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=be(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ni("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Jr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Jr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Wr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Wr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ca(e){const t=E(e.restDecoder);for(let n=0;nOn(e,ji,nn),Aa=(e,t)=>{if(e.constructor===ct){const{client:n,clock:s}=e.id;return new ct(C(n,s+t),e.length-t)}else if(e.constructor===at){const{client:n,clock:s}=e.id;return new at(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},On=(e,t=De,n=ne)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Wt(u)));let r=s.map(u=>new tr(u,!0)),i=null;const o=new n,l=new er(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===at?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Ft(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===at?i.struct.length-=p:d=Aa(d,p)),i.struct.mergeWith(d)||(Ft(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==at;d=u.next())Ft(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Ft(l,i.struct,i.offset),i=null),nr(l);const c=s.map(u=>Qs(u)),a=As(c);return Re(o,a),o.toUint8Array()},Ia=(e,t,n=De,s=ne)=>{const r=zi(t),i=new s,o=new er(i),l=new n(Wt(e)),c=new tr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===at){c.next();continue}if(u.id.clock+u.length>d)for(Ft(o,u,ie(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Ft(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}nr(o);const a=Qs(l);return Re(i,a),i.toUint8Array()},no=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:F(e.encoder.restEncoder)}),e.encoder.restEncoder=X(),e.written=0)},Ft=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&no(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},nr=e=>{no(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Wt(e)),i=new tr(r,!1),o=new s,l=new er(o);for(let a=i.curr;a!==null;a=i.next())Ft(l,t(a),0);nr(l);const c=Qs(r);return Re(o,c),o.toUint8Array()},xa=e=>Ta(e,Fl,De,nn),Yr="You must not compute changes after the event-handler fired.";class Xn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=La(this.currentTarget,this.target))}deletes(t){return en(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw yt(Yr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ls(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ls(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ls(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw yt(Yr);const n=this.target,s=Ht(),r=Ht(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const La=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},K=()=>{Ni("Invalid access: Add Yjs type to a document before reading data.")},so=80;let sr=0;class Oa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=sr++}}const Ra=e=>{e.timestamp=sr++},ro=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=sr++},Ua=(e,t,n)=>{if(e.length>=so){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>bn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&bn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ie(t,r.index+n))}},Qn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;bt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;qi(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Fr(),this._dEH=Fr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ft()}clone(){throw ft()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Br(this._eH,t)}observeDeep(t){Br(this._dEH,t)}unobserve(t){Vr(this._eH,t)}unobserveDeep(t){Vr(this._dEH,t)}toJSON(){}}const io=(e,t,n)=>{e.doc??K(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},oo=e=>{e.doc??K();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??K();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return Ke(e,(s,r)=>{n.push(t(s,r,e))}),n},Ma=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},co=(e,t)=>{e.doc??K();const n=Kn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new re(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new sn(new Uint8Array(h))),r.integrate(e,0);break;case oe:r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new rn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Et(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ao=()=>yt("Length exceeded!"),ho=(e,t,n,s)=>{if(n>t._length)throw ao();if(n===0)return t._searchMarker&&Xe(t._searchMarker,n,s.length),Rn(e,t,null,s);const r=n,i=Kn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Rn(e,t,r,n)},uo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Kn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw ao();t._searchMarker&&Xe(t._searchMarker,r,-i+s)},Un=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},rr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new re([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new re([s]);break;case Uint8Array:l=new sn(s);break;case oe:l=new rn(s);break;default:if(s instanceof z)l=new Et(s);else throw new Error("Unexpected content type")}new M(C(o,j(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},ir=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},fo=e=>{const t={};return e.doc??K(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},go=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted},Na=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&fe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},mn=e=>(e.doc??K(),Xc(e._map.entries(),t=>!t[1].deleted));class $a extends Xn{}class Se extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Se;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Se}clone(){const t=new Se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._length}_callObserver(t,n){super._callObserver(t,n),Qn(this,t,new $a(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{va(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{uo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return co(this,t)}toArray(){return oo(this)}slice(t=0,n=this.length){return io(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return lo(this,t)}forEach(t){Ke(this,t)}[Symbol.iterator](){return Ma(this)}_write(t){t.writeTypeRef(ch)}}const Fa=e=>new Se;class Ba extends Xn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ae extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ae}clone(){const t=new Ae;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){Qn(this,t,new Ba(this,t,n))}toJSON(){this.doc??K();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...mn(this)].length}keys(){return gs(mn(this),t=>t[0])}values(){return gs(mn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return gs(mn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??K(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return ir(this,t)}has(t){return go(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Un(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ah)}}const Va=e=>new Ae,Bt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Nl(e,t);class xs{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&rt(),this.right.content.constructor===J?this.right.deleted||Ue(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===J?t.right.deleted||Ue(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Kn(t,n):null;if(i){const o=new xs(i.p.left,i.p,i.index,r);return zr(e,o,n-i.index)}else{const o=new xs(null,t._start,0,r);return zr(e,o,n)}},po=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===J&&Bt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new M(C(i,j(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new J(l,o));u.integrate(e,0),n.right=u,n.forward()})},Ue=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},wo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===J&&Bt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},mo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Bt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new M(C(i,j(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new J(l,c)),n.right.integrate(e,0),n.forward()}}return o},ps=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;wo(n,r);const l=mo(e,t,n,r),c=s.constructor===String?new kt(s):s instanceof z?new Et(s):new le(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Xe(t._searchMarker,n.index,c.getLength()),u=new M(C(o,j(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),po(e,t,n,l)},Gr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;wo(n,r);const l=mo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===J));){if(!n.right.deleted)switch(n.right.content.constructor){case J:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Bt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new M(C(o,j(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new kt(c)),n.right.integrate(e,0),n.forward()}po(e,t,n,l)},yo=(e,t,n,s,r)=>{let i=t;const o=tt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===J){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===J){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Ue(r,a)}}t=t.right}return l},ja=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===J){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ha=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=tt();const o=ks(i);for(;r;)r.deleted===!1&&(r.content.constructor===J?Ue(o,r.content):(t+=yo(n,s,r,i,o),i=ks(o),s=r)),r=r.right}),t},Pa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&to(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===J&&o.constructor!==ct&&t.add(o.parent)})}U(n,s=>{Ce(e,e.deleteSet,r=>{if(r instanceof ct||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===J?t.add(i):ja(s,r)});for(const r of t)Ha(r)})},qr=(e,t,n)=>{const s=n,r=ks(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Et:case le:case kt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},vl(c)||(f.attributes=Ol({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case Et:case le:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case kt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case J:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Bt(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Bt(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Bt(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Bt(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),Ue(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ie extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??K(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ie}clone(){const t=new Ie;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Ja(this,t,n);Qn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??K();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===kt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new xs(null,this._start,0,new Map);for(let i=0;i0)&&ps(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Gr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&qr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??K();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(fe(c,t)||n!==void 0&&fe(c,n))switch(c.content.constructor){case kt:{const h=i.get("ychange");t!==void 0&&!fe(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!fe(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case Et:case le:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case J:fe(c,t)&&(a(),Ue(i,c.content));break}c=c.right}a()};return t||n?U(o,h=>{t&&Is(h,t),n&&Is(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ps(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!s);ps(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{qr(r,yn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!1);o.right!==null&&Gr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return ir(this,t)}getAttributes(){return fo(this)}_write(t){t.writeTypeRef(hh)}}const Wa=e=>new Ie;class ws{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??K()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Te||n.constructor===se)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class se extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new se}clone(){const t=new se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new ws(this,t)}querySelector(t){t=t.toUpperCase();const s=new ws(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Ot(new ws(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Qn(this,t,new Ga(this,n,t))}toString(){return lo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),Ke(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Rn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw yt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{uo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return oo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return co(this,t)}slice(t=0,n=this.length){return io(this,t,n)}forEach(t){Ke(this,t)}_write(t){t.writeTypeRef(fh)}}const Ya=e=>new se;class Te extends se{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Te(this.nodeName)}clone(){const t=new Te(this.nodeName),n=this.getAttributes();return Ul(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return ir(this,t)}hasAttribute(t){return go(this,t)}getAttributes(t){return t?Na(this,t):fo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return Ke(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(uh),t.writeKey(this.nodeName)}}const za=e=>new Te(e.readKey());class Ga extends Xn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Mn extends Ae{constructor(t){super(),this.hookName=t}_copy(){return new Mn(this.hookName)}clone(){const t=new Mn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(dh),t.writeKey(this.hookName)}}const qa=e=>new Mn(e.readKey());class vn extends Ie{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new vn}clone(){const t=new vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(gh)}}const Xa=e=>new vn;class or{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ft()}mergeWith(t){return!1}write(t,n,s){throw ft()}integrate(t,n){throw ft()}}const Ka=0;class ct extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Zi(t.doc.store,this)}write(t,n){t.writeInfo(Ka),t.writeLen(this.length-n)}getMissing(t,n){return null}}class sn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new sn(this.content)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Qa=e=>new sn(e.readBuf());class Qe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Qe(this.len)}splice(t){const n=new Qe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){qe(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Za=e=>new Qe(e.readLen()),So=(e,t)=>new oe({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class rn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new rn(So(this.doc.guid,this.opts))}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const th=e=>new rn(So(e.readString(),e.readAny()));class le{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new le(this.embed)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const eh=e=>new le(e.readJSON());class J{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new J(this.key,this.value)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const nh=e=>new J(e.readKey(),e.readJSON());class Nn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Nn(this.arr)}splice(t){const n=new Nn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const oh=e=>new kt(e.readString()),lh=[Fa,Va,Wa,za,Ya,qa,Xa],ch=0,ah=1,hh=2,uh=3,fh=4,dh=5,gh=6;class Et{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Et(this.type._copy())}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const ph=e=>new Et(lh[e.readTypeRef()](e)),Ls=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ye(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},lr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},$n=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Xr=(e,t)=>Ms(e,n=>en(n.deletions,t)),ko=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Z(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||ko(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Z(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||en(s,h.right.id)||Xr(i.undoStack,h.right.id)||Xr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Z(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=j(l,c),y=C(c,p),k=new M(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,lr(k,!0),k.integrate(e,0),k};class M extends or{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Dr:0}set marker(t){(this.info&as)>0!==t&&(this.info^=as)}get marker(){return(this.info&as)>0}get keep(){return(this.info&Cr)>0}set keep(t){this.keep!==t&&(this.info^=Cr)}get countable(){return(this.info&Dr)>0}get deleted(){return(this.info&cs)>0}set deleted(t){this.deleted!==t&&(this.info^=cs)}markDeleted(){this.info|=cs}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=j(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=j(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===me&&this.id.client!==this.parent.client&&this.parent.clock>=j(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=jr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Z(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ct||this.right&&this.right.constructor===ct)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===me){const s=ye(n,this.parent);s.constructor===ct?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=jr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ge(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),qe(t.deleteSet,this.id.client,this.id.clock,this.length),Pr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw rt();this.content.gc(t),n?Sa(t,this,new ct(this.id,this.length)):this.content=new Qe(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Vn|(s===null?0:st)|(r===null?0:Lt)|(i===null?0:Pe);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Xi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===me?(t.writeParentInfo(!1),t.writeLeftID(l)):rt();i!==null&&t.writeString(i)}this.content.write(t,n)}}const bo=(e,t)=>wh[t&Vn](e),wh=[()=>{rt()},Za,sh,Qa,oh,eh,nh,ph,ih,th,()=>{rt()}],mh=10;class at extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){rt()}write(t,n){t.writeInfo(mh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const _o=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Eo="__ $YJS$ __";_o[Eo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");_o[Eo]=!0;const Co=new Map;class yh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Kl(n.newValue||"")}),Tl(this._onChange)}postMessage(t){ci.setItem(this.room,Xl(Wl(t)))}close(){xl(this._onChange)}}const Sh=typeof BroadcastChannel>"u"?yh:BroadcastChannel,cr=e=>bt(Co,e,()=>{const t=Ht(),n=new Sh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),kh=(e,t)=>(cr(e).subs.add(t),t),bh=(e,t)=>{const n=cr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Co.delete(e)),s},de=(e,t,n=null)=>{const s=cr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Do=0,ar=1,Ao=2,Os=(e,t)=>{_(e,Do);const n=ua(t);V(e,n)},Io=(e,t,n)=>{_(e,ar),V(e,Yi(t,n))},_h=(e,t,n)=>Io(t,n,q(e)),To=(e,t,n,s)=>{try{Wi(t,q(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Eh=(e,t)=>{_(e,Ao),V(e,t)},Ch=To,Dh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Do:_h(e,t,n);break;case ar:To(e,n,s,r);break;case Ao:Ch(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ah=0,Ih=(e,t,n)=>{E(e)===Ah&&n(t,Vt(e))},ms=3e4;class xo extends Go{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Pt();this.getLocalState()!==null&&ms/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&ms<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&hr(this,s,"timeout")},dt(ms/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Pt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),pe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const hr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},He=(e,t,n=e.states)=>{const s=t.length,r=X();_(r,s);for(let i=0;i{const s=Wt(t),r=Pt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},xh=e=>Ml(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Qt=0,Lo=3,ke=1,Lh=2,on=[];on[Qt]=(e,t,n,s,r)=>{_(e,Qt);const i=Dh(t,e,n.doc,n);s&&i===ar&&!n.synced&&(n.synced=!0)};on[Lo]=(e,t,n,s,r)=>{_(e,ke),V(e,He(n.awareness,Array.from(n.awareness.getStates().keys())))};on[ke]=(e,t,n,s,r)=>{Th(n.awareness,q(t),n)};on[Lh]=(e,t,n,s,r)=>{Ih(t,n.doc,(i,o)=>Oh(n,o))};const Kr=3e4,Oh=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Oo=(e,t,n)=>{const s=Wt(t),r=X(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Rh=e=>!(e.code>=4400&&e.code<4500),Rs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,hr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Ro,Ns(qo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Ro=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Pt();const s=Oo(e,new Uint8Array(n.data),!0);$s(s)>1&&t.send(F(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Rs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Pt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=X();if(_(n,Qt),Os(n,e.doc),t.send(F(n)),e.awareness.getLocalState()!==null){const s=X();_(s,ke),V(s,He(e.awareness,[e.doc.clientID])),t.send(F(s))}},e.emit("status",[{status:"connecting"}])}},ys=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&de(e.bcChannel,t,e)};class Uh extends vs{constructor(t,n,s,{connect:r=!0,awareness:i=new xo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Rh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=on.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=X();_(f,Qt),Os(f,s),this.ws.send(F(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=Oo(this,new Uint8Array(f),!1);$s(y)>1&&de(this.bcChannel,F(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=X();_(y,Qt),Eh(y,f),ys(this,F(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},k)=>{const w=f.concat(p).concat(y),b=X();_(b,ke),V(b,He(i,w)),ys(this,F(b))},this._exitHandler=()=>{hr(this.awareness,[s.clientID],"app closed")},Jt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Kr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=ma(da(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Uh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},vh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Yi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Qr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,O=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let I;w===0?I=0:L===-w||L!==w&&b[L-1+w-1]=r&&N>=i){u=w;break}}a.push(O)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],O=d-f,L=O===-w||O!==w&&b[O-1+w-1]B&&f>ht;)d--,f--,h.push(d,f);d=I,f=N}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,k=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],O=h[w+1];(b>y||O>k)&&p.push({aS:n+y,aE:n+b,bS:n+k,bE:n+O}),y=b+1,k=O+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +`)||i[o.length]===` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Vh(e,t)<=0?e+t:t+e:null}function Bn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=wt(e,s),l=wt(t,s),c=wt(n,s),a=mt(o,i),u=[...xe(a,mt(l,i)).map(k=>({h:k,toks:l,side:0})),...xe(a,mt(c,i)).map(k=>({h:k,toks:c,side:1}))];u.sort((k,w)=>k.h.aS-w.h.aS||k.h.aE-w.h.aE||k.side-w.side);const h=(k,w,b)=>k.slice(w,b).join(""),d=(k,w,b,O)=>{let L="",I=b;for(const N of k)N.side===w&&(L+=h(o,I,N.h.aS)+h(N.toks,N.h.bS,N.h.bE),I=N.h.aE);return L+h(o,I,O)};let f="",p=0,y=0;for(;yB.side)).size===1){f+=d(k,k[0].side,w,b);continue}const L=d(k,0,w,b),I=d(k,1,w,b);if(L===I){f+=L;continue}if(w===b){const B=jh(L,I,s!==Ss,o.length===0);if(B===null){if(!r)return null;f+=I;continue}f+=B;continue}if(s===Ss)return null;const N=s===Fn?Bn(h(o,w,b),L,I,Ss):Bn(h(o,w,b),L,I,s+1,r);if(N===null){if(!r)return null;f+=I;continue}f+=N}return f+h(o,p,o.length)}const Zt=e=>e===""||e.endsWith(` +`)?e:e+` +`;function Uo(e,t,n,s){let r=t.endsWith(` +`);return r===e.endsWith(` +`)&&(r=n.endsWith(` +`)),s===""||r===s.endsWith(` +`)?s:r?s+` +`:s.slice(0,-1)}function he(e,t,n){const s=Bn(Zt(e),Zt(t),Zt(n),jt);return s===null?{ok:!1}:{ok:!0,text:Uo(e,t,n,s)}}function eu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Bn(Zt(e),Zt(t),Zt(n),jt,!0)??Zt(n);return Uo(e,t,n,s)}function Zr(e,t){if(e===t)return[];const n=[],s=new Map,r=wt(e,jt),i=wt(t,jt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;O>=55296&&O<=56319&&w--;const L=b>0?p.charCodeAt(p.length-b):0;L>=56320&&L<=57343&&b--,k+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:k,deleteCount:p.length,insertText:y}),a=d,u=f}}function Sn(e,t,n){const s=new Map,r=mt(wt(t,jt),s),i=xe(mt(wt(e,jt),s),r),o=xe(r,mt(wt(n,jt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function kn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ti=700,ue=[2e3,4e3,8e3,15e3],ei=2e3,Ph=4,Jh=64,Wh=8,Yh=32e3,zh=32;function nu(e){let t=e.seed,n=e.baseSha;const s=(g,S)=>{t=g,r=S,It(S);const m=Ut.lastIndexOf(g);m>=0?Ut.splice(0,m+1):Ut.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const S=[];for(let m=g;m!==null&&S.length<4;m=m.prev)m.sent!==m.from&&!S.includes(m.sent)&&S.push(m.sent);return S.length?S:void 0},o=(g,S=Ct)=>{const m=i(S);return r&&r===n&&t.length>Yh?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,k=!1,w=null,b=null,O="",L=0;const I=(g=Date.now())=>{const S=Math.max(g,L+1e3);return L=S,Ho(e.path,e.who||"browser",new Date(S))},N=new Map;let B=0,ht=!1,it=null,Yt=0,Zn=!1,Ct=null,zt=!1;const Ut=[],ur=g=>{Ut.at(-1)!==g&&(Ut.push(g),Ut.length>zh&&Ut.shift())};let Dt=!1,Me=null,Gt=0;const ve=()=>{Dt=!1,Me=null},ts=g=>{Gt===g&&ve()};let et=0,ut=0,ln=null,qt=null,es=!1,At=null,Ne=!1,Xt=null,ot=null;const $=g=>e.onState?.(g),cn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Mt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let an=null,ns=0;const $e=()=>{clearTimeout(an??void 0),an=null},hn=g=>{if(!(g instanceof nt?g.status>=500||g.status===429:!0)||h||a)return;$e();const m=ue[Math.min(ns,ue.length-1)];ns++,an=setTimeout(()=>{an=null,!h&&!a&&Fe()},m)},fr=()=>{$e(),ns=0},un=()=>{$e(),Xt&&clearTimeout(Xt),Xt=setTimeout(()=>{Fe()},ti)},Kt=g=>{if(h)return f=g,!0;const S=H();if(S===g)return!0;const m=Zr(S,g);if(yr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Fe=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():Ve();if(qt)return es=!0,qt;const g=(async()=>{try{await Mo()}finally{qt=null}})();return qt=g,g},Mo=async()=>{let g=0;for(;;){if(es=!1,W||a||k)return;const S=H();if(S===t&&!zt){$("clean");return}if($("saving"),e.onWriting?.(),ht){if(w!==null&&b===S){if(await fn(S,O)==="stop")return;continue}ht=!1}const m=l||c?await vo(S):await $o(S);if(m==="stop")return;if(m==="rebased"){if(++g>Ph){await fn(H(),n??"");return}continue}if(!es){$(H()===t&&!zt?"clean":"dirty");return}}};let vt=!1;const vo=async g=>{At=g,Ne=!1;let S;try{S=await gn(cn(e.path),g,n,vt)}catch(m){return At=null,m instanceof nt&&m.status===422&&kn(m)?(vt=!1,Be(g),"stop"):m instanceof nt&&m.status===409?await dr(t,!1)?"rebased":"stop":($("error"),hn(m),"stop")}return At=null,vt=!1,fr(),S.merged?await dr(g,!0)?"rebased":"stop":(Ne||s(g,S.sha),e.onSaved?.(g),"done")},dr=async(g,S)=>{let m;try{m=await _r(Er(e.apiBase,e.path))}catch(v){return $("error"),H()!==t&&hn(v),!1}if(m.kind!=="text")return $("error"),!1;const A=H(),D=he(g,m.text,A);return!D.ok||!Kt(D.text)?(S&&It(m.sha),await fn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),S&&e.onSaved?.(m.text),!0)},No=g=>{if(g.update&&T.applyRemoteUpdate(g.update),typeof g.text!="string"){Ct=null;return}let S=null;for(let m=Ct;m!==null;m=m.prev)if(m.sent!==m.from&&Sn(m.from,m.sent,g.text)){S=m;break}if(Ct=null,S){zt=!0;const m=he(S.sent,g.text,H());m.ok&&Kt(m.text)?(t=g.text,r=void 0,It(g.sha)):(t=S.sent,r=void 0)}},$o=async g=>{At=g,Ne=!1;let S;const m=Ct;try{Ct={sent:g,from:t,prev:m},S=await $t(Mt,{...o(g,m),...vt?{confirm_shrink:!0}:{}})}catch(D){if(At=null,D instanceof nt&&[400,401,403,404,405,409,413].includes(D.status)&&(Ct=m),D instanceof nt&&(D.status===404||D.status===405))return c=!0,"rebased";if(D instanceof nt&&D.status===422&&kn(D))return vt=!1,Be(g),"stop";if(D instanceof nt&&D.status===409&&!a){let v={};try{v=JSON.parse(D.body)}catch{}const x=typeof v.text=="string"?v.text:null;if(x!==null){const R=he(t,x,H());if(R.ok&&Kt(R.text))return t=x,r=void 0,It(v.sha),"rebased"}return fn(H(),v.sha??"")}return $(a?"dirty":"error"),hn(D),"stop"}if(At=null,vt=!1,fr(),S.update&&T.applyRemoteUpdate(S.update),Ct=null,zt=!1,a)return"stop";const A=he(g,S.text,H());return A.ok&&Kt(A.text)&&(Ne||s(S.text,S.sha)),e.onSaved?.(S.text),"done"};let W=null;const Be=g=>{W||h||!e.onShrinkRefused||($("error"),W={was:pn(t),now:pn(g),confirm:async()=>{if(!h){if(a){$("saving"),e.onWriting?.();const S=et,m=Gt;try{const A=await $t(Mt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),ss(S,m);const D=!Dt&&ut>=et;$(D?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&ut{if(!h)try{const S=await _r(Er(e.apiBase,e.path));if(h||S.kind!=="text")return;if(s(S.text,S.sha),Kt(S.text),W=null,a&&!u){if(await ce(!1),h)return;$(ut>=et&&!Dt?"clean":"dirty");return}ut=et,d&&(d=0,e.onPending?.(0)),ve(),$("clean")}catch{$("error")}finally{W=null}}},e.onShrinkRefused(W))};let Nt=null;const Fo=()=>{Nt&&clearTimeout(Nt),Nt=setTimeout(()=>{const g=H();Po(pn(t),pn(g))&&Be(g)},ti)},gr=async(g,S,m=I())=>{const A=++B;let D=m;for(let v=1;;v++){const x=D;N.set(x,g);try{return await gn(cn(x),g,void 0,!1,!1,!1,!0),A===B&&!a&&(t=g,r=void 0,S&&(n=S),$("clean")),e.onConflictCopy?.(x),null}catch(R){if(R instanceof nt&&R.status===409&&v{const D=(v,x)=>{gn(cn(v),S,void 0,!1,!0,!0,!0).then(R=>A?.(R.parked??v),R=>{if(R instanceof nt&&R.status===409&&x{(w===null||b!==g)&&(w=I(),b=g);const m=w;O=S,ht=!0;const A=await gr(g,S,m);return h?"stop":A?(hn(A.err),"stop"):(ht=!1,b===g&&(w=null,b=null,O=""),H()!==g?"rebased":"stop")},ss=(g,S)=>{ut=Math.max(ut,g),ts(S),!(h||u)&&(d=et-ut,e.onPending?.(d))},Bo=()=>{h||u||W||ot||(ot=setTimeout(()=>{ot=null,!u&&!h&&ce(!1)},ei))},ce=g=>{if(clearTimeout(ot??void 0),ot=null,g){if(ut>=et)return Promise.resolve();const m=et,A=Gt;return $t(Mt,{update:T.encodeState(),base:n},!0).then(D=>{It(D.sha),ss(m,A)})}if(ln)return ln;const S=(async()=>{try{for(;!u&&!h&&!W&&ut{p=!1,w=null,b=null,Yt=0,clearTimeout(it??void 0),it=null,zt=!1,a=!0,ur(T.text.toString()),g?.(),Zn&&(Zn=!1,e.onReady(T))},Ve=async()=>{if(h||a||y||k)return;if(clearTimeout(it??void 0),it=null,Xt&&clearTimeout(Xt),Xt=null,qt){k=!0;try{for(;qt;)await qt}finally{k=!1}if(h||a)return;if(!u){H()!==t&&un();return}}if(Ct!==null&&!c){let x;k=!0;try{x=await $t(Mt,{peek:!0})}catch{if(h||a)return;const R=ue[Math.min(Yt,ue.length-1)];Yt++,it=setTimeout(()=>{it=null,Ve()},R);return}finally{k=!1}if(h||a)return;if(No(x),!u){(H()!==t||zt)&&un();return}}const g=e.soloText?.();if(g===void 0||g===t)return rs();const S=T.text.toString(),m=he(t,S,g);if(m.ok)return rs(()=>T.applySplices(Zr(S,m.text)));p=!0,(w===null||b!==g)&&(w=I(),b=g),y=!0;let A;try{A=await gr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,Ve()):rs(()=>{t=T.text.toString()});const D=A.err;if(D instanceof nt&&!(D.status>=500||D.status===429))return;const v=ue[Math.min(Yt,ue.length-1)];Yt++,it=setTimeout(()=>{it=null,Ve()},v)},T=new Mh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(ot&&clearTimeout(ot),ot=null,$e(),a||Ve(),ut=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(T):Zn=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),wr=(g,S)=>{const m=a?T.text.toString():null;if(m!==null&&ur(m),!T.isRemote(S?.origin)){if($("dirty"),a){Dt=!0,Me=m,Gt+=1,u||(et+=1,d=et-ut,e.onPending?.(d),clearTimeout(ot??void 0),ot=setTimeout(()=>{ot=null,!u&&!h&&ce(!1)},ei)),Fo();return}un()}};T.text.observe(wr);const mr=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",mr),Nh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const H=()=>f!==null?f:yr()?T.text.toString():e.soloText?.()??"",yr=()=>a||l&&T.text.length>0,It=g=>{g&&(n=g)},Vo=(g,S,m)=>{if(m?.held)return s(g,S),"same";if(g===t||g===At)return It(S),"same";const A=H();if(g===A)return s(g,S),a&&(ve(),$("clean")),"same";if(a){const v=t;return Ut.includes(g)||Sn(v,g,A)?(s(g,S),Dt&&(Me===null||g===Me||Sn(v,Me,g))&&(ve(),$("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(g,S),Kt(g),ve(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const D=he(t,g,A);return D.ok?(At!==null&&(Ne=!0),s(g,S),Kt(D.text),D.text!==g?un():At===null&&$("clean"),D.text===A?"same":"merged"):"blocked"};let dn=null;const jo=()=>{if(!a)return Fe();if(W||h)return Promise.resolve();if(!u)return d>0?ce(!1):Promise.resolve();if(!Dt)return Promise.resolve();if(dn)return dn;const g=Gt;$("saving");const S=(async()=>{try{const m=await $t(Mt,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),ts(g),$(Dt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof nt&&m.status===422&&kn(m)&&(clearTimeout(Nt??void 0),Nt=null,Be(H()),W))return;$(Dt?"dirty":"clean")}finally{dn=null}})();return dn=S,S};let Tt=null;const is=g=>()=>{Tt===g&&(Tt=null)},Sr=(g,S)=>{if(W)return;if(a){const x=!u&&d>0;if(!x&&!(u&&Dt))return;const R="room\0"+T.text.toString();if(Tt===R)return;Tt=R;const lt=Gt;(x?ce(!0):$t(Mt,{update:T.encodeState()},!0).then(os=>It(os.sha))).then(()=>ts(lt),is(R));return}if(p||ht){const x="park\0"+g;if(Tt===x)return;Tt=x;let R=w!==null&&b===g?w:null;for(const[lt,gt]of N)R===null&>===g&&(R=lt);R??=I(),pr(R,g,x);return}if(!g||g===t)return;const m="text\0"+g;if(Tt===m)return;if((l||c)&&!S){Fe();return}Tt=m;const A=t,D=x=>{if(!(x instanceof nt&&x.status===409))return is(m)();let R={};try{const gt=JSON.parse(x.body);gt&&typeof gt=="object"&&(R=gt)}catch{}if(typeof R.text=="string"&&(R.text===g||Sn(A,g,R.text)))return;ht=!0;let lt=w!==null&&b===g?w:null;for(const[gt,os]of N)lt===null&&os===g&&(lt=gt);lt??=I(),w=lt,b=g,pr(lt,g,m,gt=>{ht=!1,e.onConflictCopy?.(gt)})},v=x=>{x.parked&&e.onConflictCopy?.(x.parked)};l||c?gn(cn(e.path),g,n,vt,!0,!0).then(v,D):$t(Mt,{...o(g),park_on_conflict:!0},!0).then(v,D)},kr=()=>{h||Sr(H(),!0)},br=()=>{Tt=null};return typeof window<"u"&&(window.addEventListener("pagehide",kr),window.addEventListener("pageshow",br)),{collab:T,current:H,merge:Vo,rebase:It,saveNow:jo,askingShrink:()=>W!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",kr),window.removeEventListener("pageshow",br)),clearTimeout(Xt??void 0),clearTimeout(Nt??void 0),$e(),clearTimeout(it??void 0),it=null;const g=H();h=!0,f=g,W?e.onShrinkWithdrawn?.(W):Sr(g,!1),clearTimeout(ot??void 0),T.awareness.off("change",mr),T.text.unobserve(wr),T.destroy()}}}export{oe as D,ti as S,tu as U,Qh as a,da as b,ma as c,Zr as d,Zh as e,Ns as f,ie as g,qh as h,xt as i,eu as m,nu as o,Kh as r,Xh as t}; diff --git a/internal/webapp/static/assets/sharedfile-s3I9dExU.js b/internal/webapp/static/assets/sharedfile-s3I9dExU.js deleted file mode 100644 index f2eb7d96..00000000 --- a/internal/webapp/static/assets/sharedfile-s3I9dExU.js +++ /dev/null @@ -1,16 +0,0 @@ -import{H as ht,h as Je,i as Nt,k as Ho,f as br,e as _r,l as mn,m as Jo}from"./index-xYv7N57r.js";const tt=()=>new Map,Ss=e=>{const t=tt();return e.forEach((n,s)=>{t.set(s,n)}),t},kt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Po=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Wo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},jt=()=>new Set,ls=e=>e[e.length-1],Yo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Lt((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}class Go{constructor(){this._observers=tt()}on(t,n){kt(this._observers,t,jt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Lt((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}const ft=Math.floor,En=Math.abs,Ns=(e,t)=>ee>t?e:t,qo=Math.pow,ei=e=>e!==0?e<0:1/e<0,Er=1,Cr=2,cs=4,as=8,Ye=32,xt=64,nt=128,Hn=31,bs=63,te=127,Xo=2147483647,In=Number.MAX_SAFE_INTEGER,Dr=Number.MIN_SAFE_INTEGER,Ko=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&ft(e)===e),ni=String.fromCharCode,Qo=e=>e.toLowerCase(),Zo=/^\s*/g,tl=e=>e.replace(Zo,""),el=/([A-Z])/g,Ar=(e,t)=>tl(e.replace(el,n=>`${t}${Qo(n)}`)),nl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rze.encode(e),rl=ze?sl:nl;let Pe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Pe&&Pe.decode(new Uint8Array).length===1&&(Pe=null);const il=(e,t)=>zo(t,()=>e).join("");class nn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const X=()=>new nn,$s=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array($s(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},_s=Y,_=(e,t)=>{for(;t>te;)Y(e,nt|te&t),t=ft(t/128);Y(e,te&t)},Fs=(e,t)=>{const n=ei(t);for(n&&(t=-t),Y(e,(t>bs?nt:0)|(n?xt:0)|bs&t),t=ft(t/64);t>0;)Y(e,(t>te?nt:0)|te&t),t=ft(t/128)},Es=new Uint8Array(3e4),ll=Es.length/3,cl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ns(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ie(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},F=(e,t)=>{_(e,t.byteLength),Jn(e,t)},Bs=(e,t)=>{ol(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},hl=(e,t)=>Bs(e,4).setFloat32(0,t,!1),ul=(e,t)=>Bs(e,8).setFloat64(0,t,!1),fl=(e,t)=>Bs(e,8).setBigInt64(0,t,!1),Ir=new DataView(new ArrayBuffer(4)),dl=e=>(Ir.setFloat32(0,e),Ir.getFloat32(0)===e),Ge=(e,t)=>{switch(typeof t){case"string":Y(e,119),ee(e,t);break;case"number":Ko(t)&&En(t)<=Xo?(Y(e,125),Fs(e,t)):dl(t)?(Y(e,124),hl(e,t)):(Y(e,123),ul(e,t));break;case"bigint":Y(e,122),fl(e,t);break;case"object":if(t===null)Y(e,126);else if(be(t)){Y(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const xr=e=>{e.count>0&&(Fs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class Cn{constructor(){this.encoder=new nn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(xr(this),this.count=1,this.s=t)}toUint8Array(){return xr(this),v(this.encoder)}}const Lr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Fs(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class hs{constructor(){this.encoder=new nn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Lr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Lr(this),v(this.encoder)}}class gl{constructor(){this.sarr=[],this.s="",this.lensE=new Cn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new nn;return this.sarr.push(this.s),this.s="",ee(t,this.sarr.join("")),Jn(t,this.lensE.toUint8Array()),v(t)}}const wt=e=>new Error(e),ut=()=>{throw wt("Method unimplemented")},st=()=>{throw wt("Unexpected case")},si=wt("Unexpected end of array"),ri=wt("Integer out of Range");class Pn{constructor(t){this.arr=t,this.pos=0}}const Pt=e=>new Pn(e),pl=e=>e.pos!==e.arr.length,wl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},q=e=>wl(e,E(e)),_e=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posIn)throw ri}throw si},Vs=e=>{let t=e.arr[e.pos++],n=t&bs,s=64;const r=(t&xt)>0?-1:1;if((t&nt)===0)return r*n;const i=e.arr.length;for(;e.posIn)throw ri}throw si},ml=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(_e(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(_e(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},yl=e=>Pe.decode(q(e)),Bt=Pe?yl:ml,js=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},kl=e=>js(e,4).getFloat32(0,!1),Sl=e=>js(e,8).getFloat64(0,!1),bl=e=>js(e,8).getBigInt64(0,!1),_l=[e=>{},e=>null,Vs,kl,Sl,bl,e=>!1,e=>!0,Bt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;s_l[127-_e(e)](e);class Or extends Pn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),pl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Dn extends Pn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vs(this);const t=ei(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class us extends Pn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Vs(this),n=t&1;this.diff=ft(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class El{constructor(t){this.decoder=new Dn(t),this.str=Bt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Cl=crypto.getRandomValues.bind(crypto),ii=()=>Cl(new Uint32Array(1))[0],Dl="10000000-1000-4000-8000"+-1e11,Al=()=>Dl.replace(/[018]/g,e=>(e^ii()&15>>e/4).toString(16)),Ht=Date.now,Rr=e=>new Promise(e);Promise.all.bind(Promise);const Ur=e=>e===void 0?null:e;class Il{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let oi=new Il,Hs=!0;try{typeof localStorage<"u"&&localStorage&&(oi=localStorage,Hs=!1)}catch{}const li=oi,Tl=e=>Hs||addEventListener("storage",e),xl=e=>Hs||removeEventListener("storage",e),Xe=Symbol("Equality"),ci=(e,t)=>e===t||!!e?.[Xe]?.(t)||!1,Ll=e=>typeof e=="object",Ol=Object.assign,Rl=Object.keys,Ul=(e,t)=>{for(const n in e)t(e[n],n)},Ml=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Tn=e=>Rl(e).length,vl=e=>{for(const t in e)return!1;return!0},sn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Js=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Nl=(e,t)=>e===t||Tn(e)===Tn(t)&&sn(e,(n,s)=>(n!==void 0||Js(t,s))&&ci(t[s],n)),$l=Object.freeze,ai=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&ai(e[t])}return $l(e)},Ps=(e,t,n=0)=>{try{for(;ne,pe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Xe]!=null)return e[Xe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var hi={};const Jt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ui=typeof window<"u"&&typeof document<"u"&&!Jt;let dt;const Vl=()=>{if(dt===void 0)if(Jt){dt=tt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");dt.set(`--${Ar(t,"-")}`,n),dt.set(`-${Ar(t,"-")}`,n)}})):dt=tt();return dt},Cs=e=>Vl().has(e),xn=e=>Ur(Jt?hi[e.toUpperCase().replaceAll("-","_")]:li.getItem(e)),fi=e=>Cs("--"+e)||xn(e)!==null,jl=fi("production"),Hl=Jt&&Bl(hi.FORCE_COLOR,["true","1","2"]),Jl=Hl||!Cs("--no-colors")&&!fi("no-color")&&(!Jt||process.stdout.isTTY)&&(!Jt||Cs("--color")||xn("COLORTERM")!==null||(xn("TERM")||"").includes("color")),di=e=>new Uint8Array(e),Pl=(e,t,n)=>new Uint8Array(e,t,n),Wl=e=>new Uint8Array(e),Yl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Gl=e=>{const t=atob(e),n=di(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Pl(t.buffer,t.byteOffset,t.byteLength)},Xl=ui?Yl:zl,Kl=ui?Gl:ql,Ql=e=>{const t=di(e.byteLength);return t.set(e),t};class Zl{constructor(t,n){this.left=t,this.right=n}}const Tt=(e,t)=>new Zl(e,t),tc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Mr=e=>e.next()>=.5,fs=(e,t,n)=>ft(e.next()*(n+1-t)+t),gi=(e,t,n)=>ft(e.next()*(n+1-t)+t),Ws=(e,t,n)=>gi(e,t,n),ec=e=>ni(Ws(e,97,122)),nc=(e,t=0,n=20)=>{const s=Ws(e,t,n);let r="";for(let i=0;it[Ws(e,0,t.length-1)],sc=Symbol("0schema");class rc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(il(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const Ds=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Xe]?ci(e,t):be(e)?Us(e,n=>Ms(t,s=>Ds(n,s))):Ll(e)?sn(e,(n,s)=>Ds(n,t[s])):!1;class Q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Ds(n,s)}equals(t){return this.constructor===t.constructor&&pe(this.shape,t.shape)}[sc](){return!0}[Xe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ut()}get nullable(){return Le(this,qn)}get optional(){return new mi(this)}cast(t){return vr(t,this),t}expect(t){return vr(t,this),t}}class Ys extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const j=(e,t=null)=>new Ys(e,t);j(Ys);class zs extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new zs(e);j(zs);class Wn extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Yn=(...e)=>new Wn(e),pi=j(Wn),ic=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),wi=e=>{if(Ee.check(e))return[ic(e)];if(pi.check(e))return e.shape.map(t=>t+"");if(Ai.check(e))return["[+-]?\\d+.?\\d*"];if(Ii.check(e))return[".*"];if(Ln.check(e))return e.shape.map(wi).flat(1);st()};class oc extends Q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(wi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}j(oc);const lc=Symbol("optional");class mi extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[lc](){return!0}}const cc=j(mi);class ac extends Q{check(t,n){return n?.extend(null,"never",typeof t),!1}}j(ac);class zn extends Q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new zn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):sn(this.shape,(s,r)=>{const i=this._isPartial&&!Js(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const hc=e=>new zn(e),uc=j(zn),fc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class yi extends Q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&sn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const ki=(e,t)=>new yi(e,t),dc=j(yi);class Si extends Q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&sn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const gc=(...e)=>new Si(e);j(Si);class bi extends Q{constructor(t){super(),this.shape=t.length===1?t[0]:new Gs(t)}check(t,n){const s=be(t)&&Us(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const _i=(...e)=>new bi(e),pc=j(bi),wc=G(e=>be(e));class Ei extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const mc=(e,t=null)=>new Ei(e,t);j(Ei);const yc=mc(Q);class kc extends Q{constructor(t){super(),this.len=t.length-1,this.args=gc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Sc=j(kc),bc=G(e=>typeof e=="function");class _c extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=Us(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}j(_c,e=>e.shape.length>0);class Gs extends Q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ms(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Le=(...e)=>e.findIndex(t=>Ln.check(t))>=0?Le(...e.map(t=>Ke(t)).map(t=>Ln.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Gs(e),Ln=j(Gs),Ci=()=>!0,On=G(Ci),Ec=j(zs,e=>e.shape===Ci),qs=G(e=>typeof e=="bigint"),Cc=G(e=>e===qs),Di=G(e=>typeof e=="symbol");G(e=>e===Di);const we=G(e=>typeof e=="number"),Ai=G(e=>e===we),Ee=G(e=>typeof e=="string"),Ii=G(e=>e===Ee),Gn=G(e=>typeof e=="boolean"),Dc=G(e=>e===Gn),Ti=Yn(void 0);j(Wn,e=>e.shape.length===1&&e.shape[0]===void 0);Yn(void 0);const qn=Yn(null),Ac=j(Wn,e=>e.shape.length===1&&e.shape[0]===null);j(Uint8Array);j(Ys,e=>e.shape===Uint8Array);const Ic=Le(we,Ee,qn,Ti,qs,Gn,Di);(()=>{const e=_i(On),t=ki(Ee,On),n=Le(we,Ee,qn,Gn,e,t);return e.shape=n,t.shape.values=n,n})();const Ke=e=>{if(yc.check(e))return e;if(fc.check(e)){const t={};for(const n in e)t[n]=Ke(e[n]);return hc(t)}else{if(wc.check(e))return Le(...e.map(Ke));if(Ic.check(e))return Yn(e);if(bc.check(e))return j(e)}st()},vr=jl?()=>{}:(e,t)=>{const n=new rc;if(!t.check(e,n))throw wt(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Tc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ke(t),h:n}),this}else(t){return this.if(On,t)}done(){return(t,n)=>{for(let s=0;snew Tc(e),xi=xc(On).if(Ai,(e,t)=>fs(t,Dr,In)).if(Ii,(e,t)=>nc(t)).if(Dc,(e,t)=>Mr(t)).if(Cc,(e,t)=>BigInt(fs(t,Dr,In))).if(Ln,(e,t)=>ae(t,ds(t,e.shape))).if(uc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(cc.check(r)){if(Mr(t))continue;r=r.shape}n[s]=xi(r,t)}return n}).if(pc,(e,t)=>{const n=[],s=gi(t,0,42);for(let r=0;rds(t,e.shape)).if(Ac,(e,t)=>null).if(Sc,(e,t)=>{const n=ae(t,e.res);return()=>n}).if(Ec,(e,t)=>ae(t,ds(t,[we,Ee,qn,Ti,qs,Gn,_i(we),ki(Le("a","b","c"),we)]))).if(dc,(e,t)=>{const n={},s=fs(t,0,3);for(let r=0;rxi(Ke(t),e),St=typeof document<"u"?document:{},Lc=e=>St.createElement(e),Oc=()=>St.createDocumentFragment();G(e=>e.nodeType===Vc);const Rc=e=>St.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Uc=(e,t)=>(tc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Mc=e=>{const t=Oc();for(let n=0;n(Li(e,Mc(t)),e),zh=(e,t=[],n=[])=>vc(Uc(Lc(e),t),n);G(e=>e.nodeType===$c);const Gh=Rc;G(e=>e.nodeType===Fc);const Nc=e=>Po(e,(t,n)=>`${n}:${t};`).join(""),Li=(e,t)=>e.appendChild(t),$c=St.ELEMENT_NODE,Fc=St.TEXT_NODE;St.CDATA_SECTION_NODE;St.COMMENT_NODE;const Bc=St.DOCUMENT_NODE;St.DOCUMENT_TYPE_NODE;const Vc=St.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Bc);const Ot=Symbol,Oi=Ot(),Ri=Ot(),jc=Ot(),Hc=Ot(),Jc=Ot(),Ui=Ot(),Pc=Ot(),Xs=Ot(),Wc=Ot(),Yc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=tt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Mi(e)),Ni.forEach(t=>t.print(e))},vi=(...e)=>{console.warn(...Mi(e)),e.unshift(Xs),Ni.forEach(t=>t.print(e))},Ni=jt(),$i=e=>({[Symbol.iterator](){return this},next:e}),Xc=(e,t)=>$i(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),gs=(e,t)=>$i(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Xn{constructor(t,n){this.clock=t,this.len=n}}class Oe{constructor(){this.clients=new Map}}const Ce=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=ft((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Kc(n,t.clock)!==null},Ks=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Xn(r.clock,ie(r.len,i.clock+i.len-r.clock)):(s{const t=new Oe;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{kt(e.clients,t,()=>[]).push(new Xn(n,s))},Qc=()=>new Oe,Zc=e=>{const t=Qc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Re=(e,t)=>{_(e.restEncoder,t.clients.size),Lt(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Oe,n=E(e.restDecoder);for(let s=0;s0){const o=kt(t.clients,r,()=>[]);for(let l=0;l{const s=new Oe,r=E(e.restDecoder);for(let i=0;i0){const i=new ne;return _(i.restEncoder,0),Re(i,s),i.toUint8Array()}return null},Fi=ii;class oe extends vs{constructor({guid:t=Al(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Fi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Ki,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Rr(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Rr(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&O(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Lt(this.subdocs).map(t=>t.guid))}transact(t,n=null){return O(this,t,n)}get(t,n=z){const s=kt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,ke)}getText(t=""){return this.get(t,Ie)}getMap(t=""){return this.get(t,Ae)}getXmlElement(t=""){return this.get(t,Te)}getXmlFragment(t=""){return this.get(t,se)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Lt(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new oe({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,O(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Bi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class Vi extends Bi{readLeftID(){return C(E(this.restDecoder),E(this.restDecoder))}readRightID(){return C(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return _e(this.restDecoder)}readString(){return Bt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return qe(this.restDecoder)}readBuf(){return Ql(q(this.restDecoder))}readJSON(){return JSON.parse(Bt(this.restDecoder))}readKey(){return Bt(this.restDecoder)}}class ta{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class De extends ta{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new us(q(t)),this.clientDecoder=new Dn(q(t)),this.leftClockDecoder=new us(q(t)),this.rightClockDecoder=new us(q(t)),this.infoDecoder=new Or(q(t),_e),this.stringDecoder=new El(q(t)),this.parentInfoDecoder=new Or(q(t),_e),this.typeRefDecoder=new Dn(q(t)),this.lenDecoder=new Dn(q(t))}readLeftID(){return new me(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new me(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return qe(this.restDecoder)}readBuf(){return q(this.restDecoder)}readJSON(){return qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ie(s,t[0].id.clock);const r=mt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{B(t,i)>r&&s.set(i,r)}),Kn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),Lt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ea(e,t.clients.get(r),r,i)})},na=(e,t)=>{const n=tt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=Lt(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Ki,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(S=>S!==p)}s.length=0};for(;;){if(u.constructor!==lt){const p=kt(h,u.id.client,()=>B(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,B(t,y)),d();else{u=S.refs[S.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new ne;return Zs(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ra=(e,t)=>Zs(e,t.doc.store,t.beforeState),ia=(e,t,n,s=new De(e))=>O(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=na(s,o),a=sa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=Un([u.update,a.update])}}else l.pendingStructs=a;const h=Nr(s,r,l);if(l.pendingDs){const d=new De(Pt(l.pendingDs));E(d.restDecoder);const f=Nr(d,r,l);h&&f?l.pendingDs=Un([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Ji(r.doc,d)}},n,!1),Ji=(e,t,n,s=De)=>{const r=Pt(t);ia(r,e,n,new s(r))},Pi=(e,t,n)=>Ji(e,t,n,Vi),oa=(e,t,n=new Map)=>{Zs(e,t.store,n),Re(e,Zc(t.store))},la=(e,t=new Uint8Array([0]),n=new ne)=>{const s=Yi(t);oa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ia(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===on)return Da(r.map((i,o)=>o===0?i:xa(i)));if(n.constructor===ne)return Un(r)}return r[0]},Wi=(e,t)=>la(e,t,new on),ca=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sca(new Bi(Pt(e))),zi=(e,t)=>(_(e.restEncoder,t.size),Lt(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),aa=(e,t)=>zi(e,Kn(t.store)),ha=(e,t=new Hi)=>(e instanceof Map?zi(t,e):aa(t,e),t.toUint8Array()),ua=e=>ha(e,new ji);class fa{constructor(){this.l=[]}}const $r=()=>new fa,Fr=(e,t)=>e.l.push(t),Br=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Gi=(e,t,n)=>Ps(e.l,[t,n]);class me{constructor(t,n){this.client=t,this.clock=n}}const ge=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new me(e,t),qi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw st()},Rn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Xi{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const qh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},da=e=>new Xi(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ga{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const pa=(e,t,n=0)=>new ga(e,t,n),yn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=qi(e):s=C(e._item.id.client,e._item.id.clock),new Xi(s,r,t,n)},Xh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return yn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return yn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return yn(e,s.lastId,n);s=s.right}return yn(e,null,n)},wa=(e,t)=>{const n=ye(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},ma=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(B(s,r.client)<=r.clock)return null;const u=n?Ls(s,r):wa(s,r),h=u.item;if(!(h instanceof R))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(B(s,i.client)<=i.clock)return null;const{item:u}=n?Ls(s,i):{item:ye(s,i)};if(u instanceof R&&u.content instanceof bt)c=u.content.type;else return null}else throw st();l>=0?a=c._length:a=0}return pa(c,a,e.assoc)},Kh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ge(e.item,t.item)&&ge(e.type,t.type)&&e.assoc===t.assoc,fe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!rn(t.ds,e.id),Is=(e,t)=>{const n=kt(e.meta,Is,jt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Ki{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Kn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},B=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Qi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw st()}n.push(t)},mt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=ft(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[mt(n,t.clock)]},ye=ya,Ts=(e,t,n)=>{const s=mt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ts(e,n,t.clock)]},Vr=(e,t,n)=>{const s=t.clients.get(n.client),r=mt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ot&&s.splice(r+1,0,Bn(e,i,n.clock-i.id.clock+1)),i},ka=(e,t,n)=>{const s=e.clients.get(t.id.client);s[mt(s,t.id.clock)]=n},Zi=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ts(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Wo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ks(t.deleteSet),ra(e,t),Re(e,t.deleteSet),!0),Hr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&kt(e.changed,t,jt).add(n)},An=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof R&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ba=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=mt(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ns(r.length-1,1+mt(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+An(r,c)}})},to=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{Gi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ja(n)})}),Ps(l,[])}finally{s.gc&&ba(i,r,s.gcFilter),_a(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ie(mt(f,d),1);for(let y=f.length-1;y>=p;)y-=1+An(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=mt(f,d);p+11||p>0&&An(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(qc(Xs,Oi,"[yjs] ",Ri,Ui,"Changed the client-id because another client seems to be using it."),s.clientID=Fi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new on;jr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new ne;jr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):to(e,t+1)}}},O=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Sa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&to(r,0)}}return o};class Ea{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Jr=(e,t,n)=>{Ce(e,n.deletions,s=>{s instanceof R&&t.scope.some(r=>r===e.doc||Rn(r,s))&&lr(s,!1)})},Pr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;O(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Ce(l,a.insertions,f=>{if(f instanceof R){if(f.redone!==null){let{item:p,diff:y}=Ls(c,f.id);y>0&&(p=Z(l,C(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||Rn(p,f))&&h.push(f)}}),Ce(l,a.deletions,f=>{f instanceof R&&i.some(p=>p===l.doc||Rn(p,f))&&!rn(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=ko(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class Qh extends vs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=be(t)?t[0].doc:t instanceof oe?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Oe;c.afterState.forEach((S,w)=>{const b=c.beforeState.get(w)||0,L=S-b;L>0&&Qe(d,w,b,L)});const f=Ht();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=As([S.deletions,c.deleteSet]),S.insertions=As([S.insertions,d])}else h.push(new Ea(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Ce(c,c.deleteSet,S=>{S instanceof R&&this.scope.some(w=>w===c.doc||Rn(w,S))&&lr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=be(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&vi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Jr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Jr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Pr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Pr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ca(e){const t=E(e.restDecoder);for(let n=0;nUn(e,Vi,on),Aa=(e,t)=>{if(e.constructor===ot){const{client:n,clock:s}=e.id;return new ot(C(n,s+t),e.length-t)}else if(e.constructor===lt){const{client:n,clock:s}=e.id;return new lt(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new R(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Un=(e,t=De,n=ne)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Pt(u)));let r=s.map(u=>new tr(u,!0)),i=null;const o=new n,l=new er(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===lt?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)$t(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===lt?i.struct.length-=p:d=Aa(d,p)),i.struct.mergeWith(d)||($t(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==lt;d=u.next())$t(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&($t(l,i.struct,i.offset),i=null),nr(l);const c=s.map(u=>Qs(u)),a=As(c);return Re(o,a),o.toUint8Array()},Ia=(e,t,n=De,s=ne)=>{const r=Yi(t),i=new s,o=new er(i),l=new n(Pt(e)),c=new tr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===lt){c.next();continue}if(u.id.clock+u.length>d)for($t(o,u,ie(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)$t(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}nr(o);const a=Qs(l);return Re(i,a),i.toUint8Array()},eo=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=X(),e.written=0)},$t=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&eo(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},nr=e=>{eo(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Pt(e)),i=new tr(r,!1),o=new s,l=new er(o);for(let a=i.curr;a!==null;a=i.next())$t(l,t(a),0);nr(l);const c=Qs(r);return Re(o,c),o.toUint8Array()},xa=e=>Ta(e,Fl,De,on),Wr="You must not compute changes after the event-handler fired.";class Qn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=La(this.currentTarget,this.target))}deletes(t){return rn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw wt(Wr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ls(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ls(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ls(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw wt(Wr);const n=this.target,s=jt(),r=jt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const La=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},K=()=>{vi("Invalid access: Add Yjs type to a document before reading data.")},no=80;let sr=0;class Oa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=sr++}}const Ra=e=>{e.timestamp=sr++},so=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=sr++},Ua=(e,t,n)=>{if(e.length>=no){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>En(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&En(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ie(t,r.index+n))}},ts=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;kt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Gi(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=$r(),this._dEH=$r(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ut()}clone(){throw ut()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Fr(this._eH,t)}observeDeep(t){Fr(this._dEH,t)}unobserve(t){Br(this._eH,t)}unobserveDeep(t){Br(this._dEH,t)}toJSON(){}}const ro=(e,t,n)=>{e.doc??K(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},io=e=>{e.doc??K();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??K();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return tn(e,(s,r)=>{n.push(t(s,r,e))}),n},Ma=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},lo=(e,t)=>{e.doc??K();const n=Zn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new re(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ln(new Uint8Array(h))),r.integrate(e,0);break;case oe:r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new cn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new R(C(o,B(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new bt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},co=()=>wt("Length exceeded!"),ao=(e,t,n,s)=>{if(n>t._length)throw co();if(n===0)return t._searchMarker&&Ze(t._searchMarker,n,s.length),Mn(e,t,null,s);const r=n,i=Zn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Mn(e,t,r,n)},ho=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Zn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw co();t._searchMarker&&Ze(t._searchMarker,r,-i+s)},vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},rr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new re([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new re([s]);break;case Uint8Array:l=new ln(s);break;case oe:l=new cn(s);break;default:if(s instanceof z)l=new bt(s);else throw new Error("Unexpected content type")}new R(C(o,B(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},ir=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},uo=e=>{const t={};return e.doc??K(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},fo=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted},Na=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&fe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},kn=e=>(e.doc??K(),Xc(e._map.entries(),t=>!t[1].deleted));class $a extends Qn{}class ke extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new ke;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ke}clone(){const t=new ke;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._length}_callObserver(t,n){super._callObserver(t,n),ts(this,t,new $a(this,t))}insert(t,n){this.doc!==null?O(this.doc,s=>{ao(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?O(this.doc,n=>{va(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?O(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return lo(this,t)}toArray(){return io(this)}slice(t=0,n=this.length){return ro(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return oo(this,t)}forEach(t){tn(this,t)}[Symbol.iterator](){return Ma(this)}_write(t){t.writeTypeRef(ch)}}const Fa=e=>new ke;class Ba extends Qn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ae extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ae}clone(){const t=new Ae;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ts(this,t,new Ba(this,t,n))}toJSON(){this.doc??K();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...kn(this)].length}keys(){return gs(kn(this),t=>t[0])}values(){return gs(kn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return gs(kn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??K(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return ir(this,t)}has(t){return fo(this,t)}clear(){this.doc!==null?O(this.doc,t=>{this.forEach(function(n,s,r){vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ah)}}const Va=e=>new Ae,Ft=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Nl(e,t);class xs{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&st(),this.right.content.constructor===J?this.right.deleted||Ue(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Yr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===J?t.right.deleted||Ue(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Zn(t,n):null;if(i){const o=new xs(i.p.left,i.p,i.index,r);return Yr(e,o,n-i.index)}else{const o=new xs(null,t._start,0,r);return Yr(e,o,n)}},go=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===J&&Ft(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new R(C(i,B(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new J(l,o));u.integrate(e,0),n.right=u,n.forward()})},Ue=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},po=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===J&&Ft(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},wo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Ft(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new R(C(i,B(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new J(l,c)),n.right.integrate(e,0),n.forward()}}return o},ps=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;po(n,r);const l=wo(e,t,n,r),c=s.constructor===String?new yt(s):s instanceof z?new bt(s):new le(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Ze(t._searchMarker,n.index,c.getLength()),u=new R(C(o,B(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),go(e,t,n,l)},zr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;po(n,r);const l=wo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===J));){if(!n.right.deleted)switch(n.right.content.constructor){case J:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Ft(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new R(C(o,B(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new yt(c)),n.right.integrate(e,0),n.forward()}go(e,t,n,l)},mo=(e,t,n,s,r)=>{let i=t;const o=tt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===J){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===J){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Ue(r,a)}}t=t.right}return l},ja=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===J){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ha=e=>{let t=0;return O(e.doc,n=>{let s=e._start,r=e._start,i=tt();const o=Ss(i);for(;r;)r.deleted===!1&&(r.content.constructor===J?Ue(o,r.content):(t+=mo(n,s,r,i,o),i=Ss(o),s=r)),r=r.right}),t},Ja=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&Zi(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===J&&o.constructor!==ot&&t.add(o.parent)})}O(n,s=>{Ce(e,e.deleteSet,r=>{if(r instanceof ot||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===J?t.add(i):ja(s,r)});for(const r of t)Ha(r)})},Gr=(e,t,n)=>{const s=n,r=Ss(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case bt:case le:case yt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];O(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},vl(c)||(f.attributes=Ol({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case bt:case le:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case yt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case J:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Ft(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Ft(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Ft(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Ft(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),Ue(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ie extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??K(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ie}clone(){const t=new Ie;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Pa(this,t,n);ts(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??K();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===yt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?O(this.doc,s=>{const r=new xs(null,this._start,0,new Map);for(let i=0;i0)&&ps(s,this,r,l,o.attributes||{})}else o.retain!==void 0?zr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Gr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??K();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(fe(c,t)||n!==void 0&&fe(c,n))switch(c.content.constructor){case yt:{const h=i.get("ychange");t!==void 0&&!fe(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!fe(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case bt:case le:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case J:fe(c,t)&&(a(),Ue(i,c.content));break}c=c.right}a()};return t||n?O(o,h=>{t&&Is(h,t),n&&Is(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ps(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!s);ps(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?O(s,r=>{Gr(r,Sn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?O(r,i=>{const o=Sn(i,this,t,!1);o.right!==null&&zr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return ir(this,t)}getAttributes(){return uo(this)}_write(t){t.writeTypeRef(hh)}}const Wa=e=>new Ie;class ws{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??K()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Te||n.constructor===se)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class se extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new se}clone(){const t=new se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new ws(this,t)}querySelector(t){t=t.toUpperCase();const s=new ws(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Lt(new ws(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ts(this,t,new Ga(this,n,t))}toString(){return oo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),tn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?O(this.doc,s=>{ao(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)O(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Mn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw wt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?O(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return io(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return lo(this,t)}slice(t=0,n=this.length){return ro(this,t,n)}forEach(t){tn(this,t)}_write(t){t.writeTypeRef(fh)}}const Ya=e=>new se;class Te extends se{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Te(this.nodeName)}clone(){const t=new Te(this.nodeName),n=this.getAttributes();return Ul(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?O(this.doc,n=>{vn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?O(this.doc,s=>{rr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return ir(this,t)}hasAttribute(t){return fo(this,t)}getAttributes(t){return t?Na(this,t):uo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return tn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(uh),t.writeKey(this.nodeName)}}const za=e=>new Te(e.readKey());class Ga extends Qn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Nn extends Ae{constructor(t){super(),this.hookName=t}_copy(){return new Nn(this.hookName)}clone(){const t=new Nn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(dh),t.writeKey(this.hookName)}}const qa=e=>new Nn(e.readKey());class $n extends Ie{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new $n}clone(){const t=new $n;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(gh)}}const Xa=e=>new $n;class or{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ut()}mergeWith(t){return!1}write(t,n,s){throw ut()}integrate(t,n){throw ut()}}const Ka=0;class ot extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Qi(t.doc.store,this)}write(t,n){t.writeInfo(Ka),t.writeLen(this.length-n)}getMissing(t,n){return null}}class ln{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ln(this.content)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Qa=e=>new ln(e.readBuf());class en{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new en(this.len)}splice(t){const n=new en(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Qe(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Za=e=>new en(e.readLen()),yo=(e,t)=>new oe({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class cn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new cn(yo(this.doc.guid,this.opts))}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const th=e=>new cn(yo(e.readString(),e.readAny()));class le{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new le(this.embed)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const eh=e=>new le(e.readJSON());class J{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new J(this.key,this.value)}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const nh=e=>new J(e.readKey(),e.readJSON());class Fn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Fn(this.arr)}splice(t){const n=new Fn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const oh=e=>new yt(e.readString()),lh=[Fa,Va,Wa,za,Ya,qa,Xa],ch=0,ah=1,hh=2,uh=3,fh=4,dh=5,gh=6;class bt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new bt(this.type._copy())}splice(t){throw ut()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const ph=e=>new bt(lh[e.readTypeRef()](e)),Ls=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ye(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof R);return{item:r,diff:s}},lr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Bn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new R(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},qr=(e,t)=>Ms(e,n=>rn(n.deletions,t)),ko=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Z(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||ko(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Z(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||rn(s,h.right.id)||qr(i.undoStack,h.right.id)||qr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Z(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=B(l,c),y=C(c,p),S=new R(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,lr(S,!0),S.integrate(e,0),S};class R extends or{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Cr:0}set marker(t){(this.info&as)>0!==t&&(this.info^=as)}get marker(){return(this.info&as)>0}get keep(){return(this.info&Er)>0}set keep(t){this.keep!==t&&(this.info^=Er)}get countable(){return(this.info&Cr)>0}get deleted(){return(this.info&cs)>0}set deleted(t){this.deleted!==t&&(this.info^=cs)}markDeleted(){this.info|=cs}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=B(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=B(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===me&&this.id.client!==this.parent.client&&this.parent.clock>=B(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Vr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Z(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ot||this.right&&this.right.constructor===ot)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===R?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===R&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===me){const s=ye(n,this.parent);s.constructor===ot?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Vr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ge(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Qe(t.deleteSet,this.id.client,this.id.clock,this.length),Hr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw st();this.content.gc(t),n?ka(t,this,new ot(this.id,this.length)):this.content=new en(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Hn|(s===null?0:nt)|(r===null?0:xt)|(i===null?0:Ye);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=qi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===me?(t.writeParentInfo(!1),t.writeLeftID(l)):st();i!==null&&t.writeString(i)}this.content.write(t,n)}}const So=(e,t)=>wh[t&Hn](e),wh=[()=>{st()},Za,sh,Qa,oh,eh,nh,ph,ih,th,()=>{st()}],mh=10;class lt extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){st()}write(t,n){t.writeInfo(mh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},_o="__ $YJS$ __";bo[_o]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");bo[_o]=!0;const Eo=new Map;class yh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Kl(n.newValue||"")}),Tl(this._onChange)}postMessage(t){li.setItem(this.room,Xl(Wl(t)))}close(){xl(this._onChange)}}const kh=typeof BroadcastChannel>"u"?yh:BroadcastChannel,cr=e=>kt(Eo,e,()=>{const t=jt(),n=new kh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Sh=(e,t)=>(cr(e).subs.add(t),t),bh=(e,t)=>{const n=cr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Eo.delete(e)),s},de=(e,t,n=null)=>{const s=cr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Co=0,ar=1,Do=2,Os=(e,t)=>{_(e,Co);const n=ua(t);F(e,n)},Ao=(e,t,n)=>{_(e,ar),F(e,Wi(t,n))},_h=(e,t,n)=>Ao(t,n,q(e)),Io=(e,t,n,s)=>{try{Pi(t,q(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Eh=(e,t)=>{_(e,Do),F(e,t)},Ch=Io,Dh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Co:_h(e,t,n);break;case ar:Io(e,n,s,r);break;case Do:Ch(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ah=0,Ih=(e,t,n)=>{E(e)===Ah&&n(t,Bt(e))},ms=3e4;class To extends Go{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Ht();this.getLocalState()!==null&&ms/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&ms<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&hr(this,s,"timeout")},ft(ms/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Ht()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),pe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const hr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},We=(e,t,n=e.states)=>{const s=t.length,r=X();_(r,s);for(let i=0;i{const s=Pt(t),r=Ht(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},xh=e=>Ml(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Qt=0,xo=3,Se=1,Lh=2,an=[];an[Qt]=(e,t,n,s,r)=>{_(e,Qt);const i=Dh(t,e,n.doc,n);s&&i===ar&&!n.synced&&(n.synced=!0)};an[xo]=(e,t,n,s,r)=>{_(e,Se),F(e,We(n.awareness,Array.from(n.awareness.getStates().keys())))};an[Se]=(e,t,n,s,r)=>{Th(n.awareness,q(t),n)};an[Lh]=(e,t,n,s,r)=>{Ih(t,n.doc,(i,o)=>Oh(n,o))};const Xr=3e4,Oh=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),Lo=(e,t,n)=>{const s=Pt(t),r=X(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Rh=e=>!(e.code>=4400&&e.code<4500),Rs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,hr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Oo,Ns(qo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Oo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Ht();const s=Lo(e,new Uint8Array(n.data),!0);$s(s)>1&&t.send(v(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Rs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Ht(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=X();if(_(n,Qt),Os(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){const s=X();_(s,Se),F(s,We(e.awareness,[e.doc.clientID])),t.send(v(s))}},e.emit("status",[{status:"connecting"}])}},ys=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&de(e.bcChannel,t,e)};class Uh extends vs{constructor(t,n,s,{connect:r=!0,awareness:i=new To(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Rh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=an.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=X();_(f,Qt),Os(f,s),this.ws.send(v(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=Lo(this,new Uint8Array(f),!1);$s(y)>1&&de(this.bcChannel,v(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=X();_(y,Qt),Eh(y,f),ys(this,v(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},S)=>{const w=f.concat(p).concat(y),b=X();_(b,Se),F(b,We(i,w)),ys(this,v(b))},this._exitHandler=()=>{hr(this.awareness,[s.clientID],"app closed")},Jt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Xr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=ma(da(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Uh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},vh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Wi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Kr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,L=new Int32Array(2*w+1);for(let x=-w;x<=w;x+=2){let I;w===0?I=0:x===-w||x!==w&&b[x-1+w-1]=r&&U>=i){u=w;break}}a.push(L)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],L=d-f,x=L===-w||L!==w&&b[L-1+w-1]N&&f>ct;)d--,f--,h.push(d,f);d=I,f=U}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],L=h[w+1];(b>y||L>S)&&p.push({aS:n+y,aE:n+b,bS:n+S,bE:n+L}),y=b+1,S=L+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` -`)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Vh(e,t)<=0?e+t:t+e:null}function jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=gt(e,s),l=gt(t,s),c=gt(n,s),a=pt(o,i),u=[...xe(a,pt(l,i)).map(S=>({h:S,toks:l,side:0})),...xe(a,pt(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,b)=>S.slice(w,b).join(""),d=(S,w,b,L)=>{let x="",I=b;for(const U of S)U.side===w&&(x+=h(o,I,U.h.aS)+h(U.toks,U.h.bS,U.h.bE),I=U.h.aE);return x+h(o,I,L)};let f="",p=0,y=0;for(;yN.side)).size===1){f+=d(S,S[0].side,w,b);continue}const x=d(S,0,w,b),I=d(S,1,w,b);if(x===I){f+=x;continue}if(w===b){const N=jh(x,I,s!==ks,o.length===0);if(N===null){if(!r)return null;f+=I;continue}f+=N;continue}if(s===ks)return null;const U=s===Vn?jn(h(o,w,b),x,I,ks):jn(h(o,w,b),x,I,s+1,r);if(U===null){if(!r)return null;f+=I;continue}f+=U}return f+h(o,p,o.length)}const Zt=e=>e===""||e.endsWith(` -`)?e:e+` -`;function Ro(e,t,n,s){let r=t.endsWith(` -`);return r===e.endsWith(` -`)&&(r=n.endsWith(` -`)),s===""||r===s.endsWith(` -`)?s:r?s+` -`:s.slice(0,-1)}function he(e,t,n){const s=jn(Zt(e),Zt(t),Zt(n),Vt);return s===null?{ok:!1}:{ok:!0,text:Ro(e,t,n,s)}}function Zh(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=jn(Zt(e),Zt(t),Zt(n),Vt,!0)??Zt(n);return Ro(e,t,n,s)}function Qr(e,t){if(e===t)return[];const n=[],s=new Map,r=gt(e,Vt),i=gt(t,Vt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;L>=55296&&L<=56319&&w--;const x=b>0?p.charCodeAt(p.length-b):0;x>=56320&&x<=57343&&b--,S+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:S,deleteCount:p.length,insertText:y}),a=d,u=f}}function bn(e,t,n){const s=new Map,r=pt(gt(t,Vt),s),i=xe(pt(gt(e,Vt),s),r),o=xe(r,pt(gt(n,Vt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function _n(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const Zr=700,ue=[2e3,4e3,8e3,15e3],ti=2e3,Jh=4,Ph=32e3,Wh=32;function tu(e){let t=e.seed,n=e.baseSha;const s=(g,k)=>{t=g,r=k,Dt(k);const m=Rt.lastIndexOf(g);m>=0?Rt.splice(0,m+1):Rt.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(g,k=_t)=>{const m=i(k);return r&&r===n&&t.length>Ph?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,S=!1,w=null,b=null,L="",x=0;const I=(g=Date.now())=>{const k=Math.max(g,x+1e3);return x=k,Ho(e.path,e.who||"browser",new Date(k))},U=new Map;let N=0,ct=!1,rt=null,Wt=0,es=!1,_t=null,Yt=!1;const Rt=[],ur=g=>{Rt.at(-1)!==g&&(Rt.push(g),Rt.length>Wh&&Rt.shift())};let Et=!1,Me=null,zt=0;const ve=()=>{Et=!1,Me=null},ns=g=>{zt===g&&ve()};let et=0,at=0,hn=null,Gt=null,ss=!1,Ct=null,Ne=!1,qt=null,it=null;const M=g=>e.onState?.(g),$e=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ut=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let un=null,rs=0;const Fe=()=>{clearTimeout(un??void 0),un=null},fn=g=>{if(!(g instanceof ht?g.status>=500||g.status===429:!0)||h||a)return;Fe();const m=ue[Math.min(rs,ue.length-1)];rs++,un=setTimeout(()=>{un=null,!h&&!a&&Be()},m)},fr=()=>{Fe(),rs=0},dn=()=>{Fe(),qt&&clearTimeout(qt),qt=setTimeout(()=>{Be()},Zr)},Xt=g=>{if(h)return f=g,!0;const k=V();if(k===g)return!0;const m=Qr(k,g);if(mr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Be=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():je();if(Gt)return ss=!0,Gt;const g=(async()=>{try{await Uo()}finally{Gt=null}})();return Gt=g,g},Uo=async()=>{let g=0;for(;;){if(ss=!1,P||a||S)return;const k=V();if(k===t&&!Yt){M("clean");return}if(M("saving"),e.onWriting?.(),ct){if(w!==null&&b===k){if(await gn(k,L)==="stop")return;continue}ct=!1}const m=l||c?await Mo(k):await No(k);if(m==="stop")return;if(m==="rebased"){if(++g>Jh){await gn(V(),n??"");return}continue}if(!ss){M(V()===t&&!Yt?"clean":"dirty");return}}};let Mt=!1;const Mo=async g=>{Ct=g,Ne=!1;let k;try{k=await Je($e(e.path),g,n,Mt)}catch(m){return Ct=null,m instanceof ht&&m.status===422&&_n(m)?(Mt=!1,Ve(g),"stop"):m instanceof ht&&m.status===409?await dr(t,!1)?"rebased":"stop":(M("error"),fn(m),"stop")}return Ct=null,Mt=!1,fr(),k.merged?await dr(g,!0)?"rebased":"stop":(Ne||s(g,k.sha),e.onSaved?.(g),"done")},dr=async(g,k)=>{let m;try{m=await br(_r(e.apiBase,e.path))}catch(H){return M("error"),V()!==t&&fn(H),!1}if(m.kind!=="text")return M("error"),!1;const A=V(),D=he(g,m.text,A);return!D.ok||!Xt(D.text)?(k&&Dt(m.sha),await gn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},vo=g=>{if(g.update&&T.applyRemoteUpdate(g.update),typeof g.text!="string"){_t=null;return}let k=null;for(let m=_t;m!==null;m=m.prev)if(m.sent!==m.from&&bn(m.from,m.sent,g.text)){k=m;break}if(_t=null,k){Yt=!0;const m=he(k.sent,g.text,V());m.ok&&Xt(m.text)?(t=g.text,r=void 0,Dt(g.sha)):(t=k.sent,r=void 0)}},No=async g=>{Ct=g,Ne=!1;let k;const m=_t;try{_t={sent:g,from:t,prev:m},k=await Nt(Ut,{...o(g,m),...Mt?{confirm_shrink:!0}:{}})}catch(D){if(Ct=null,D instanceof ht&&[400,401,403,404,405,409,413].includes(D.status)&&(_t=m),D instanceof ht&&(D.status===404||D.status===405))return c=!0,"rebased";if(D instanceof ht&&D.status===422&&_n(D))return Mt=!1,Ve(g),"stop";if(D instanceof ht&&D.status===409&&!a){let H={};try{H=JSON.parse(D.body)}catch{}const $=typeof H.text=="string"?H.text:null;if($!==null){const W=he(t,$,V());if(W.ok&&Xt(W.text))return t=$,r=void 0,Dt(H.sha),"rebased"}return gn(V(),H.sha??"")}return M(a?"dirty":"error"),fn(D),"stop"}if(Ct=null,Mt=!1,fr(),k.update&&T.applyRemoteUpdate(k.update),_t=null,Yt=!1,a)return"stop";const A=he(g,k.text,V());return A.ok&&Xt(A.text)&&(Ne||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let P=null;const Ve=g=>{P||h||!e.onShrinkRefused||(M("error"),P={was:mn(t),now:mn(g),confirm:async()=>{if(!h){if(a){M("saving"),e.onWriting?.();const k=et,m=zt;try{const A=await Nt(Ut,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),is(k,m);const D=!Et&&at>=et;M(D?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&at{if(!h)try{const k=await br(_r(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Xt(k.text),P=null,a&&!u){if(await ce(!1),h)return;M(at>=et&&!Et?"clean":"dirty");return}at=et,d&&(d=0,e.onPending?.(0)),ve(),M("clean")}catch{M("error")}finally{P=null}}},e.onShrinkRefused(P))};let vt=null;const $o=()=>{vt&&clearTimeout(vt),vt=setTimeout(()=>{const g=V();Jo(mn(t),mn(g))&&Ve(g)},Zr)},gr=async(g,k,m=I())=>{const A=++N;U.set(m,g);try{return await Je($e(m),g),A===N&&!a&&(t=g,r=void 0,k&&(n=k),M("clean")),e.onConflictCopy?.(m),null}catch(D){return A===N&&!a&&M("error"),{err:D}}finally{U.get(m)===g&&U.delete(m)}},gn=async(g,k)=>{(w===null||b!==g)&&(w=I(),b=g);const m=w;L=k,ct=!0;const A=await gr(g,k,m);return h?"stop":A?(fn(A.err),"stop"):(ct=!1,w===m&&(w=null,b=null,L=""),V()!==g?"rebased":"stop")},is=(g,k)=>{at=Math.max(at,g),ns(k),!(h||u)&&(d=et-at,e.onPending?.(d))},Fo=()=>{h||u||P||it||(it=setTimeout(()=>{it=null,!u&&!h&&ce(!1)},ti))},ce=g=>{if(clearTimeout(it??void 0),it=null,g){if(at>=et)return Promise.resolve();const m=et,A=zt;return Nt(Ut,{update:T.encodeState(),base:n},!0).then(D=>{Dt(D.sha),is(m,A)})}if(hn)return hn;const k=(async()=>{try{for(;!u&&!h&&!P&&at{p=!1,w=null,b=null,Wt=0,clearTimeout(rt??void 0),rt=null,Yt=!1,a=!0,ur(T.text.toString()),g?.(),es&&(es=!1,e.onReady(T))},je=async()=>{if(h||a||y||S)return;if(clearTimeout(rt??void 0),rt=null,qt&&clearTimeout(qt),qt=null,Gt){S=!0;try{for(;Gt;)await Gt}finally{S=!1}if(h||a)return;if(!u){V()!==t&&dn();return}}if(_t!==null&&!c){let $;S=!0;try{$=await Nt(Ut,{peek:!0})}catch{if(h||a)return;const W=ue[Math.min(Wt,ue.length-1)];Wt++,rt=setTimeout(()=>{rt=null,je()},W);return}finally{S=!1}if(h||a)return;if(vo($),!u){(V()!==t||Yt)&&dn();return}}const g=e.soloText?.();if(g===void 0||g===t)return os();const k=T.text.toString(),m=he(t,k,g);if(m.ok)return os(()=>T.applySplices(Qr(k,m.text)));p=!0,(w===null||b!==g)&&(w=I(),b=g),y=!0;let A;try{A=await gr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,je()):os(()=>{t=T.text.toString()});const D=A.err;if(D instanceof ht&&!(D.status>=500||D.status===429))return;const H=ue[Math.min(Wt,ue.length-1)];Wt++,rt=setTimeout(()=>{rt=null,je()},H)},T=new Mh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(it&&clearTimeout(it),it=null,Fe(),a||je(),at=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(T):es=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),pr=(g,k)=>{const m=a?T.text.toString():null;if(m!==null&&ur(m),!T.isRemote(k?.origin)){if(M("dirty"),a){Et=!0,Me=m,zt+=1,u||(et+=1,d=et-at,e.onPending?.(d),clearTimeout(it??void 0),it=setTimeout(()=>{it=null,!u&&!h&&ce(!1)},ti)),$o();return}dn()}};T.text.observe(pr);const wr=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",wr),Nh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const V=()=>f!==null?f:mr()?T.text.toString():e.soloText?.()??"",mr=()=>a||l&&T.text.length>0,Dt=g=>{g&&(n=g)},Bo=(g,k,m)=>{if(m?.held)return s(g,k),"same";if(g===t||g===Ct)return Dt(k),"same";const A=V();if(g===A)return s(g,k),a&&(ve(),M("clean")),"same";if(a){const H=t;return Rt.includes(g)||bn(H,g,A)?(s(g,k),Et&&(Me===null||g===Me||bn(H,Me,g))&&(ve(),M("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(g,k),Xt(g),ve(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const D=he(t,g,A);return D.ok?(Ct!==null&&(Ne=!0),s(g,k),Xt(D.text),D.text!==g?dn():Ct===null&&M("clean"),D.text===A?"same":"merged"):"blocked"};let pn=null;const Vo=()=>{if(!a)return Be();if(P||h)return Promise.resolve();if(!u)return d>0?ce(!1):Promise.resolve();if(!Et)return Promise.resolve();if(pn)return pn;const g=zt;M("saving");const k=(async()=>{try{const m=await Nt(Ut,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),ns(g),M(Et?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof ht&&m.status===422&&_n(m)&&(clearTimeout(vt??void 0),vt=null,Ve(V()),P))return;M(Et?"dirty":"clean")}finally{pn=null}})();return pn=k,k};let At=null;const wn=g=>()=>{At===g&&(At=null)},yr=(g,k)=>{if(P)return;if(a){const $=!u&&d>0;if(!$&&!(u&&Et))return;const W="room\0"+T.text.toString();if(At===W)return;At=W;const It=zt;($?ce(!0):Nt(Ut,{update:T.encodeState()},!0).then(Kt=>Dt(Kt.sha))).then(()=>ns(It),wn(W));return}if(p||ct){const $="park\0"+g;if(At===$)return;At=$;let W=w!==null&&b===g?w:null;for(const[It,He]of U)W===null&&He===g&&(W=It);W??=I(),Je($e(W),g,void 0,!1,!0).catch(wn($));return}if(!g||g===t)return;const m="text\0"+g;if(At===m)return;if((l||c)&&!k){Be();return}At=m;const A=t,D=$=>{if(!($ instanceof ht&&$.status===409))return wn(m)();let W={};try{const Kt=JSON.parse($.body);Kt&&typeof Kt=="object"&&(W=Kt)}catch{}if(typeof W.text=="string"&&(W.text===g||bn(A,g,W.text)))return;ct=!0;let It=w!==null&&b===g?w:null;for(const[Kt,jo]of U)It===null&&jo===g&&(It=Kt);It??=I(),w=It,b=g;const He=It;Je($e(He),g,void 0,!1,!0).then(()=>{ct=!1,e.onConflictCopy?.(He)},wn(m))},H=$=>{$.parked&&e.onConflictCopy?.($.parked)};l||c?Je($e(e.path),g,n,Mt,!0,!0).then(H,D):Nt(Ut,{...o(g),park_on_conflict:!0},!0).then(H,D)},kr=()=>{h||yr(V(),!0)},Sr=()=>{At=null};return typeof window<"u"&&(window.addEventListener("pagehide",kr),window.addEventListener("pageshow",Sr)),{collab:T,current:V,merge:Bo,rebase:Dt,saveNow:Vo,askingShrink:()=>P!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",kr),window.removeEventListener("pageshow",Sr)),clearTimeout(qt??void 0),clearTimeout(vt??void 0),Fe(),clearTimeout(rt??void 0),rt=null;const g=V();h=!0,f=g,P?e.onShrinkWithdrawn?.(P):yr(g,!1),clearTimeout(it??void 0),T.awareness.off("change",wr),T.text.unobserve(pr),T.destroy()}}}export{oe as D,Zr as S,Qh as U,Xh as a,da as b,ma as c,Qr as d,Kh as e,Ns as f,ie as g,zh as h,Tt as i,Zh as m,tu as o,qh as r,Gh as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 8fd45982..3b198090 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + diff --git a/internal/webapp/upload.go b/internal/webapp/upload.go index cb4f5721..039b0164 100644 --- a/internal/webapp/upload.go +++ b/internal/webapp/upload.go @@ -775,6 +775,16 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R createOnly := base == "" && r.Header.Get("If-None-Match") == "*" if createOnly { if head, ok := s.headBlob(r.Context(), v, p); ok && head != blob { + // A retry of a create whose answer was lost finds its own bytes: + // nothing to refuse. A directory never names a version by its + // content, so the bytes are what is compared. + if s.holdsBytes(r.Context(), v, p, blob, size) { + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "unchanged": true}) + return + } + if s.stepConflictCopy(w, r, v, up, p, tmp, size, blob, -1) { + return + } writeJSONStatus(w, http.StatusConflict, map[string]any{ "error": "this file already exists", "sha": head, "path": p, }) @@ -924,7 +934,11 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R } } // Quota already passed for these bytes above. - if !createOnly && s.parkStaleUpload(w, r, v, up, p, head, tmp, size, blob, billed) { + if createOnly { + if s.stepConflictCopy(w, r, v, up, p, tmp, size, blob, billed) { + return + } + } else if s.parkStaleUpload(w, r, v, up, p, head, tmp, size, blob, billed) { return } writeJSONStatus(w, http.StatusConflict, map[string]any{ @@ -966,14 +980,53 @@ func (s *Server) handleUploadContent(v *volume, w http.ResponseWriter, r *http.R // for it (parkOnConflictHeader). handled says a response was written: ok // naming the copy, or the refusal that kept it from being stored. billed is // what quota already admitted for these bytes, or -1 when nobody asked yet. -// -// A copy is named to the second, and two tabs of one account can close in -// the same one: each name is created only if it is free (createAbsent), and a -// taken one moves the copy a second on, so neither replaces the other. func (s *Server) parkStaleUpload(w http.ResponseWriter, r *http.Request, v *volume, up Uploader, p, head string, tmp *os.File, size int64, blob string, billed int64) (handled bool) { if r.Header.Get(parkOnConflictHeader) == "" || size == 0 { return false } + who := s.requestUser(r) + t0 := time.Now() + parked, ok := s.storeConflictCopy(w, r, v, up, func(i int) string { + return conflictPath(p, who, t0.Add(time.Duration(i)*time.Second)) + }, tmp, size, blob, billed) + if ok { + writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "parked": parked}) + } + return true +} + +// stepConflictCopy is a create-only write of a conflict copy whose name is +// taken (p, If-None-Match: *), asked to park anyway (parkOnConflictHeader): +// a closing tab's flush of a copy it already named, which cannot answer a +// 409 by naming the next one itself. The copy moves a second on at a time, +// as the hub's own copies do. handled says a response was written. +func (s *Server) stepConflictCopy(w http.ResponseWriter, r *http.Request, v *volume, up Uploader, p string, tmp *os.File, size int64, blob string, billed int64) (handled bool) { + if r.Header.Get(parkOnConflictHeader) == "" || size == 0 { + return false + } + if _, ok := shiftConflictName(p, 0); !ok { + return false // not a conflict copy's name: nothing to move + } + parked, ok := s.storeConflictCopy(w, r, v, up, func(i int) string { + next, _ := shiftConflictName(p, i+1) + return next + }, tmp, size, blob, billed) + if ok { + sha, found := s.headBlob(r.Context(), v, parked) + if !found { + sha = blob + } + writeJSON(w, map[string]any{"ok": true, "path": parked, "sha": sha, "parked": parked}) + } + return true +} + +// storeConflictCopy stores tmp under the first of name(0), name(1), … that is +// free or already holds these bytes, up to maxConflictNameTries, and reports +// it. ok false means a refusal was written instead: quota, a folder rule, +// storage, or no free name. billed is what quota already admitted for these +// bytes, or -1 when nobody asked yet. +func (s *Server) storeConflictCopy(w http.ResponseWriter, r *http.Request, v *volume, up Uploader, name func(int) string, tmp *os.File, size int64, blob string, billed int64) (parked string, ok bool) { who := s.requestUser(r) ctx := r.Context() project := projectID(r) @@ -984,23 +1037,21 @@ func (s *Server) parkStaleUpload(w http.ResponseWriter, r *http.Request, v *volu var err error if billed, err = billableBytes(ctx, rs.Backend, "blobs/"+blob, size); err != nil { storageErr(w, http.StatusBadGateway, "could not check the stored object", err) - return true + return "", false } } if err := s.quota().CheckWrite(org, billed+s.reservedBytes(org)); err != nil { http.Error(w, err.Error(), http.StatusForbidden) - return true + return "", false } } - t0 := time.Now() - parked := "" for i := range maxConflictNameTries { - name := conflictPath(p, who, t0.Add(time.Duration(i)*time.Second)) - if !s.writablePath(w, r, name) { - return true + n := name(i) + if !s.writablePath(w, r, n) { + return "", false } - unlock := s.lockPath(project, name) - err := s.createAbsent(ctx, v, up, name, tmp, size, blob, who) + unlock := s.lockPath(project, n) + err := s.createAbsent(ctx, v, up, n, tmp, size, blob, who) unlock() var stale *staleWriteError if errors.As(err, &stale) { @@ -1008,16 +1059,16 @@ func (s *Server) parkStaleUpload(w http.ResponseWriter, r *http.Request, v *volu } if err != nil { http.Error(w, fmt.Sprintf("store: %v", err), http.StatusBadGateway) - return true + return "", false } - parked = name + parked = n break } if parked == "" { writeJSONStatus(w, http.StatusConflict, map[string]any{ - "error": "no free conflict copy name", "sha": head, "path": p, + "error": "no free conflict copy name", "path": name(0), }) - return true + return "", false } if billed > 0 { s.quota().RecordUsage(org, billed) @@ -1026,8 +1077,33 @@ func (s *Server) parkStaleUpload(w http.ResponseWriter, r *http.Request, v *volu s.dataWrote(ctx, project) s.captureChange(r, "browser", 1, 0) s.publishChange(r, "browser", []string{parked}, 1, 0) - writeJSON(w, map[string]any{"ok": true, "path": p, "sha": head, "parked": parked}) - return true + return parked, true +} + +// holdsBytes reports whether p already holds exactly blob's bytes. Read back +// only where the version name is not the content hash (a directory), and only +// when the sizes agree. +func (s *Server) holdsBytes(ctx context.Context, v *volume, p, blob string, size int64) bool { + fi, ok := s.headFile(ctx, v, p) + if !ok || fi.Size != size { + return false + } + if fi.Blob == blob { + return true + } + if _, journaled := v.source.(*RemoteSource); journaled { + return false + } + rc, err := v.source.Open(ctx, p, fi) + if err != nil { + return false + } + defer rc.Close() + h := sha256.New() + if _, err := io.Copy(h, rc); err != nil { + return false + } + return hex.EncodeToString(h.Sum(nil)) == blob } // maxConflictNameTries bounds how many seconds past now a conflict copy's @@ -1050,9 +1126,12 @@ func (s *Server) createAbsent(ctx context.Context, v *volume, up Uploader, p str } return rs.commitIfBase(ctx, p, blob, size, who, "", &commitBase{path: p, mustBeAbsent: true, blob: blob}) } - // A directory names a version by mtime and size, never content, so any - // file already there is taken. + // A directory names a version by mtime and size, never content: a file + // already there is taken unless it holds these very bytes (a retry). if head, ok := s.headBlob(ctx, v, p); ok { + if s.holdsBytes(ctx, v, p, blob, size) { + return nil + } return &staleWriteError{head: head} } return up.Upload(ctx, p, tmp, size, who, "") diff --git a/internal/webapp/upload_landed_test.go b/internal/webapp/upload_landed_test.go index 1c02dbc9..24ec6ef6 100644 --- a/internal/webapp/upload_landed_test.go +++ b/internal/webapp/upload_landed_test.go @@ -345,3 +345,95 @@ func TestUploadParkOnConflictAcrossProcessesNeverReplacesACopy(t *testing.T) { } } } + +/* +A conflict copy the browser names itself is created with If-None-Match: *, so +a second tab's copy under the same second can never replace the first's. + + - A retry of a create whose answer was lost finds its own bytes and is ok, + unchanged: no second copy. + - Different bytes under a taken name are a 409, so a live tab names the + next copy itself. + - A closing tab cannot, so with X-Bdrive-Park-On-Conflict the hub moves the + copy a second on — and a retry of that finds its own bytes there too. + +Both on hub storage, where the version is the content hash, and on a plain +directory, where it is not and the bytes themselves are compared. +*/ +func TestUploadCreateOnlyConflictCopyIsIdempotentAndSteps(t *testing.T) { + name := conflictPath("notes.md", User{Name: "Tab"}, time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)) + next, ok := shiftConflictName(name, 1) + if !ok || conflictStamp(t, "notes.md", next).Sub(conflictStamp(t, "notes.md", name)) != time.Second { + t.Fatalf("shift %s by 1s = %s", name, next) + } + const tab1, tab2 = "tab one's text\n", "tab two's text\n" + + run := func(t *testing.T, h http.Handler, prefix string) { + create := func(body string, park bool) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + r := httptest.NewRequest("PUT", prefix+"upload/content?path="+name, strings.NewReader(body)) + r.Header.Set("If-None-Match", "*") + if park { + r.Header.Set(parkOnConflictHeader, "1") + } + h.ServeHTTP(rec, r) + return rec + } + read := func(p string) string { return get(t, h, prefix+"file?path="+p).Body.String() } + type answer struct { + Path string `json:"path"` + Unchanged bool `json:"unchanged"` + Parked string `json:"parked"` + } + decode := func(rec *httptest.ResponseRecorder) answer { + t.Helper() + var out answer + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("%s: %v", rec.Body, err) + } + return out + } + + if rec := create(tab1, false); rec.Code != http.StatusOK { + t.Fatalf("create: %d %s", rec.Code, rec.Body) + } + rec := create(tab1, false) + if rec.Code != http.StatusOK || !decode(rec).Unchanged { + t.Fatalf("retried create: %d %s, want ok unchanged", rec.Code, rec.Body) + } + if rec := create(tab2, false); rec.Code != http.StatusConflict { + t.Fatalf("another tab's create under a taken name: %d %s, want 409", rec.Code, rec.Body) + } + if got := read(name); got != tab1 { + t.Fatalf("%s = %q after a refused create, want %q", name, got, tab1) + } + for attempt := range 2 { // the second is a retry whose answer was lost + rec := create(tab2, true) + if rec.Code != http.StatusOK { + t.Fatalf("parked create (attempt %d): %d %s", attempt, rec.Code, rec.Body) + } + if out := decode(rec); out.Parked != next || out.Path != next { + t.Fatalf("parked create (attempt %d) answered %s, want parked at %s", attempt, rec.Body, next) + } + } + if got := read(name); got != tab1 { + t.Fatalf("%s = %q, want tab one's %q", name, got, tab1) + } + if got := read(next); got != tab2 { + t.Fatalf("%s = %q, want tab two's %q", next, got, tab2) + } + after, _ := shiftConflictName(name, 2) + if rec := get(t, h, prefix+"file?path="+after); rec.Code != http.StatusNotFound { + t.Fatalf("%s exists (%d): a retry parked a second copy", after, rec.Code) + } + } + + t.Run("hub storage", func(t *testing.T) { + srv, p, _ := newHub(t, true, nil) + run(t, srv.Handler(), "/api/p/"+p.ID+"/") + }) + t.Run("directory", func(t *testing.T) { + run(t, writableDirServer(t, nil), "/api/") + }) +} diff --git a/internal/webapp/ycollab.go b/internal/webapp/ycollab.go index c6d8bd48..c4714784 100644 --- a/internal/webapp/ycollab.go +++ b/internal/webapp/ycollab.go @@ -2037,13 +2037,32 @@ var ( // budget: once the room is evicted this text exists nowhere else, so giving // up would be the loss the copy exists to prevent. Held in memory only, so a // hub restart before the store recovers still loses it. +// +// The copy is only ever created, never written over: a name another copy +// already holds (another room, or a closing tab, in the same second) moves it +// a second on. A retry finding its own text under a name it reached before +// is answered unchanged and counts as written. func (s *Server) parkCopy(ctx context.Context, who User, project, path, copy, text string) { try := func(ctx context.Context) bool { - cw := s.putAs(ctx, who, project, copy, text, "") - if cw.code == http.StatusOK { - log.Printf("bdrive: %s: the room's text could not be written to it; parked beside it as %s", path, copy) - s.rooms().parkedOnStorage(project+"/"+path, text) - return true + var cw *memWriter + for i := range maxConflictNameTries { + name, ok := shiftConflictName(copy, i) + if !ok { + if i > 0 { + break + } + name = copy + } + cw = s.putVia(ctx, who, project, name, text, "", true) + if cw.code == http.StatusConflict { + continue + } + if cw.code == http.StatusOK { + log.Printf("bdrive: %s: the room's text could not be written to it; parked beside it as %s", path, name) + s.rooms().parkedOnStorage(project+"/"+path, text) + return true + } + break } log.Printf("bdrive: %s: could not park the room's refused text (%d bytes) as %s (%d); retrying", path, len(text), copy, cw.code) return false @@ -2284,7 +2303,25 @@ func conflictPath(path string, who User, at time.Time) string { } return '-' }, name) - return path + ".bdrive-conflict-" + safe + "-" + at.UTC().Format("20060102T150405Z") + return path + ".bdrive-conflict-" + safe + "-" + at.UTC().Format(conflictStampLayout) +} + +// conflictStampLayout is the second a conflict copy's name ends in. The sync +// engine and the browser parse exactly this form. +const conflictStampLayout = "20060102T150405Z" + +// shiftConflictName is a conflict copy's name moved step seconds on, and +// whether name is one at all. +func shiftConflictName(name string, step int) (string, bool) { + i := strings.LastIndex(name, "-") + if i < 0 || !strings.Contains(name[:i], ".bdrive-conflict-") { + return "", false + } + at, err := time.Parse(conflictStampLayout, name[i+1:]) + if err != nil { + return "", false + } + return name[:i+1] + at.Add(time.Duration(step)*time.Second).UTC().Format(conflictStampLayout), true } // roomRegistry keeps a live room's document addressable, and remembers who may From 6a088a694e76cf0e70be421c7934fb16150ff1b5 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:15:15 +0900 Subject: [PATCH 05/34] fix(webapp): send emptied buffers on exit and adopt bfcache checkpoints --- .../webapp/frontend/src/lib/sharedfile.ts | 117 ++++++++++- .../src/lib/sharedfile_restore.test.ts | 195 ++++++++++++++++++ ...{Editor-Kfw2qBqm.js => Editor-Bf_MRt-m.js} | 2 +- ...dit-C9Fhkd7e.js => VisualEdit-eZmLVOyc.js} | 2 +- .../{index-DTYyCePQ.js => index-ClgB4GHM.js} | 4 +- .../static/assets/sharedfile-C8ckGCkQ.js | 16 ++ .../static/assets/sharedfile-DCDc5SSp.js | 16 -- internal/webapp/static/index.html | 2 +- 8 files changed, 323 insertions(+), 31 deletions(-) rename internal/webapp/static/assets/{Editor-Kfw2qBqm.js => Editor-Bf_MRt-m.js} (99%) rename internal/webapp/static/assets/{VisualEdit-C9Fhkd7e.js => VisualEdit-eZmLVOyc.js} (97%) rename internal/webapp/static/assets/{index-DTYyCePQ.js => index-ClgB4GHM.js} (99%) create mode 100644 internal/webapp/static/assets/sharedfile-C8ckGCkQ.js delete mode 100644 internal/webapp/static/assets/sharedfile-DCDc5SSp.js diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index 8ef4839e..83f25fad 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -333,6 +333,11 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { and the second is a 409 against our own first. */ let saving: Promise | null = null; let dirtyWhileSaving = false; + /* The way-out write (flushExit) on the wire. It runs outside `saving` — + the page may be gone before it lands — but a page that lives on (the + bfcache) must not checkpoint or join past it: a join that peeks before it + reaches the room splices its text in, and then it lands a second copy. */ + let exitSaving: Promise | null = null; // The text on the wire, so its own echo through the change stream (which // routinely beats the response back) is not mistaken for a stranger's. // Cleared the moment the request settles. @@ -414,6 +419,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } const run = (async () => { try { + while (exitSaving) await exitSaving; await saveLoop(); } finally { saving = null; @@ -964,10 +970,12 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { own copy of them arrives after: every checkpointed line twice. So wait for it — the loop sends no further checkpoint meanwhile — and let it hand its items to the document first (sendRoom). */ - if (saving) { + if (saving || exitSaving) { waitingToJoin = true; try { - while (saving) await saving; + // The way-out checkpoint too: a page back from the bfcache joins + // only once it has landed (or failed, and is named for the peek). + while (saving || exitSaving) await (saving ?? exitSaving); } finally { waitingToJoin = false; } @@ -1308,6 +1316,9 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { return; } if (pendingJoin || stagingConflict) { + // A blank buffer is never parked beside a file (the hub agrees: + // upload.go refuses a whitespace-only conflict copy). + if (!text.trim()) return; const key = "park\u0000" + text; if (exitSent === key) return; exitSent = key; @@ -1320,7 +1331,9 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { parkOnExit(copy, text, key); return; } - if (!text || text === saved) return; + // An emptied file is an edit like any other: only "nothing changed" is + // nothing to send. + if (text === saved && !roomNeedsFlush) return; const key = "text\u0000" + text; if (exitSent === key) return; if ((solo || noRoomHttp) && !unloading) { @@ -1329,21 +1342,61 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } exitSent = key; const from = saved; + const staging = !(solo || noRoomHttp); + /* A staging checkpoint is recorded as ambiguous until answered, exactly + as sendRoom records one: a page restored from the bfcache with this + request unsettled (or failed after it reached the room) names it in + `prior_sent`, and a join peeks, so it is never applied twice. */ + const before = ambiguousRoomCheckpoint; + const mine: Ambiguous = { sent: text, from, prev: before }; + if (staging) ambiguousRoomCheckpoint = mine; /* The page is going and will not get to send a second request, so this one asks the hub to park a clash beside the file itself and answers with the copy (`parked`). An older hub refuses 409 instead: if its head already holds our edit there is nothing to keep; otherwise the words are parked from here, as long as the page lives to send it. */ const onExitError = (e: unknown) => { + // Refused before the room was touched: the checkpoint is not ambiguous. + if ( + staging && + e instanceof HttpError && + [400, 401, 403, 404, 405, 409, 413].includes(e.status) && + ambiguousRoomCheckpoint === mine + ) { + ambiguousRoomCheckpoint = before; + } + // A page that lives on (bfcache, or no unload at all) asks the user, + // as a save would have. + if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) { + exitFailed(key)(); + if (!gone) { + clearTimeout(shrinkTimer ?? undefined); + shrinkTimer = null; + askShrink(current()); + } + return; + } if (!(e instanceof HttpError && e.status === 409)) return exitFailed(key)(); - let theirs: { text?: unknown } = {}; + let theirs: { text?: unknown; sha?: unknown } = {}; try { const parsed: unknown = JSON.parse(e.body); if (parsed && typeof parsed === "object") theirs = parsed as typeof theirs; } catch { // an older hub, or a body we cannot read: park } - if (typeof theirs.text === "string" && (theirs.text === text || retainsChanges(from, text, theirs.text))) return; + if (typeof theirs.text === "string" && (theirs.text === text || retainsChanges(from, text, theirs.text))) { + // Already in the hub's text: a page that lives on is built on it now. + if (!gone && !hubHoldsIt) { + const res = merge3(text, theirs.text, current()); + if (res.ok && applyText(res.text)) { + saved = theirs.text; + savedSha = undefined; + if (typeof theirs.sha === "string") rebase(theirs.sha); + } + } + return; + } + if (!text.trim()) return; // a blank buffer is never parked stagingConflict = true; let copy = parkedName !== null && parkedText === text ? parkedName : null; for (const [path, held] of conflictPuts) if (copy === null && held === text) copy = path; @@ -1355,14 +1408,58 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { opts.onConflictCopy?.(path); }); }; - const landed = (out: { parked?: string }) => { - if (out.parked) opts.onConflictCopy?.(out.parked); + /* Answered: what landed is what a page restored from the bfcache builds + on, so its next save diffs against it rather than against `from`. */ + const parkedHere = (parked: string, sha?: string) => { + saved = text; + savedSha = undefined; + rebase(sha); + if (!gone && current() === text) setState("clean"); + opts.onConflictCopy?.(parked); }; - if (solo || noRoomHttp) { - void putText(contentURL(opts.path), text, base, confirmShrinkOnce, true, true).then(landed, onExitError); + let req: Promise; + if (!staging) { + req = putText(contentURL(opts.path), text, base, confirmShrinkOnce, true, true).then((out) => { + confirmShrinkOnce = false; + if (out.parked) return parkedHere(out.parked, out.sha); + if (out.merged) { + // The hub folded it into a newer file: learn what the file is. + if (!gone) void rebaseOnHead(text, true); + else rebase(out.sha); + return; + } + adopt(text, out.sha); + if (!gone && current() === saved) setState("clean"); + opts.onSaved?.(text); + }, onExitError); } else { - void syncCollab(syncURL, { ...roomPayload(text), park_on_conflict: true }, true).then(landed, onExitError); + req = syncCollab(syncURL, { ...roomPayload(text, before), park_on_conflict: true }, true).then((out) => { + confirmShrinkOnce = false; + if (ambiguousRoomCheckpoint === mine) ambiguousRoomCheckpoint = null; + roomNeedsFlush = false; + if (out.parked) return parkedHere(out.parked, out.sha); + if (out.update) collab.applyRemoteUpdate(out.update); + if (gone || hubHoldsIt || typeof out.text !== "string") { + rebase(out.sha); + return; + } + const res = merge3(text, out.text, current()); + if (res.ok && applyText(res.text)) { + adopt(out.text, out.sha); + if (current() === saved) setState("clean"); + } + opts.onSaved?.(out.text); + }, onExitError); } + // Settled either way: what waits on it only needs to know it is over. + const settled: Promise = req.then( + () => {}, + () => {}, + ); + exitSaving = settled; + void settled.then(() => { + if (exitSaving === settled) exitSaving = null; + }); }; const onPageHide = () => { if (!gone) flushExit(current(), true); diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 5e9eecf6..8f237d81 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -1207,6 +1207,201 @@ test("late join conflict park steps past a second another tab already took", asy } }); +/* Emptying a file is an edit: the way out sends "" rather than treating an + empty buffer as nothing to say, in every mode and on both exits. */ +for (const mode of ["staging", "solo"] as const) { + for (const exit of ["pagehide", "destroy"] as const) { + test(`an emptied file is flushed on the way out (${mode}, ${exit})`, async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const connect = mock.method(CollabDoc.prototype, "connect", () => {}); + try { + const reqs: Array<{ method: string; url: string; body: string }> = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const method = init?.method ?? "GET"; + reqs.push({ method, url: decodeURIComponent(String(url)), body: String(init?.body) }); + if (method === "PUT") return new Response(JSON.stringify({ sha: "sha-2" }), { status: 200 }); + return new Response(JSON.stringify({ sha: "sha-2", text: "" }), { status: 200 }); + }) as typeof fetch; + let buffer = "todo\n"; + let solo = false; + const file = openSharedFile({ + apiBase: mode === "solo" ? "/api/" : "/api/p/proj/", + path: "notes.md", + seed: "todo\n", + baseSha: "sha-a", + who: "tester", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + if (mode === "solo") await waitFor(() => assert.equal(solo, true)); + + buffer = ""; + if (exit === "pagehide") window.dispatchEvent(new Event("pagehide")); + else file.destroy(); + await advance(0); + assert.equal(reqs.length, 1); + if (mode === "solo") { + assert.equal(reqs[0].method, "PUT"); + assert.ok(reqs[0].url.includes("upload/content?path=notes.md")); + assert.equal(reqs[0].body, ""); + } else { + assert.equal(reqs[0].method, "POST"); + assert.ok(reqs[0].url.includes("ycollab/sync?path=notes.md")); + const body = JSON.parse(reqs[0].body) as { base_text?: string; text?: string }; + assert.equal(body.text, ""); + assert.equal(body.base_text, "todo\n"); + } + if (exit === "pagehide") { + // Landed: the unmount that follows has nothing left to send. + file.destroy(); + await advance(0); + assert.equal(reqs.length, 1); + } + } finally { + realTimers(); + connect.mock.restore(); + } + }); + } +} + +/* A pagehide flush refused for a sharp shrink, on a page that lives on (the + bfcache, or no unload at all): the user is asked, as a save would ask. */ +test("a pagehide flush refused 422 for a shrink asks the user when the page lives on", async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + try { + const reqs: string[] = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + reqs.push((init?.method ?? "GET") + " " + decodeURIComponent(String(url))); + return new Response(JSON.stringify({ error: "would empty the file", shrink: true }), { status: 422 }); + }) as typeof fetch; + let buffer = "todo\n"; + let solo = false; + const asks: ShrinkAsk[] = []; + const file = openSharedFile({ + apiBase: "/api/", + path: "notes.md", + seed: "todo\n", + baseSha: "sha-a", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onShrinkRefused: (a) => asks.push(a), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + buffer = ""; + window.dispatchEvent(new Event("pagehide")); + await advance(0); + assert.equal(reqs.length, 1); + assert.equal(asks.length, 1); + file.destroy(); + } finally { + realTimers(); + } +}); + +/* A staging pagehide checkpoints "v0\nx\n"; the page is restored from the + bfcache and the user types a second "x". Landed, the next checkpoint is + built on what landed (two x lines at the hub, never three). Failed after + it may have reached the room, the next one names it in prior_sent so the + hub never applies it twice. Still unanswered, the next save waits for it + rather than racing it to the room. */ +for (const answer of ["landed", "502", "unsettled"] as const) { + test(`a bfcache-restored page builds on its pagehide checkpoint (${answer})`, async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const h = stagingConflictHarness(); + try { + h.state.buffer = "v0\nx\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.posts.length, 1); + same(h.posts[0], { base: "sha-0", base_text: "v0\n", text: "v0\nx\n", park_on_conflict: true }); + if (answer === "landed") h.roomAnswers[0].resolve(h.ok({ ok: true, sha: "sha-1", text: "v0\nx\n" })); + if (answer === "502") h.roomAnswers[0].resolve(new Response("bad gateway", { status: 502 })); + await advance(0); + + window.dispatchEvent(new Event("pageshow")); + h.state.buffer = "v0\nx\nx\n"; + void h.file.saveNow(); + await advance(0); + if (answer === "unsettled") { + // Held behind the pagehide request until it settles, here as a 502. + assert.equal(h.posts.length, 1); + h.roomAnswers[0].resolve(new Response("bad gateway", { status: 502 })); + await advance(0); + } + assert.equal(h.posts.length, 2); + if (answer === "landed") { + same(h.posts[1], { base: "sha-1", base_text: "v0\nx\n", text: "v0\nx\nx\n" }); + } else { + same(h.posts[1], { base: "sha-0", base_text: "v0\n", text: "v0\nx\nx\n", prior_sent: ["v0\nx\n"] }); + } + } finally { + realTimers(); + h.connect.mock.restore(); + } + }); +} + +/* Back from the bfcache with the pagehide checkpoint still on the wire, the + socket syncs: the join waits for that checkpoint rather than peeking past + it (a peek that beats it to the room would splice "x" in, and the late + checkpoint would land a second one). It lands, and the line is there once. */ +test("a join after a bfcache restore waits for the in-flight pagehide checkpoint", async () => { + Reflect.set(globalThis, "window", new EventTarget()); + fakeTimers(); + const h = stagingConflictHarness(); + try { + const sock = { destroy() {} }; + const c = h.file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + + h.state.buffer = "v0\nx\n"; + window.dispatchEvent(new Event("pagehide")); + assert.equal(h.posts.length, 1); + window.dispatchEvent(new Event("pageshow")); + + // The room's document arrives before the checkpoint has reached it. + c.ws = sock; + h.file.collab.doc.transact(() => h.file.collab.text.insert(0, "v0\n"), sock); + c.onStatus("live"); + c.onReady(); + await advance(0); + // Waiting: no peek, no splice, no park. + assert.equal(h.posts.length, 1); + same(h.puts, []); + assert.equal(h.file.collab.text.toString(), "v0\n"); + + // The checkpoint lands, and the room broadcasts its line on the socket. + h.roomAnswers[0].resolve(h.ok({ ok: true, sha: "sha-1", text: "v0\nx\n" })); + h.file.collab.doc.transact(() => h.file.collab.text.insert(3, "x\n"), sock); + await advance(0); + assert.equal(h.file.collab.text.toString(), "v0\nx\n"); // once, never twice + assert.equal(h.posts.length, 1); + same(h.puts, []); + await advance(60_000); + assert.equal(h.file.collab.text.toString(), "v0\nx\n"); + assert.equal(h.posts.length, 1); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + /* R11: the socket syncs while a staging checkpoint is still on the wire. The room applies the checkpoint (its own item IDs), and the same items reach this tab twice — in the HTTP answer's `update` and on the socket. The join diff --git a/internal/webapp/static/assets/Editor-Kfw2qBqm.js b/internal/webapp/static/assets/Editor-Bf_MRt-m.js similarity index 99% rename from internal/webapp/static/assets/Editor-Kfw2qBqm.js rename to internal/webapp/static/assets/Editor-Bf_MRt-m.js index 9b59d5ee..bd87c112 100644 --- a/internal/webapp/static/assets/Editor-Kfw2qBqm.js +++ b/internal/webapp/static/assets/Editor-Bf_MRt-m.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DTYyCePQ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-DCDc5SSp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-ClgB4GHM.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-C8ckGCkQ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js b/internal/webapp/static/assets/VisualEdit-eZmLVOyc.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js rename to internal/webapp/static/assets/VisualEdit-eZmLVOyc.js index f8b6f81c..0b46581f 100644 --- a/internal/webapp/static/assets/VisualEdit-C9Fhkd7e.js +++ b/internal/webapp/static/assets/VisualEdit-eZmLVOyc.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-DTYyCePQ.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-DCDc5SSp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-ClgB4GHM.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-C8ckGCkQ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-DTYyCePQ.js b/internal/webapp/static/assets/index-ClgB4GHM.js similarity index 99% rename from internal/webapp/static/assets/index-DTYyCePQ.js rename to internal/webapp/static/assets/index-ClgB4GHM.js index 33838366..988eb8aa 100644 --- a/internal/webapp/static/assets/index-DTYyCePQ.js +++ b/internal/webapp/static/assets/index-ClgB4GHM.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Kfw2qBqm.js","assets/sharedfile-DCDc5SSp.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-C9Fhkd7e.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Bf_MRt-m.js","assets/sharedfile-C8ckGCkQ.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-eZmLVOyc.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Kfw2qBqm.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-C9Fhkd7e.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Bf_MRt-m.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-eZmLVOyc.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!l,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&o.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&o.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,l.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,o as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-C8ckGCkQ.js b/internal/webapp/static/assets/sharedfile-C8ckGCkQ.js new file mode 100644 index 00000000..caae5eed --- /dev/null +++ b/internal/webapp/static/assets/sharedfile-C8ckGCkQ.js @@ -0,0 +1,16 @@ +import{H as et,h as Sn,i as Ht,k as zo,f as Tr,e as xr,l as bn,m as Go}from"./index-ClgB4GHM.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const mt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ci=e=>e!==0?e<0:1/e<0,Lr=1,Or=2,ps=4,ws=8,ze=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,Ln=Number.MAX_SAFE_INTEGER,Rr=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&mt(e)===e),ai=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Ur=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rGe.encode(e),hl=Ge?al:cl;let Ye=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ye&&Ye.decode(new Uint8Array).length===1&&(Ye=null);const ul=(e,t)=>Zo(t,()=>e).join("");class rn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new rn,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=mt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ci(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=mt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=mt(t/128)},Ls=new Uint8Array(3e4),dl=Ls.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),Mr=new DataView(new ArrayBuffer(4)),kl=e=>(Mr.setFloat32(0,e),Mr.getFloat32(0)===e),Xe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Nr=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new rn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Nr(this),this.count=1,this.s=t)}toUint8Array(){return Nr(this),F(this.encoder)}}const $r=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new rn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):($r(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return $r(this),F(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new rn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),F(t)}}const Et=e=>new Error(e),wt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},hi=Et("Unexpected end of array"),ui=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posLn)throw ui}throw hi},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posLn)throw ui}throw hi},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>Ye.decode(K(e)),Yt=Ye?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Yt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Fr extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ci(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=mt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ll=crypto.getRandomValues.bind(crypto),fi=()=>Ll(new Uint32Array(1))[0],Ol="10000000-1000-4000-8000"+-1e11,Rl=()=>Ol.replace(/[018]/g,e=>(e^fi()&15>>e/4).toString(16)),Gt=Date.now,Br=e=>new Promise(e);Promise.all.bind(Promise);const Vr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let di=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(di=localStorage,Gs=!1)}catch{}const gi=di,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Qe=Symbol("Equality"),pi=(e,t)=>e===t||!!e?.[Qe]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},On=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},on=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||On(e)===On(t)&&on(e,(n,s)=>(n!==void 0||Xs(t,s))&&pi(t[s],n)),Pl=Object.freeze,wi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&wi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Qe]!=null)return e[Qe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var mi={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",yi=typeof window<"u"&&typeof document<"u"&&!Xt;let St;const Yl=()=>{if(St===void 0)if(Xt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Ur(t,"-")}`,n),St.set(`-${Ur(t,"-")}`,n)}})):St=rt();return St},Os=e=>Yl().has(e),Rn=e=>Vr(Xt?mi[e.toUpperCase().replaceAll("-","_")]:gi.getItem(e)),ki=e=>Os("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Xt&&Wl(mi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Os("--no-colors")&&!ki("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Os("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),Si=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=Si(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=yi?Ql:Zl,sc=yi?tc:ec,rc=e=>{const t=Si(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),jr=e=>e.next()>=.5,ks=(e,t,n)=>mt(e.next()*(n+1-t)+t),bi=(e,t,n)=>mt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>bi(e,t,n),lc=e=>ai(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Qe]?pi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?on(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Qe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){wt()}get nullable(){return Me(this,Qn)}get optional(){return new Ci(this)}cast(t){return Hr(t,this),t}expect(t){return Hr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),_i=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ei=e=>{if(Ie.check(e))return[uc(e)];if(_i.check(e))return e.shape.map(t=>t+"");if(Ui.check(e))return["[+-]?\\d+.?\\d*"];if(Mi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ei).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ei).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Ci extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Ci);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):on(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Di extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&on(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ai=(e,t)=>new Di(e,t),kc=J(Di);class Ii extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&on(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ii(e);J(Ii);class Ti extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const xi=(...e)=>new Ti(e),bc=J(Ti),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>Ze(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Oi=()=>!0,Mn=G(Oi),xc=J(tr,e=>e.shape===Oi),nr=G(e=>typeof e=="bigint"),Lc=G(e=>e===nr),Ri=G(e=>typeof e=="symbol");G(e=>e===Ri);const Se=G(e=>typeof e=="number"),Ui=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Mi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Oc=G(e=>e===Kn),vi=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,vi,nr,Kn,Ri);(()=>{const e=xi(Mn),t=Ai(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const Ze=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=Ze(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(Ze));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Hr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ze(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),Ni=vc(Mn).if(Ui,(e,t)=>ks(t,Rr,Ln)).if(Mi,(e,t)=>cc(t)).if(Oc,(e,t)=>jr(t)).if(Lc,(e,t)=>BigInt(ks(t,Rr,Ln))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(jr(t))continue;r=r.shape}n[s]=Ni(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=bi(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,vi,nr,Kn,xi(Se),Ai(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;rNi(Ze(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n($i(e,Vc(t)),e),eu=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const nu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),$i=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Fi=Ft(),Bi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),Vi=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...ji(e)),Pi.forEach(t=>t.print(e))},Hi=(...e)=>{console.warn(...ji(e)),e.unshift(sr),Pi.forEach(t=>t.print(e))},Pi=zt(),Ji=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Ji(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Ji(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=mt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Wi=fi;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Wi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Br(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Br(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Yi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class qi extends Yi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Fr(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Fr(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new ro,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(S=>S!==p)}s.length=0};for(;;){if(u.constructor!==dt){const p=At(h,u.id.client,()=>P(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,P(t,y)),d();else{u=S.refs[S.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new oe;return or(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),a=aa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=Nn([u.update,a.update])}}else l.pendingStructs=a;const h=Pr(s,r,l);if(l.pendingDs){const d=new xe(Kt(l.pendingDs));E(d.restDecoder);const f=Pr(d,r,l);h&&f?l.pendingDs=Nn([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Xi(r.doc,d)}},n,!1),Xi=(e,t,n,s=xe)=>{const r=Kt(t);ua(r,e,n,new s(r))},Ki=(e,t,n)=>Xi(e,t,n,qi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=Zi(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===cn)return Oa(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Qi=(e,t)=>da(e,t,new cn),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new Yi(Kt(e))),to=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>to(e,ts(t.store)),wa=(e,t=new Gi)=>(e instanceof Map?to(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new zi);class ya{constructor(){this.l=[]}}const Jr=()=>new ya,Wr=(e,t)=>e.l.push(t),Yr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},eo=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),no=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class so{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const su=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new so(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=no(e):s=D(e._item.id.client,e._item.id.clock),new so(s,r,t,n)},ru=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const u=n?$s(s,r):_a(s,r),h=u.item;if(!(h instanceof M))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:u}=n?$s(s,i):{item:_e(s,i)};if(u instanceof M&&u.content instanceof Tt)c=u.content.type;else return null}else throw at();l>=0?a=c._length:a=0}return ba(c,a,e.assoc)},iu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ln(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class ro{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},io=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=mt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},qr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ft&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},oo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Gr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,zt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=Ct(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+xn(r,c)}})},lo=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{eo(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ae(Ct(f,d),1);for(let y=f.length-1;y>=p;)y-=1+xn(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=Ct(f,d);p+11||p>0&&xn(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Fi,"[yjs] ",Bi,Vi,"Changed the client-id because another client seems to be using it."),s.clientID=Wi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new cn;zr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new oe;zr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):lo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&lo(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Xr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Kr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Te(l,a.insertions,f=>{if(f instanceof M){if(f.redone!==null){let{item:p,diff:y}=$s(c,f.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||vn(p,f))&&h.push(f)}}),Te(l,a.deletions,f=>{f instanceof M&&i.some(p=>p===l.doc||vn(p,f))&&!ln(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=Ao(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class ou extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new ve;c.afterState.forEach((S,w)=>{const b=c.beforeState.get(w)||0,O=S-b;O>0&&tn(d,w,b,O)});const f=Gt();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=Us([S.deletions,c.deleteSet]),S.insertions=Us([S.insertions,d])}else h.push(new xa(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Te(c,c.deleteSet,S=>{S instanceof M&&this.scope.some(w=>w===c.doc||vn(w,S))&&gr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Hi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Xr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Xr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Kr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Kr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*La(e){const t=E(e.restDecoder);for(let n=0;nNn(e,qi,cn),Ra=(e,t)=>{if(e.constructor===ft){const{client:n,clock:s}=e.id;return new ft(D(n,s+t),e.length-t)}else if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Kt(u)));let r=s.map(u=>new lr(u,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===dt?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===dt?i.struct.length-=p:d=Ra(d,p)),i.struct.mergeWith(d)||(Jt(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==dt;d=u.next())Jt(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(u=>ir(u)),a=Us(c);return Ne(o,a),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=Zi(t),i=new s,o=new cr(i),l=new n(Kt(e)),c=new lr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===dt){c.next();continue}if(u.id.clock+u.length>d)for(Jt(o,u,ae(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}ar(o);const a=ir(l);return Ne(i,a),i.toUint8Array()},co=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:F(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&co(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{co(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let a=i.curr;a!==null;a=i.next())Jt(l,t(a),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,cn),Qr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return ln(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Qr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Qr);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Hi("Invalid access: Add Yjs type to a document before reading data.")},ao=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},ho=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ao){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;eo(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Jr(),this._dEH=Jr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw wt()}clone(){throw wt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Wr(this._eH,t)}observeDeep(t){Wr(this._dEH,t)}unobserve(t){Yr(this._eH,t)}unobserveDeep(t){Yr(this._dEH,t)}toJSON(){}}const uo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},fo=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return nn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},po=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new an(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},wo=()=>Et("Length exceeded!"),mo=(e,t,n,s)=>{if(n>t._length)throw wo();if(n===0)return t._searchMarker&&en(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},yo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw wo();t._searchMarker&&en(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new an(s);break;case he:l=new hn(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new M(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},So=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return po(this,t)}toArray(){return fo(this)}slice(t=0,n=this.length){return uo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return go(this,t)}forEach(t){nn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return So(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return Zr(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return Zr(e,o,n)}},bo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new M(D(i,P(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new W(l,o));u.integrate(e,0),n.right=u,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},_o=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Eo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Wt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new M(D(i,P(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:a,right:u,index:h}=n;t._searchMarker&&en(t._searchMarker,n.index,c.getLength()),u=new M(D(o,P(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),bo(e,t,n,l)},ti=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Wt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new M(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}bo(e,t,n,l)},Co=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===W){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&$e(r,a)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Co(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&oo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==ft&&t.add(o.parent)})}U(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof ft||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ei=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},jl(c)||(f.attributes=$l({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case W:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Wt(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Wt(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Wt(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Wt(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),$e(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ti(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ei(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const h=i.get("ychange");t!==void 0&&!we(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case W:we(c,t)&&(a(),$e(i,c.content));break}c=c.right}a()};return t||n?U(o,h=>{t&&Ms(h,t),n&&Ms(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{ei(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ti(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Oe;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return go(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),nn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return fo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return po(this,t)}slice(t=0,n=this.length){return uo(this,t,n)}forEach(t){nn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return So(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return nn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Le{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw wt()}mergeWith(t){return!1}write(t,n,s){throw wt()}integrate(t,n){throw wt()}}const sh=0;class ft extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),io(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class an{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new an(this.content)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new an(e.readBuf());class sn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new sn(this.len)}splice(t){const n=new sn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){tn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new sn(e.readLen()),Do=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class hn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hn(Do(this.doc.guid,this.opts))}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new hn(Do(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ni=(e,t)=>js(e,n=>ln(n.deletions,t)),Ao=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return st(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Ao(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=st(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||ln(s,h.right.id)||ni(i.undoStack,h.right.id)||ni(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=st(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),S=new M(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,gr(S,!0),S.integrate(e,0),S};class M extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Or:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Or)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=qr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ft||this.right&&this.right.constructor===ft)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===ft?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=qr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),tn(t.deleteSet,this.id.client,this.id.clock,this.length),Gr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new ft(this.id,this.length)):this.content=new sn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:ze);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=no(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const Io=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},xo="__ $YJS$ __";To[xo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");To[xo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){gi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=zt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Oo=0,wr=1,Ro=2,Fs=(e,t)=>{_(e,Oo);const n=ma(t);H(e,n)},Uo=(e,t,n)=>{_(e,wr),H(e,Qi(t,n))},Th=(e,t,n)=>Uo(t,n,K(e)),Mo=(e,t,n,s)=>{try{Ki(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Ro),H(e,t)},Lh=Mo,Oh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Oo:Th(e,t,n);break;case wr:Mo(e,n,s,r);break;case Ro:Lh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Yt(e))},Cs=3e4;class vo extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Gt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},mt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Gt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},qe=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Kt(t),r=Gt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,No=3,Ce=1,Nh=2,un=[];un[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Oh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};un[No]=(e,t,n,s,r)=>{_(e,Ce),H(e,qe(n.awareness,Array.from(n.awareness.getStates().keys())))};un[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};un[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const si=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),$o=(e,t,n)=>{const s=Kt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Fo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Fo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt();const s=$o(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(F(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(F(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,qe(e.awareness,[e.doc.clientID])),t.send(F(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new vo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=un.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=Q();_(f,ne),Fs(f,s),this.ws.send(F(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=$o(this,new Uint8Array(f),!1);Js(y)>1&&me(this.bcChannel,F(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,f),Ds(this,F(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},S)=>{const w=f.concat(p).concat(y),b=Q();_(b,Ce),H(b,qe(i,w)),Ds(this,F(b))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&si{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Qi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ri||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,O=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let T;w===0?T=0:L===-w||L!==w&&b[L-1+w-1]=r&&$>=i){u=w;break}}a.push(O)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],O=d-f,L=O===-w||O!==w&&b[O-1+w-1]B&&f>gt;)d--,f--,h.push(d,f);d=T,f=$}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],O=h[w+1];(b>y||O>S)&&p.push({aS:n+y,aE:n+b,bS:n+S,bE:n+O}),y=b+1,S=O+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +`)||i[o.length]===` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),a=_t(o,i),u=[...Ue(a,_t(l,i)).map(S=>({h:S,toks:l,side:0})),...Ue(a,_t(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,b)=>S.slice(w,b).join(""),d=(S,w,b,O)=>{let L="",T=b;for(const $ of S)$.side===w&&(L+=h(o,T,$.h.aS)+h($.toks,$.h.bS,$.h.bE),T=$.h.aE);return L+h(o,T,O)};let f="",p=0,y=0;for(;yB.side)).size===1){f+=d(S,S[0].side,w,b);continue}const L=d(S,0,w,b),T=d(S,1,w,b);if(L===T){f+=L;continue}if(w===b){const B=qh(L,T,s!==As,o.length===0);if(B===null){if(!r)return null;f+=T;continue}f+=B;continue}if(s===As)return null;const $=s===Pn?Jn(h(o,w,b),L,T,As):Jn(h(o,w,b),L,T,s+1,r);if($===null){if(!r)return null;f+=T;continue}f+=$}return f+h(o,p,o.length)}const se=e=>e===""||e.endsWith(` +`)?e:e+` +`;function Bo(e,t,n,s){let r=t.endsWith(` +`);return r===e.endsWith(` +`)&&(r=n.endsWith(` +`)),s===""||r===s.endsWith(` +`)?s:r?s+` +`:s.slice(0,-1)}function Pt(e,t,n){const s=Jn(se(e),se(t),se(n),qt);return s===null?{ok:!1}:{ok:!0,text:Bo(e,t,n,s)}}function lu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),qt,!0)??se(n);return Bo(e,t,n,s)}function ii(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,qt),i=bt(t,qt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;O>=55296&&O<=56319&&w--;const L=b>0?p.charCodeAt(p.length-b):0;L>=56320&&L<=57343&&b--,S+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:S,deleteCount:p.length,insertText:y}),a=d,u=f}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,qt),s),i=Ue(_t(bt(e,qt),s),r),o=Ue(r,_t(bt(n,qt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function We(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const oi=700,pe=[2e3,4e3,8e3,15e3],li=2e3,Gh=4,Xh=64,Kh=8,Qh=32e3,Zh=32;function cu(e){let t=e.seed,n=e.baseSha;const s=(g,k)=>{t=g,r=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(g,k=tt)=>{const m=i(k);return r&&r===n&&t.length>Qh?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,S=!1,w=null,b=null,O="",L=0;const T=(g=Date.now())=>{const k=Math.max(g,L+1e3);return L=k,zo(e.path,e.who||"browser",new Date(k))},$=new Map;let B=0,gt=!1,ht=null,Qt=0,rs=!1,tt=null,xt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>Zh&&Bt.shift())};let Lt=!1,Fe=null,Zt=0;const Be=()=>{Lt=!1,Fe=null},is=g=>{Zt===g&&Be()};let it=0,pt=0,fn=null,te=null,os=!1,Vt=null,Ot=null,Ve=!1,ee=null,ut=null;const v=g=>e.onState?.(g),dn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let gn=null,ls=0;const je=()=>{clearTimeout(gn??void 0),gn=null},pn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||h||a)return;je();const m=pe[Math.min(ls,pe.length-1)];ls++,gn=setTimeout(()=>{gn=null,!h&&!a&&He()},m)},kr=()=>{je(),ls=0},wn=()=>{je(),ee&&clearTimeout(ee),ee=setTimeout(()=>{He()},oi)},Rt=g=>{if(h)return f=g,!0;const k=N();if(k===g)return!0;const m=ii(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},He=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():Pe();if(te)return os=!0,te;const g=(async()=>{try{for(;Vt;)await Vt;await Vo()}finally{te=null}})();return te=g,g},Vo=async()=>{let g=0;for(;;){if(os=!1,Y||a||S)return;const k=N();if(k===t&&!xt){v("clean");return}if(v("saving"),e.onWriting?.(),gt){if(w!==null&&b===k){if(await mn(k,O)==="stop")return;continue}gt=!1}const m=l||c?await jo(k):await Po(k);if(m==="stop")return;if(m==="rebased"){if(++g>Gh){await mn(N(),n??"");return}continue}if(!os){v(N()===t&&!xt?"clean":"dirty");return}}};let yt=!1;const jo=async g=>{Ot=g,Ve=!1;let k;try{k=await Sn(dn(e.path),g,n,yt)}catch(m){return Ot=null,m instanceof et&&m.status===422&&We(m)?(yt=!1,fe(g),"stop"):m instanceof et&&m.status===409?await cs(t,!1)?"rebased":"stop":(v("error"),pn(m),"stop")}return Ot=null,yt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(Ve||s(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await Tr(xr(e.apiBase,e.path))}catch(R){return v("error"),N()!==t&&pn(R),!1}if(m.kind!=="text")return v("error"),!1;const A=N(),C=Pt(g,m.text,A);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await mn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ho=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){xt=!0;const m=Pt(k.sent,g.text,N());m.ok&&Rt(m.text)?(t=g.text,r=void 0,ot(g.sha)):(t=k.sent,r=void 0)}},Po=async g=>{Ot=g,Ve=!1;let k;const m=tt;try{tt={sent:g,from:t,prev:m},k=await Ht(jt,{...o(g,m),...yt?{confirm_shrink:!0}:{}})}catch(C){if(Ot=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return c=!0,"rebased";if(C instanceof et&&C.status===422&&We(C))return yt=!1,fe(g),"stop";if(C instanceof et&&C.status===409&&!a){let R={};try{R=JSON.parse(C.body)}catch{}const j=typeof R.text=="string"?R.text:null;if(j!==null){const X=Pt(t,j,N());if(X.ok&&Rt(X.text))return t=j,r=void 0,ot(R.sha),"rebased"}return mn(N(),R.sha??"")}return v(a?"dirty":"error"),pn(C),"stop"}if(Ot=null,yt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,xt=!1,a)return"stop";const A=Pt(g,k.text,N());return A.ok&&Rt(A.text)&&(Ve||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const fe=g=>{Y||h||!e.onShrinkRefused||(v("error"),Y={was:bn(t),now:bn(g),confirm:async()=>{if(!h){if(a){v("saving"),e.onWriting?.();const k=it,m=Zt;try{const A=await Ht(jt,{update:x.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),as(k,m);const C=!Lt&&pt>=it;v(C?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&pt{if(!h)try{const k=await Tr(xr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await de(!1),h)return;v(pt>=it&&!Lt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Be(),v("clean")}catch{v("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let kt=null;const Jo=()=>{kt&&clearTimeout(kt),kt=setTimeout(()=>{const g=N();Go(bn(t),bn(g))&&fe(g)},oi)},Sr=async(g,k,m=T())=>{const A=++B;let C=m;for(let R=1;;R++){const j=C;$.set(j,g);try{return await Sn(dn(j),g,void 0,!1,!1,!1,!0),A===B&&!a&&(t=g,r=void 0,k&&(n=k),v("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&R{const C=(R,j)=>{Sn(dn(R),k,void 0,!1,!0,!0,!0).then(X=>A?.(X.parked??R),X=>{if(X instanceof et&&X.status===409&&j{(w===null||b!==g)&&(w=T(),b=g);const m=w;O=k,gt=!0;const A=await Sr(g,k,m);return h?"stop":A?(pn(A.err),"stop"):(gt=!1,b===g&&(w=null,b=null,O=""),N()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(h||u)&&(d=it-pt,e.onPending?.(d))},Wo=()=>{h||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!h&&de(!1)},li))},de=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,A=Zt;return Ht(jt,{update:x.encodeState(),base:n},!0).then(C=>{ot(C.sha),as(m,A)})}if(fn)return fn;const k=(async()=>{try{for(;!u&&!h&&!Y&&pt{p=!1,w=null,b=null,Qt=0,clearTimeout(ht??void 0),ht=null,xt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Pe=async()=>{if(h||a||y||S)return;if(clearTimeout(ht??void 0),ht=null,ee&&clearTimeout(ee),ee=null,te||Vt){S=!0;try{for(;te||Vt;)await(te??Vt)}finally{S=!1}if(h||a)return;if(!u){N()!==t&&wn();return}}if(tt!==null&&!c){let j;S=!0;try{j=await Ht(jt,{peek:!0})}catch{if(h||a)return;const X=pe[Math.min(Qt,pe.length-1)];Qt++,ht=setTimeout(()=>{ht=null,Pe()},X);return}finally{S=!1}if(h||a)return;if(Ho(j),!u){(N()!==t||xt)&&wn();return}}const g=e.soloText?.();if(g===void 0||g===t)return hs();const k=x.text.toString(),m=Pt(t,k,g);if(m.ok)return hs(()=>x.applySplices(ii(k,m.text)));p=!0,(w===null||b!==g)&&(w=T(),b=g),y=!0;let A;try{A=await Sr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,Pe()):hs(()=>{t=x.text.toString()});const C=A.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const R=pe[Math.min(Qt,pe.length-1)];Qt++,ht=setTimeout(()=>{ht=null,Pe()},R)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(ut&&clearTimeout(ut),ut=null,je(),a||Pe(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if(v("dirty"),a){Lt=!0,Fe=m,Zt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!h&&de(!1)},li)),Jo();return}wn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{h||(l=!0,x.stop(),e.onSolo())});const N=()=>f!==null?f:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||l&&x.text.length>0,ot=g=>{g&&(n=g)},Yo=(g,k,m)=>{if(m?.held)return s(g,k),"same";if(g===t||g===Ot)return ot(k),"same";const A=N();if(g===A)return s(g,k),a&&(Be(),v("clean")),"same";if(a){const R=t;return Bt.includes(g)||Dn(R,g,A)?(s(g,k),Lt&&(Fe===null||g===Fe||Dn(R,Fe,g))&&(Be(),v("clean")),"same"):A!==t||x.peerCount()>0?"blocked":(s(g,k),Rt(g),Be(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=Pt(t,g,A);return C.ok?(Ot!==null&&(Ve=!0),s(g,k),Rt(C.text),C.text!==g?wn():Ot===null&&v("clean"),C.text===A?"same":"merged"):"blocked"};let yn=null;const qo=()=>{if(!a)return He();if(Y||h)return Promise.resolve();if(!u)return d>0?de(!1):Promise.resolve();if(!Lt)return Promise.resolve();if(yn)return yn;const g=Zt;v("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(h)return;m.update&&x.applyRemoteUpdate(m.update),s(m.text,m.sha),is(g),v(Lt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof et&&m.status===422&&We(m)&&(clearTimeout(kt??void 0),kt=null,fe(N()),Y))return;v(Lt?"dirty":"clean")}finally{yn=null}})();return yn=k,k};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const I=!u&&d>0;if(!I&&!(u&&Lt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Zt;(I?de(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(p||gt){if(!g.trim())return;const I="park\0"+g;if(Ut===I)return;Ut=I;let V=w!==null&&b===g?w:null;for(const[Mt,lt]of $)V===null&<===g&&(V=Mt);V??=T(),br(V,g,I);return}if(g===t&&!xt)return;const m="text\0"+g;if(Ut===m)return;if((l||c)&&!k){He();return}Ut=m;const A=t,C=!(l||c),R=tt,j={sent:g,from:A,prev:R};C&&(tt=j);const X=I=>{if(C&&I instanceof et&&[400,401,403,404,405,409,413].includes(I.status)&&tt===j&&(tt=R),I instanceof et&&I.status===422&&We(I)){kn(m)(),h||(clearTimeout(kt??void 0),kt=null,fe(N()));return}if(!(I instanceof et&&I.status===409))return kn(m)();let V={};try{const lt=JSON.parse(I.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(A,g,V.text))){if(!h&&!a){const lt=Pt(g,V.text,N());lt.ok&&Rt(lt.text)&&(t=V.text,r=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;gt=!0;let Mt=w!==null&&b===g?w:null;for(const[lt,ds]of $)Mt===null&&ds===g&&(Mt=lt);Mt??=T(),w=Mt,b=g,br(Mt,g,m,lt=>{gt=!1,e.onConflictCopy?.(lt)})},Je=(I,V)=>{t=g,r=void 0,ot(V),!h&&N()===g&&v("clean"),e.onConflictCopy?.(I)};let us;C?us=Ht(jt,{...o(g,R),park_on_conflict:!0},!0).then(I=>{if(yt=!1,tt===j&&(tt=null),xt=!1,I.parked)return Je(I.parked,I.sha);if(I.update&&x.applyRemoteUpdate(I.update),h||a||typeof I.text!="string"){ot(I.sha);return}const V=Pt(g,I.text,N());V.ok&&Rt(V.text)&&(s(I.text,I.sha),N()===t&&v("clean")),e.onSaved?.(I.text)},X):us=Sn(dn(e.path),g,n,yt,!0,!0).then(I=>{if(yt=!1,I.parked)return Je(I.parked,I.sha);if(I.merged){h?ot(I.sha):cs(g,!0);return}s(g,I.sha),!h&&N()===t&&v("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{h||Dr(N(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:N,merge:Yo,rebase:ot,saveNow:qo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(ee??void 0),clearTimeout(kt??void 0),je(),clearTimeout(ht??void 0),ht=null;const g=N();h=!0,f=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,oi as S,ou as U,ru as a,ka as b,Ea as c,ii as d,iu as e,Ps as f,ae as g,eu as h,vt as i,lu as m,cu as o,su as r,nu as t}; diff --git a/internal/webapp/static/assets/sharedfile-DCDc5SSp.js b/internal/webapp/static/assets/sharedfile-DCDc5SSp.js deleted file mode 100644 index a68d00a2..00000000 --- a/internal/webapp/static/assets/sharedfile-DCDc5SSp.js +++ /dev/null @@ -1,16 +0,0 @@ -import{H as nt,h as gn,i as $t,k as Ho,f as _r,e as Er,l as pn,m as Po}from"./index-DTYyCePQ.js";const tt=()=>new Map,ks=e=>{const t=tt();return e.forEach((n,s)=>{t.set(s,n)}),t},bt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Jo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Wo=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},Ht=()=>new Set,ls=e=>e[e.length-1],Yo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Ot((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}class Go{constructor(){this._observers=tt()}on(t,n){bt(this._observers,t,Ht).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return Ot((this._observers.get(t)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}const dt=Math.floor,bn=Math.abs,Ns=(e,t)=>ee>t?e:t,qo=Math.pow,ni=e=>e!==0?e<0:1/e<0,Cr=1,Dr=2,cs=4,as=8,Pe=32,Lt=64,st=128,Vn=31,bs=63,te=127,Xo=2147483647,Dn=Number.MAX_SAFE_INTEGER,Ar=Number.MIN_SAFE_INTEGER,Ko=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&dt(e)===e),si=String.fromCharCode,Qo=e=>e.toLowerCase(),Zo=/^\s*/g,tl=e=>e.replace(Zo,""),el=/([A-Z])/g,Ir=(e,t)=>tl(e.replace(el,n=>`${t}${Qo(n)}`)),nl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rJe.encode(e),rl=Je?sl:nl;let je=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});je&&je.decode(new Uint8Array).length===1&&(je=null);const il=(e,t)=>zo(t,()=>e).join("");class Ze{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const X=()=>new Ze,$s=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array($s(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},_s=Y,_=(e,t)=>{for(;t>te;)Y(e,st|te&t),t=dt(t/128);Y(e,te&t)},Fs=(e,t)=>{const n=ni(t);for(n&&(t=-t),Y(e,(t>bs?st:0)|(n?Lt:0)|bs&t),t=dt(t/64);t>0;)Y(e,(t>te?st:0)|te&t),t=dt(t/128)},Es=new Uint8Array(3e4),ll=Es.length/3,cl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ns(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ie(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},V=(e,t)=>{_(e,t.byteLength),jn(e,t)},Bs=(e,t)=>{ol(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},hl=(e,t)=>Bs(e,4).setFloat32(0,t,!1),ul=(e,t)=>Bs(e,8).setFloat64(0,t,!1),fl=(e,t)=>Bs(e,8).setBigInt64(0,t,!1),Tr=new DataView(new ArrayBuffer(4)),dl=e=>(Tr.setFloat32(0,e),Tr.getFloat32(0)===e),We=(e,t)=>{switch(typeof t){case"string":Y(e,119),ee(e,t);break;case"number":Ko(t)&&bn(t)<=Xo?(Y(e,125),Fs(e,t)):dl(t)?(Y(e,124),hl(e,t)):(Y(e,123),ul(e,t));break;case"bigint":Y(e,122),fl(e,t);break;case"object":if(t===null)Y(e,126);else if(be(t)){Y(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Lr=e=>{e.count>0&&(Fs(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class _n{constructor(){this.encoder=new Ze,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Lr(this),this.count=1,this.s=t)}toUint8Array(){return Lr(this),F(this.encoder)}}const Or=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Fs(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class hs{constructor(){this.encoder=new Ze,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Or(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Or(this),F(this.encoder)}}class gl{constructor(){this.sarr=[],this.s="",this.lensE=new _n}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Ze;return this.sarr.push(this.s),this.s="",ee(t,this.sarr.join("")),jn(t,this.lensE.toUint8Array()),F(t)}}const yt=e=>new Error(e),ft=()=>{throw yt("Method unimplemented")},rt=()=>{throw yt("Unexpected case")},ri=yt("Unexpected end of array"),ii=yt("Integer out of Range");class Hn{constructor(t){this.arr=t,this.pos=0}}const Wt=e=>new Hn(e),pl=e=>e.pos!==e.arr.length,wl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},q=e=>wl(e,E(e)),_e=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posDn)throw ii}throw ri},Vs=e=>{let t=e.arr[e.pos++],n=t&bs,s=64;const r=(t&Lt)>0?-1:1;if((t&st)===0)return r*n;const i=e.arr.length;for(;e.posDn)throw ii}throw ri},ml=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(_e(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(_e(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},yl=e=>je.decode(q(e)),Vt=je?yl:ml,js=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Sl=e=>js(e,4).getFloat32(0,!1),kl=e=>js(e,8).getFloat64(0,!1),bl=e=>js(e,8).getBigInt64(0,!1),_l=[e=>{},e=>null,Vs,Sl,kl,bl,e=>!1,e=>!0,Vt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;s_l[127-_e(e)](e);class Rr extends Hn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),pl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class En extends Hn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vs(this);const t=ni(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class us extends Hn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Vs(this),n=t&1;this.diff=dt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class El{constructor(t){this.decoder=new En(t),this.str=Vt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Cl=crypto.getRandomValues.bind(crypto),oi=()=>Cl(new Uint32Array(1))[0],Dl="10000000-1000-4000-8000"+-1e11,Al=()=>Dl.replace(/[018]/g,e=>(e^oi()&15>>e/4).toString(16)),Pt=Date.now,Ur=e=>new Promise(e);Promise.all.bind(Promise);const Mr=e=>e===void 0?null:e;class Il{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let li=new Il,Hs=!0;try{typeof localStorage<"u"&&localStorage&&(li=localStorage,Hs=!1)}catch{}const ci=li,Tl=e=>Hs||addEventListener("storage",e),xl=e=>Hs||removeEventListener("storage",e),ze=Symbol("Equality"),ai=(e,t)=>e===t||!!e?.[ze]?.(t)||!1,Ll=e=>typeof e=="object",Ol=Object.assign,Rl=Object.keys,Ul=(e,t)=>{for(const n in e)t(e[n],n)},Ml=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},An=e=>Rl(e).length,vl=e=>{for(const t in e)return!1;return!0},tn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ps=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Nl=(e,t)=>e===t||An(e)===An(t)&&tn(e,(n,s)=>(n!==void 0||Ps(t,s))&&ai(t[s],n)),$l=Object.freeze,hi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&hi(e[t])}return $l(e)},Js=(e,t,n=0)=>{try{for(;ne,pe=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ze]!=null)return e[ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ui={};const Jt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",fi=typeof window<"u"&&typeof document<"u"&&!Jt;let pt;const Vl=()=>{if(pt===void 0)if(Jt){pt=tt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");pt.set(`--${Ir(t,"-")}`,n),pt.set(`-${Ir(t,"-")}`,n)}})):pt=tt();return pt},Cs=e=>Vl().has(e),In=e=>Mr(Jt?ui[e.toUpperCase().replaceAll("-","_")]:ci.getItem(e)),di=e=>Cs("--"+e)||In(e)!==null,jl=di("production"),Hl=Jt&&Bl(ui.FORCE_COLOR,["true","1","2"]),Pl=Hl||!Cs("--no-colors")&&!di("no-color")&&(!Jt||process.stdout.isTTY)&&(!Jt||Cs("--color")||In("COLORTERM")!==null||(In("TERM")||"").includes("color")),gi=e=>new Uint8Array(e),Jl=(e,t,n)=>new Uint8Array(e,t,n),Wl=e=>new Uint8Array(e),Yl=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Gl=e=>{const t=atob(e),n=gi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Jl(t.buffer,t.byteOffset,t.byteLength)},Xl=fi?Yl:zl,Kl=fi?Gl:ql,Ql=e=>{const t=gi(e.byteLength);return t.set(e),t};class Zl{constructor(t,n){this.left=t,this.right=n}}const xt=(e,t)=>new Zl(e,t),tc=(e,t)=>e.forEach(n=>t(n.left,n.right)),vr=e=>e.next()>=.5,fs=(e,t,n)=>dt(e.next()*(n+1-t)+t),pi=(e,t,n)=>dt(e.next()*(n+1-t)+t),Ws=(e,t,n)=>pi(e,t,n),ec=e=>si(Ws(e,97,122)),nc=(e,t=0,n=20)=>{const s=Ws(e,t,n);let r="";for(let i=0;it[Ws(e,0,t.length-1)],sc=Symbol("0schema");class rc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(il(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const Ds=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[ze]?ai(e,t):be(e)?Us(e,n=>Ms(t,s=>Ds(n,s))):Ll(e)?tn(e,(n,s)=>Ds(n,t[s])):!1;class Q{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Ds(n,s)}equals(t){return this.constructor===t.constructor&&pe(this.shape,t.shape)}[sc](){return!0}[ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){ft()}get nullable(){return Le(this,zn)}get optional(){return new yi(this)}cast(t){return Nr(t,this),t}expect(t){return Nr(t,this),t}}class Ys extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const P=(e,t=null)=>new Ys(e,t);P(Ys);class zs extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new zs(e);P(zs);class Pn extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Jn=(...e)=>new Pn(e),wi=P(Pn),ic=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),mi=e=>{if(Ee.check(e))return[ic(e)];if(wi.check(e))return e.shape.map(t=>t+"");if(Ii.check(e))return["[+-]?\\d+.?\\d*"];if(Ti.check(e))return[".*"];if(Tn.check(e))return e.shape.map(mi).flat(1);rt()};class oc extends Q{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(mi).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}P(oc);const lc=Symbol("optional");class yi extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[lc](){return!0}}const cc=P(yi);class ac extends Q{check(t,n){return n?.extend(null,"never",typeof t),!1}}P(ac);class Wn extends Q{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Wn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):tn(this.shape,(s,r)=>{const i=this._isPartial&&!Ps(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const hc=e=>new Wn(e),uc=P(Wn),fc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Si extends Q{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&tn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const ki=(e,t)=>new Si(e,t),dc=P(Si);class bi extends Q{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&tn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const gc=(...e)=>new bi(e);P(bi);class _i extends Q{constructor(t){super(),this.shape=t.length===1?t[0]:new Gs(t)}check(t,n){const s=be(t)&&Us(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Ei=(...e)=>new _i(e),pc=P(_i),wc=G(e=>be(e));class Ci extends Q{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const mc=(e,t=null)=>new Ci(e,t);P(Ci);const yc=mc(Q);class Sc extends Q{constructor(t){super(),this.len=t.length-1,this.args=gc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const kc=P(Sc),bc=G(e=>typeof e=="function");class _c extends Q{constructor(t){super(),this.shape=t}check(t,n){const s=Us(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}P(_c,e=>e.shape.length>0);class Gs extends Q{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Ms(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Le=(...e)=>e.findIndex(t=>Tn.check(t))>=0?Le(...e.map(t=>Ge(t)).map(t=>Tn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Gs(e),Tn=P(Gs),Di=()=>!0,xn=G(Di),Ec=P(zs,e=>e.shape===Di),qs=G(e=>typeof e=="bigint"),Cc=G(e=>e===qs),Ai=G(e=>typeof e=="symbol");G(e=>e===Ai);const we=G(e=>typeof e=="number"),Ii=G(e=>e===we),Ee=G(e=>typeof e=="string"),Ti=G(e=>e===Ee),Yn=G(e=>typeof e=="boolean"),Dc=G(e=>e===Yn),xi=Jn(void 0);P(Pn,e=>e.shape.length===1&&e.shape[0]===void 0);Jn(void 0);const zn=Jn(null),Ac=P(Pn,e=>e.shape.length===1&&e.shape[0]===null);P(Uint8Array);P(Ys,e=>e.shape===Uint8Array);const Ic=Le(we,Ee,zn,xi,qs,Yn,Ai);(()=>{const e=Ei(xn),t=ki(Ee,xn),n=Le(we,Ee,zn,Yn,e,t);return e.shape=n,t.shape.values=n,n})();const Ge=e=>{if(yc.check(e))return e;if(fc.check(e)){const t={};for(const n in e)t[n]=Ge(e[n]);return hc(t)}else{if(wc.check(e))return Le(...e.map(Ge));if(Ic.check(e))return Jn(e);if(bc.check(e))return P(e)}rt()},Nr=jl?()=>{}:(e,t)=>{const n=new rc;if(!t.check(e,n))throw yt(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Tc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ge(t),h:n}),this}else(t){return this.if(xn,t)}done(){return(t,n)=>{for(let s=0;snew Tc(e),Li=xc(xn).if(Ii,(e,t)=>fs(t,Ar,Dn)).if(Ti,(e,t)=>nc(t)).if(Dc,(e,t)=>vr(t)).if(Cc,(e,t)=>BigInt(fs(t,Ar,Dn))).if(Tn,(e,t)=>ae(t,ds(t,e.shape))).if(uc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(cc.check(r)){if(vr(t))continue;r=r.shape}n[s]=Li(r,t)}return n}).if(pc,(e,t)=>{const n=[],s=pi(t,0,42);for(let r=0;rds(t,e.shape)).if(Ac,(e,t)=>null).if(kc,(e,t)=>{const n=ae(t,e.res);return()=>n}).if(Ec,(e,t)=>ae(t,ds(t,[we,Ee,zn,xi,qs,Yn,Ei(we),ki(Le("a","b","c"),we)]))).if(dc,(e,t)=>{const n={},s=fs(t,0,3);for(let r=0;rLi(Ge(t),e),_t=typeof document<"u"?document:{},Lc=e=>_t.createElement(e),Oc=()=>_t.createDocumentFragment();G(e=>e.nodeType===Vc);const Rc=e=>_t.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Uc=(e,t)=>(tc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Mc=e=>{const t=Oc();for(let n=0;n(Oi(e,Mc(t)),e),qh=(e,t=[],n=[])=>vc(Uc(Lc(e),t),n);G(e=>e.nodeType===$c);const Xh=Rc;G(e=>e.nodeType===Fc);const Nc=e=>Jo(e,(t,n)=>`${n}:${t};`).join(""),Oi=(e,t)=>e.appendChild(t),$c=_t.ELEMENT_NODE,Fc=_t.TEXT_NODE;_t.CDATA_SECTION_NODE;_t.COMMENT_NODE;const Bc=_t.DOCUMENT_NODE;_t.DOCUMENT_TYPE_NODE;const Vc=_t.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Bc);const Rt=Symbol,Ri=Rt(),Ui=Rt(),jc=Rt(),Hc=Rt(),Pc=Rt(),Mi=Rt(),Jc=Rt(),Xs=Rt(),Wc=Rt(),Yc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=tt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...vi(e)),$i.forEach(t=>t.print(e))},Ni=(...e)=>{console.warn(...vi(e)),e.unshift(Xs),$i.forEach(t=>t.print(e))},$i=Ht(),Fi=e=>({[Symbol.iterator](){return this},next:e}),Xc=(e,t)=>Fi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),gs=(e,t)=>Fi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Gn{constructor(t,n){this.clock=t,this.len=n}}class Oe{constructor(){this.clients=new Map}}const Ce=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=dt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&Kc(n,t.clock)!==null},Ks=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Gn(r.clock,ie(r.len,i.clock+i.len-r.clock)):(s{const t=new Oe;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{bt(e.clients,t,()=>[]).push(new Gn(n,s))},Qc=()=>new Oe,Zc=e=>{const t=Qc();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Re=(e,t)=>{_(e.restEncoder,t.clients.size),Ot(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Oe,n=E(e.restDecoder);for(let s=0;s0){const o=bt(t.clients,r,()=>[]);for(let l=0;l{const s=new Oe,r=E(e.restDecoder);for(let i=0;i0){const i=new ne;return _(i.restEncoder,0),Re(i,s),i.toUint8Array()}return null},Bi=oi;class oe extends vs{constructor({guid:t=Al(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Bi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Qi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ur(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Ur(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ot(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=bt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Se)}getText(t=""){return this.get(t,Ie)}getMap(t=""){return this.get(t,Ae)}getXmlElement(t=""){return this.get(t,Te)}getXmlFragment(t=""){return this.get(t,se)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Ot(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new oe({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Vi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class ji extends Vi{readLeftID(){return C(E(this.restDecoder),E(this.restDecoder))}readRightID(){return C(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return _e(this.restDecoder)}readString(){return Vt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ye(this.restDecoder)}readBuf(){return Ql(q(this.restDecoder))}readJSON(){return JSON.parse(Vt(this.restDecoder))}readKey(){return Vt(this.restDecoder)}}class ta{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class De extends ta{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new us(q(t)),this.clientDecoder=new En(q(t)),this.leftClockDecoder=new us(q(t)),this.rightClockDecoder=new us(q(t)),this.infoDecoder=new Rr(q(t),_e),this.stringDecoder=new El(q(t)),this.parentInfoDecoder=new Rr(q(t),_e),this.typeRefDecoder=new En(q(t)),this.lenDecoder=new En(q(t))}readLeftID(){return new me(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new me(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ye(this.restDecoder)}readBuf(){return q(this.restDecoder)}readJSON(){return Ye(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ie(s,t[0].id.clock);const r=St(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{j(t,i)>r&&s.set(i,r)}),qn(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),Ot(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ea(e,t.clients.get(r),r,i)})},na=(e,t)=>{const n=tt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=Ot(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new Qi,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(k=>k!==p)}s.length=0};for(;;){if(u.constructor!==at){const p=bt(h,u.id.client,()=>j(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const k=n.get(y)||{refs:[],i:0};if(k.refs.length===k.i)a(y,j(t,y)),d();else{u=k.refs[k.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new ne;return Zs(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ra=(e,t)=>Zs(e,t.doc.store,t.beforeState),ia=(e,t,n,s=new De(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=na(s,o),a=sa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=On([u.update,a.update])}}else l.pendingStructs=a;const h=$r(s,r,l);if(l.pendingDs){const d=new De(Wt(l.pendingDs));E(d.restDecoder);const f=$r(d,r,l);h&&f?l.pendingDs=On([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Ji(r.doc,d)}},n,!1),Ji=(e,t,n,s=De)=>{const r=Wt(t);ia(r,e,n,new s(r))},Wi=(e,t,n)=>Ji(e,t,n,ji),oa=(e,t,n=new Map)=>{Zs(e,t.store,n),Re(e,Zc(t.store))},la=(e,t=new Uint8Array([0]),n=new ne)=>{const s=zi(t);oa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ia(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===nn)return Da(r.map((i,o)=>o===0?i:xa(i)));if(n.constructor===ne)return On(r)}return r[0]},Yi=(e,t)=>la(e,t,new nn),ca=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sca(new Vi(Wt(e))),Gi=(e,t)=>(_(e.restEncoder,t.size),Ot(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),aa=(e,t)=>Gi(e,qn(t.store)),ha=(e,t=new Pi)=>(e instanceof Map?Gi(t,e):aa(t,e),t.toUint8Array()),ua=e=>ha(e,new Hi);class fa{constructor(){this.l=[]}}const Fr=()=>new fa,Br=(e,t)=>e.l.push(t),Vr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},qi=(e,t,n)=>Js(e.l,[t,n]);class me{constructor(t,n){this.client=t,this.clock=n}}const ge=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,C=(e,t)=>new me(e,t),Xi=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw rt()},Ln=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Ki{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const Kh=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},da=e=>new Ki(e.type==null?null:C(e.type.client,e.type.clock),e.tname??null,e.item==null?null:C(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ga{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const pa=(e,t,n=0)=>new ga(e,t,n),wn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=Xi(e):s=C(e._item.id.client,e._item.id.clock),new Ki(s,r,t,n)},Qh=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return wn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return wn(e,C(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return wn(e,s.lastId,n);s=s.right}return wn(e,null,n)},wa=(e,t)=>{const n=ye(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},ma=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(j(s,r.client)<=r.clock)return null;const u=n?Ls(s,r):wa(s,r),h=u.item;if(!(h instanceof M))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(j(s,i.client)<=i.clock)return null;const{item:u}=n?Ls(s,i):{item:ye(s,i)};if(u instanceof M&&u.content instanceof Et)c=u.content.type;else return null}else throw rt();l>=0?a=c._length:a=0}return pa(c,a,e.assoc)},Zh=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ge(e.item,t.item)&&ge(e.type,t.type)&&e.assoc===t.assoc,fe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!en(t.ds,e.id),Is=(e,t)=>{const n=bt(e.meta,Is,Ht),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class Qi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const qn=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},j=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},Zi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw rt()}n.push(t)},St=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=dt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[St(n,t.clock)]},ye=ya,Ts=(e,t,n)=>{const s=St(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ts(e,n,t.clock)]},jr=(e,t,n)=>{const s=t.clients.get(n.client),r=St(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ct&&s.splice(r+1,0,$n(e,i,n.clock-i.id.clock+1)),i},Sa=(e,t,n)=>{const s=e.clients.get(t.id.client);s[St(s,t.id.clock)]=n},to=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ts(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Wo(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(Ks(t.deleteSet),ra(e,t),Re(e,t.deleteSet),!0),Pr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&bt(e.changed,t,Ht).add(n)},Cn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},ba=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=St(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ns(r.length-1,1+St(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+Cn(r,c)}})},eo=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{qi(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Pa(n)})}),Js(l,[])}finally{s.gc&&ba(i,r,s.gcFilter),_a(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ie(St(f,d),1);for(let y=f.length-1;y>=p;)y-=1+Cn(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=St(f,d);p+11||p>0&&Cn(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(qc(Xs,Ri,"[yjs] ",Ui,Mi,"Changed the client-id because another client seems to be using it."),s.clientID=Bi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new nn;Hr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new ne;Hr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):eo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new ka(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&eo(r,0)}}return o};class Ea{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Jr=(e,t,n)=>{Ce(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||Ln(r,s))&&lr(s,!1)})},Wr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Ce(l,a.insertions,f=>{if(f instanceof M){if(f.redone!==null){let{item:p,diff:y}=Ls(c,f.id);y>0&&(p=Z(l,C(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||Ln(p,f))&&h.push(f)}}),Ce(l,a.deletions,f=>{f instanceof M&&i.some(p=>p===l.doc||Ln(p,f))&&!en(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=ko(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class tu extends vs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=be(t)?t[0].doc:t instanceof oe?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(k=>c.changedParentTypes.has(k)||k===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new Oe;c.afterState.forEach((k,w)=>{const b=c.beforeState.get(w)||0,O=k-b;O>0&&qe(d,w,b,O)});const f=Pt();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const k=h[h.length-1];k.deletions=As([k.deletions,c.deleteSet]),k.insertions=As([k.insertions,d])}else h.push(new Ea(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Ce(c,c.deleteSet,k=>{k instanceof M&&this.scope.some(w=>w===c.doc||Ln(w,k))&&lr(k,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=be(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ni("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Jr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Jr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Wr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Wr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ca(e){const t=E(e.restDecoder);for(let n=0;nOn(e,ji,nn),Aa=(e,t)=>{if(e.constructor===ct){const{client:n,clock:s}=e.id;return new ct(C(n,s+t),e.length-t)}else if(e.constructor===at){const{client:n,clock:s}=e.id;return new at(C(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(C(s,r+t),null,C(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},On=(e,t=De,n=ne)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Wt(u)));let r=s.map(u=>new tr(u,!0)),i=null;const o=new n,l=new er(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===at?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Ft(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===at?i.struct.length-=p:d=Aa(d,p)),i.struct.mergeWith(d)||(Ft(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==at;d=u.next())Ft(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Ft(l,i.struct,i.offset),i=null),nr(l);const c=s.map(u=>Qs(u)),a=As(c);return Re(o,a),o.toUint8Array()},Ia=(e,t,n=De,s=ne)=>{const r=zi(t),i=new s,o=new er(i),l=new n(Wt(e)),c=new tr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===at){c.next();continue}if(u.id.clock+u.length>d)for(Ft(o,u,ie(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Ft(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}nr(o);const a=Qs(l);return Re(i,a),i.toUint8Array()},no=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:F(e.encoder.restEncoder)}),e.encoder.restEncoder=X(),e.written=0)},Ft=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&no(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},nr=e=>{no(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Wt(e)),i=new tr(r,!1),o=new s,l=new er(o);for(let a=i.curr;a!==null;a=i.next())Ft(l,t(a),0);nr(l);const c=Qs(r);return Re(o,c),o.toUint8Array()},xa=e=>Ta(e,Fl,De,nn),Yr="You must not compute changes after the event-handler fired.";class Xn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=La(this.currentTarget,this.target))}deletes(t){return en(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw yt(Yr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ls(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ls(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ls(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw yt(Yr);const n=this.target,s=Ht(),r=Ht(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const La=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},K=()=>{Ni("Invalid access: Add Yjs type to a document before reading data.")},so=80;let sr=0;class Oa{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=sr++}}const Ra=e=>{e.timestamp=sr++},ro=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=sr++},Ua=(e,t,n)=>{if(e.length>=so){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>bn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&bn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ie(t,r.index+n))}},Qn=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;bt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;qi(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Fr(),this._dEH=Fr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ft()}clone(){throw ft()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Br(this._eH,t)}observeDeep(t){Br(this._dEH,t)}unobserve(t){Vr(this._eH,t)}unobserveDeep(t){Vr(this._dEH,t)}toJSON(){}}const io=(e,t,n)=>{e.doc??K(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},oo=e=>{e.doc??K();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??K();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return Ke(e,(s,r)=>{n.push(t(s,r,e))}),n},Ma=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},co=(e,t)=>{e.doc??K();const n=Kn(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new re(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new sn(new Uint8Array(h))),r.integrate(e,0);break;case oe:r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new rn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new M(C(o,j(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Et(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ao=()=>yt("Length exceeded!"),ho=(e,t,n,s)=>{if(n>t._length)throw ao();if(n===0)return t._searchMarker&&Xe(t._searchMarker,n,s.length),Rn(e,t,null,s);const r=n,i=Kn(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Rn(e,t,r,n)},uo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=Kn(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw ao();t._searchMarker&&Xe(t._searchMarker,r,-i+s)},Un=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},rr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new re([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new re([s]);break;case Uint8Array:l=new sn(s);break;case oe:l=new rn(s);break;default:if(s instanceof z)l=new Et(s);else throw new Error("Unexpected content type")}new M(C(o,j(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},ir=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},fo=e=>{const t={};return e.doc??K(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},go=(e,t)=>{e.doc??K();const n=e._map.get(t);return n!==void 0&&!n.deleted},Na=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&fe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},mn=e=>(e.doc??K(),Xc(e._map.entries(),t=>!t[1].deleted));class $a extends Xn{}class Se extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Se;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Se}clone(){const t=new Se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._length}_callObserver(t,n){super._callObserver(t,n),Qn(this,t,new $a(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{va(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{uo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return co(this,t)}toArray(){return oo(this)}slice(t=0,n=this.length){return io(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return lo(this,t)}forEach(t){Ke(this,t)}[Symbol.iterator](){return Ma(this)}_write(t){t.writeTypeRef(ch)}}const Fa=e=>new Se;class Ba extends Xn{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Ae extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Ae}clone(){const t=new Ae;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){Qn(this,t,new Ba(this,t,n))}toJSON(){this.doc??K();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...mn(this)].length}keys(){return gs(mn(this),t=>t[0])}values(){return gs(mn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return gs(mn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??K(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return ir(this,t)}has(t){return go(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Un(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ah)}}const Va=e=>new Ae,Bt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Nl(e,t);class xs{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&rt(),this.right.content.constructor===J?this.right.deleted||Ue(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===J?t.right.deleted||Ue(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?Kn(t,n):null;if(i){const o=new xs(i.p.left,i.p,i.index,r);return zr(e,o,n-i.index)}else{const o=new xs(null,t._start,0,r);return zr(e,o,n)}},po=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===J&&Bt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new M(C(i,j(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new J(l,o));u.integrate(e,0),n.right=u,n.forward()})},Ue=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},wo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===J&&Bt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},mo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Bt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new M(C(i,j(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new J(l,c)),n.right.integrate(e,0),n.forward()}}return o},ps=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;wo(n,r);const l=mo(e,t,n,r),c=s.constructor===String?new kt(s):s instanceof z?new Et(s):new le(s);let{left:a,right:u,index:h}=n;t._searchMarker&&Xe(t._searchMarker,n.index,c.getLength()),u=new M(C(o,j(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),po(e,t,n,l)},Gr=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;wo(n,r);const l=mo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===J));){if(!n.right.deleted)switch(n.right.content.constructor){case J:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Bt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new M(C(o,j(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new kt(c)),n.right.integrate(e,0),n.forward()}po(e,t,n,l)},yo=(e,t,n,s,r)=>{let i=t;const o=tt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===J){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===J){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&Ue(r,a)}}t=t.right}return l},ja=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===J){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ha=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=tt();const o=ks(i);for(;r;)r.deleted===!1&&(r.content.constructor===J?Ue(o,r.content):(t+=yo(n,s,r,i,o),i=ks(o),s=r)),r=r.right}),t},Pa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&to(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===J&&o.constructor!==ct&&t.add(o.parent)})}U(n,s=>{Ce(e,e.deleteSet,r=>{if(r instanceof ct||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===J?t.add(i):ja(s,r)});for(const r of t)Ha(r)})},qr=(e,t,n)=>{const s=n,r=ks(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Et:case le:case kt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},vl(c)||(f.attributes=Ol({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case Et:case le:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case kt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case J:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Bt(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Bt(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Bt(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Bt(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),Ue(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ie extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??K(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Ie}clone(){const t=new Ie;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Ja(this,t,n);Qn(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??K();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===kt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new xs(null,this._start,0,new Map);for(let i=0;i0)&&ps(s,this,r,l,o.attributes||{})}else o.retain!==void 0?Gr(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&qr(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??K();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(fe(c,t)||n!==void 0&&fe(c,n))switch(c.content.constructor){case kt:{const h=i.get("ychange");t!==void 0&&!fe(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!fe(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case Et:case le:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case J:fe(c,t)&&(a(),Ue(i,c.content));break}c=c.right}a()};return t||n?U(o,h=>{t&&Is(h,t),n&&Is(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),ps(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!s);ps(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{qr(r,yn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=yn(i,this,t,!1);o.right!==null&&Gr(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return ir(this,t)}getAttributes(){return fo(this)}_write(t){t.writeTypeRef(hh)}}const Wa=e=>new Ie;class ws{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??K()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Te||n.constructor===se)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class se extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new se}clone(){const t=new se;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??K(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new ws(this,t)}querySelector(t){t=t.toUpperCase();const s=new ws(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Ot(new ws(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){Qn(this,t,new Ga(this,n,t))}toString(){return lo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),Ke(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{ho(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Rn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw yt("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{uo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return oo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return co(this,t)}slice(t=0,n=this.length){return io(this,t,n)}forEach(t){Ke(this,t)}_write(t){t.writeTypeRef(fh)}}const Ya=e=>new se;class Te extends se{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Te(this.nodeName)}clone(){const t=new Te(this.nodeName),n=this.getAttributes();return Ul(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Un(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{rr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return ir(this,t)}hasAttribute(t){return go(this,t)}getAttributes(t){return t?Na(this,t):fo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return Ke(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(uh),t.writeKey(this.nodeName)}}const za=e=>new Te(e.readKey());class Ga extends Xn{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Mn extends Ae{constructor(t){super(),this.hookName=t}_copy(){return new Mn(this.hookName)}clone(){const t=new Mn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(dh),t.writeKey(this.hookName)}}const qa=e=>new Mn(e.readKey());class vn extends Ie{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new vn}clone(){const t=new vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(gh)}}const Xa=e=>new vn;class or{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ft()}mergeWith(t){return!1}write(t,n,s){throw ft()}integrate(t,n){throw ft()}}const Ka=0;class ct extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),Zi(t.doc.store,this)}write(t,n){t.writeInfo(Ka),t.writeLen(this.length-n)}getMissing(t,n){return null}}class sn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new sn(this.content)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const Qa=e=>new sn(e.readBuf());class Qe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Qe(this.len)}splice(t){const n=new Qe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){qe(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const Za=e=>new Qe(e.readLen()),So=(e,t)=>new oe({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class rn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new rn(So(this.doc.guid,this.opts))}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const th=e=>new rn(So(e.readString(),e.readAny()));class le{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new le(this.embed)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const eh=e=>new le(e.readJSON());class J{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new J(this.key,this.value)}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const nh=e=>new J(e.readKey(),e.readJSON());class Nn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Nn(this.arr)}splice(t){const n=new Nn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const oh=e=>new kt(e.readString()),lh=[Fa,Va,Wa,za,Ya,qa,Xa],ch=0,ah=1,hh=2,uh=3,fh=4,dh=5,gh=6;class Et{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Et(this.type._copy())}splice(t){throw ft()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const ph=e=>new Et(lh[e.readTypeRef()](e)),Ls=(e,t)=>{let n=t,s=0,r;do s>0&&(n=C(n.client,n.clock+s)),r=ye(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},lr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},$n=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(C(s,r+n),t,C(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=C(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},Xr=(e,t)=>Ms(e,n=>en(n.deletions,t)),ko=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return Z(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||ko(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=Z(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:Z(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||en(s,h.right.id)||Xr(i.undoStack,h.right.id)||Xr(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Z(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=j(l,c),y=C(c,p),k=new M(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,lr(k,!0),k.integrate(e,0),k};class M extends or{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Dr:0}set marker(t){(this.info&as)>0!==t&&(this.info^=as)}get marker(){return(this.info&as)>0}get keep(){return(this.info&Cr)>0}set keep(t){this.keep!==t&&(this.info^=Cr)}get countable(){return(this.info&Dr)>0}get deleted(){return(this.info&cs)>0}set deleted(t){this.deleted!==t&&(this.info^=cs)}markDeleted(){this.info|=cs}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=j(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=j(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===me&&this.id.client!==this.parent.client&&this.parent.clock>=j(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=jr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Z(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ct||this.right&&this.right.constructor===ct)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===me){const s=ye(n,this.parent);s.constructor===ct?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=jr(t,t.doc.store,C(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ge(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),qe(t.deleteSet,this.id.client,this.id.clock,this.length),Pr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw rt();this.content.gc(t),n?Sa(t,this,new ct(this.id,this.length)):this.content=new Qe(this.length)}write(t,n){const s=n>0?C(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Vn|(s===null?0:st)|(r===null?0:Lt)|(i===null?0:Pe);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=Xi(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===me?(t.writeParentInfo(!1),t.writeLeftID(l)):rt();i!==null&&t.writeString(i)}this.content.write(t,n)}}const bo=(e,t)=>wh[t&Vn](e),wh=[()=>{rt()},Za,sh,Qa,oh,eh,nh,ph,ih,th,()=>{rt()}],mh=10;class at extends or{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){rt()}write(t,n){t.writeInfo(mh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const _o=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Eo="__ $YJS$ __";_o[Eo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");_o[Eo]=!0;const Co=new Map;class yh{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:Kl(n.newValue||"")}),Tl(this._onChange)}postMessage(t){ci.setItem(this.room,Xl(Wl(t)))}close(){xl(this._onChange)}}const Sh=typeof BroadcastChannel>"u"?yh:BroadcastChannel,cr=e=>bt(Co,e,()=>{const t=Ht(),n=new Sh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),kh=(e,t)=>(cr(e).subs.add(t),t),bh=(e,t)=>{const n=cr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Co.delete(e)),s},de=(e,t,n=null)=>{const s=cr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Do=0,ar=1,Ao=2,Os=(e,t)=>{_(e,Do);const n=ua(t);V(e,n)},Io=(e,t,n)=>{_(e,ar),V(e,Yi(t,n))},_h=(e,t,n)=>Io(t,n,q(e)),To=(e,t,n,s)=>{try{Wi(t,q(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Eh=(e,t)=>{_(e,Ao),V(e,t)},Ch=To,Dh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Do:_h(e,t,n);break;case ar:To(e,n,s,r);break;case Ao:Ch(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ah=0,Ih=(e,t,n)=>{E(e)===Ah&&n(t,Vt(e))},ms=3e4;class xo extends Go{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Pt();this.getLocalState()!==null&&ms/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&ms<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&hr(this,s,"timeout")},dt(ms/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Pt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),pe(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const hr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},He=(e,t,n=e.states)=>{const s=t.length,r=X();_(r,s);for(let i=0;i{const s=Wt(t),r=Pt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},xh=e=>Ml(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),Qt=0,Lo=3,ke=1,Lh=2,on=[];on[Qt]=(e,t,n,s,r)=>{_(e,Qt);const i=Dh(t,e,n.doc,n);s&&i===ar&&!n.synced&&(n.synced=!0)};on[Lo]=(e,t,n,s,r)=>{_(e,ke),V(e,He(n.awareness,Array.from(n.awareness.getStates().keys())))};on[ke]=(e,t,n,s,r)=>{Th(n.awareness,q(t),n)};on[Lh]=(e,t,n,s,r)=>{Ih(t,n.doc,(i,o)=>Oh(n,o))};const Kr=3e4,Oh=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),Oo=(e,t,n)=>{const s=Wt(t),r=X(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Rh=e=>!(e.code>=4400&&e.code<4500),Rs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,hr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Ro,Ns(qo(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Ro=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Pt();const s=Oo(e,new Uint8Array(n.data),!0);$s(s)>1&&t.send(F(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Rs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Pt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=X();if(_(n,Qt),Os(n,e.doc),t.send(F(n)),e.awareness.getLocalState()!==null){const s=X();_(s,ke),V(s,He(e.awareness,[e.doc.clientID])),t.send(F(s))}},e.emit("status",[{status:"connecting"}])}},ys=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&de(e.bcChannel,t,e)};class Uh extends vs{constructor(t,n,s,{connect:r=!0,awareness:i=new xo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Rh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=on.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=X();_(f,Qt),Os(f,s),this.ws.send(F(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=Oo(this,new Uint8Array(f),!1);$s(y)>1&&de(this.bcChannel,F(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=X();_(y,Qt),Eh(y,f),ys(this,F(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},k)=>{const w=f.concat(p).concat(y),b=X();_(b,ke),V(b,He(i,w)),ys(this,F(b))},this._exitHandler=()=>{hr(this.awareness,[s.clientID],"app closed")},Jt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Kr{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=ma(da(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Uh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},vh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Yi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===Qr||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,O=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let I;w===0?I=0:L===-w||L!==w&&b[L-1+w-1]=r&&N>=i){u=w;break}}a.push(O)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],O=d-f,L=O===-w||O!==w&&b[O-1+w-1]B&&f>ht;)d--,f--,h.push(d,f);d=I,f=N}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,k=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],O=h[w+1];(b>y||O>k)&&p.push({aS:n+y,aE:n+b,bS:n+k,bE:n+O}),y=b+1,k=O+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` -`)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Vh(e,t)<=0?e+t:t+e:null}function Bn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=wt(e,s),l=wt(t,s),c=wt(n,s),a=mt(o,i),u=[...xe(a,mt(l,i)).map(k=>({h:k,toks:l,side:0})),...xe(a,mt(c,i)).map(k=>({h:k,toks:c,side:1}))];u.sort((k,w)=>k.h.aS-w.h.aS||k.h.aE-w.h.aE||k.side-w.side);const h=(k,w,b)=>k.slice(w,b).join(""),d=(k,w,b,O)=>{let L="",I=b;for(const N of k)N.side===w&&(L+=h(o,I,N.h.aS)+h(N.toks,N.h.bS,N.h.bE),I=N.h.aE);return L+h(o,I,O)};let f="",p=0,y=0;for(;yB.side)).size===1){f+=d(k,k[0].side,w,b);continue}const L=d(k,0,w,b),I=d(k,1,w,b);if(L===I){f+=L;continue}if(w===b){const B=jh(L,I,s!==Ss,o.length===0);if(B===null){if(!r)return null;f+=I;continue}f+=B;continue}if(s===Ss)return null;const N=s===Fn?Bn(h(o,w,b),L,I,Ss):Bn(h(o,w,b),L,I,s+1,r);if(N===null){if(!r)return null;f+=I;continue}f+=N}return f+h(o,p,o.length)}const Zt=e=>e===""||e.endsWith(` -`)?e:e+` -`;function Uo(e,t,n,s){let r=t.endsWith(` -`);return r===e.endsWith(` -`)&&(r=n.endsWith(` -`)),s===""||r===s.endsWith(` -`)?s:r?s+` -`:s.slice(0,-1)}function he(e,t,n){const s=Bn(Zt(e),Zt(t),Zt(n),jt);return s===null?{ok:!1}:{ok:!0,text:Uo(e,t,n,s)}}function eu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Bn(Zt(e),Zt(t),Zt(n),jt,!0)??Zt(n);return Uo(e,t,n,s)}function Zr(e,t){if(e===t)return[];const n=[],s=new Map,r=wt(e,jt),i=wt(t,jt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;O>=55296&&O<=56319&&w--;const L=b>0?p.charCodeAt(p.length-b):0;L>=56320&&L<=57343&&b--,k+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:k,deleteCount:p.length,insertText:y}),a=d,u=f}}function Sn(e,t,n){const s=new Map,r=mt(wt(t,jt),s),i=xe(mt(wt(e,jt),s),r),o=xe(r,mt(wt(n,jt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function kn(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ti=700,ue=[2e3,4e3,8e3,15e3],ei=2e3,Ph=4,Jh=64,Wh=8,Yh=32e3,zh=32;function nu(e){let t=e.seed,n=e.baseSha;const s=(g,S)=>{t=g,r=S,It(S);const m=Ut.lastIndexOf(g);m>=0?Ut.splice(0,m+1):Ut.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const S=[];for(let m=g;m!==null&&S.length<4;m=m.prev)m.sent!==m.from&&!S.includes(m.sent)&&S.push(m.sent);return S.length?S:void 0},o=(g,S=Ct)=>{const m=i(S);return r&&r===n&&t.length>Yh?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,k=!1,w=null,b=null,O="",L=0;const I=(g=Date.now())=>{const S=Math.max(g,L+1e3);return L=S,Ho(e.path,e.who||"browser",new Date(S))},N=new Map;let B=0,ht=!1,it=null,Yt=0,Zn=!1,Ct=null,zt=!1;const Ut=[],ur=g=>{Ut.at(-1)!==g&&(Ut.push(g),Ut.length>zh&&Ut.shift())};let Dt=!1,Me=null,Gt=0;const ve=()=>{Dt=!1,Me=null},ts=g=>{Gt===g&&ve()};let et=0,ut=0,ln=null,qt=null,es=!1,At=null,Ne=!1,Xt=null,ot=null;const $=g=>e.onState?.(g),cn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Mt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let an=null,ns=0;const $e=()=>{clearTimeout(an??void 0),an=null},hn=g=>{if(!(g instanceof nt?g.status>=500||g.status===429:!0)||h||a)return;$e();const m=ue[Math.min(ns,ue.length-1)];ns++,an=setTimeout(()=>{an=null,!h&&!a&&Fe()},m)},fr=()=>{$e(),ns=0},un=()=>{$e(),Xt&&clearTimeout(Xt),Xt=setTimeout(()=>{Fe()},ti)},Kt=g=>{if(h)return f=g,!0;const S=H();if(S===g)return!0;const m=Zr(S,g);if(yr())return T.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Fe=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():Ve();if(qt)return es=!0,qt;const g=(async()=>{try{await Mo()}finally{qt=null}})();return qt=g,g},Mo=async()=>{let g=0;for(;;){if(es=!1,W||a||k)return;const S=H();if(S===t&&!zt){$("clean");return}if($("saving"),e.onWriting?.(),ht){if(w!==null&&b===S){if(await fn(S,O)==="stop")return;continue}ht=!1}const m=l||c?await vo(S):await $o(S);if(m==="stop")return;if(m==="rebased"){if(++g>Ph){await fn(H(),n??"");return}continue}if(!es){$(H()===t&&!zt?"clean":"dirty");return}}};let vt=!1;const vo=async g=>{At=g,Ne=!1;let S;try{S=await gn(cn(e.path),g,n,vt)}catch(m){return At=null,m instanceof nt&&m.status===422&&kn(m)?(vt=!1,Be(g),"stop"):m instanceof nt&&m.status===409?await dr(t,!1)?"rebased":"stop":($("error"),hn(m),"stop")}return At=null,vt=!1,fr(),S.merged?await dr(g,!0)?"rebased":"stop":(Ne||s(g,S.sha),e.onSaved?.(g),"done")},dr=async(g,S)=>{let m;try{m=await _r(Er(e.apiBase,e.path))}catch(v){return $("error"),H()!==t&&hn(v),!1}if(m.kind!=="text")return $("error"),!1;const A=H(),D=he(g,m.text,A);return!D.ok||!Kt(D.text)?(S&&It(m.sha),await fn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),S&&e.onSaved?.(m.text),!0)},No=g=>{if(g.update&&T.applyRemoteUpdate(g.update),typeof g.text!="string"){Ct=null;return}let S=null;for(let m=Ct;m!==null;m=m.prev)if(m.sent!==m.from&&Sn(m.from,m.sent,g.text)){S=m;break}if(Ct=null,S){zt=!0;const m=he(S.sent,g.text,H());m.ok&&Kt(m.text)?(t=g.text,r=void 0,It(g.sha)):(t=S.sent,r=void 0)}},$o=async g=>{At=g,Ne=!1;let S;const m=Ct;try{Ct={sent:g,from:t,prev:m},S=await $t(Mt,{...o(g,m),...vt?{confirm_shrink:!0}:{}})}catch(D){if(At=null,D instanceof nt&&[400,401,403,404,405,409,413].includes(D.status)&&(Ct=m),D instanceof nt&&(D.status===404||D.status===405))return c=!0,"rebased";if(D instanceof nt&&D.status===422&&kn(D))return vt=!1,Be(g),"stop";if(D instanceof nt&&D.status===409&&!a){let v={};try{v=JSON.parse(D.body)}catch{}const x=typeof v.text=="string"?v.text:null;if(x!==null){const R=he(t,x,H());if(R.ok&&Kt(R.text))return t=x,r=void 0,It(v.sha),"rebased"}return fn(H(),v.sha??"")}return $(a?"dirty":"error"),hn(D),"stop"}if(At=null,vt=!1,fr(),S.update&&T.applyRemoteUpdate(S.update),Ct=null,zt=!1,a)return"stop";const A=he(g,S.text,H());return A.ok&&Kt(A.text)&&(Ne||s(S.text,S.sha)),e.onSaved?.(S.text),"done"};let W=null;const Be=g=>{W||h||!e.onShrinkRefused||($("error"),W={was:pn(t),now:pn(g),confirm:async()=>{if(!h){if(a){$("saving"),e.onWriting?.();const S=et,m=Gt;try{const A=await $t(Mt,{update:T.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),ss(S,m);const D=!Dt&&ut>=et;$(D?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&ut{if(!h)try{const S=await _r(Er(e.apiBase,e.path));if(h||S.kind!=="text")return;if(s(S.text,S.sha),Kt(S.text),W=null,a&&!u){if(await ce(!1),h)return;$(ut>=et&&!Dt?"clean":"dirty");return}ut=et,d&&(d=0,e.onPending?.(0)),ve(),$("clean")}catch{$("error")}finally{W=null}}},e.onShrinkRefused(W))};let Nt=null;const Fo=()=>{Nt&&clearTimeout(Nt),Nt=setTimeout(()=>{const g=H();Po(pn(t),pn(g))&&Be(g)},ti)},gr=async(g,S,m=I())=>{const A=++B;let D=m;for(let v=1;;v++){const x=D;N.set(x,g);try{return await gn(cn(x),g,void 0,!1,!1,!1,!0),A===B&&!a&&(t=g,r=void 0,S&&(n=S),$("clean")),e.onConflictCopy?.(x),null}catch(R){if(R instanceof nt&&R.status===409&&v{const D=(v,x)=>{gn(cn(v),S,void 0,!1,!0,!0,!0).then(R=>A?.(R.parked??v),R=>{if(R instanceof nt&&R.status===409&&x{(w===null||b!==g)&&(w=I(),b=g);const m=w;O=S,ht=!0;const A=await gr(g,S,m);return h?"stop":A?(hn(A.err),"stop"):(ht=!1,b===g&&(w=null,b=null,O=""),H()!==g?"rebased":"stop")},ss=(g,S)=>{ut=Math.max(ut,g),ts(S),!(h||u)&&(d=et-ut,e.onPending?.(d))},Bo=()=>{h||u||W||ot||(ot=setTimeout(()=>{ot=null,!u&&!h&&ce(!1)},ei))},ce=g=>{if(clearTimeout(ot??void 0),ot=null,g){if(ut>=et)return Promise.resolve();const m=et,A=Gt;return $t(Mt,{update:T.encodeState(),base:n},!0).then(D=>{It(D.sha),ss(m,A)})}if(ln)return ln;const S=(async()=>{try{for(;!u&&!h&&!W&&ut{p=!1,w=null,b=null,Yt=0,clearTimeout(it??void 0),it=null,zt=!1,a=!0,ur(T.text.toString()),g?.(),Zn&&(Zn=!1,e.onReady(T))},Ve=async()=>{if(h||a||y||k)return;if(clearTimeout(it??void 0),it=null,Xt&&clearTimeout(Xt),Xt=null,qt){k=!0;try{for(;qt;)await qt}finally{k=!1}if(h||a)return;if(!u){H()!==t&&un();return}}if(Ct!==null&&!c){let x;k=!0;try{x=await $t(Mt,{peek:!0})}catch{if(h||a)return;const R=ue[Math.min(Yt,ue.length-1)];Yt++,it=setTimeout(()=>{it=null,Ve()},R);return}finally{k=!1}if(h||a)return;if(No(x),!u){(H()!==t||zt)&&un();return}}const g=e.soloText?.();if(g===void 0||g===t)return rs();const S=T.text.toString(),m=he(t,S,g);if(m.ok)return rs(()=>T.applySplices(Zr(S,m.text)));p=!0,(w===null||b!==g)&&(w=I(),b=g),y=!0;let A;try{A=await gr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,Ve()):rs(()=>{t=T.text.toString()});const D=A.err;if(D instanceof nt&&!(D.status>=500||D.status===429))return;const v=ue[Math.min(Yt,ue.length-1)];Yt++,it=setTimeout(()=>{it=null,Ve()},v)},T=new Mh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(ot&&clearTimeout(ot),ot=null,$e(),a||Ve(),ut=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(T):Zn=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),wr=(g,S)=>{const m=a?T.text.toString():null;if(m!==null&&ur(m),!T.isRemote(S?.origin)){if($("dirty"),a){Dt=!0,Me=m,Gt+=1,u||(et+=1,d=et-ut,e.onPending?.(d),clearTimeout(ot??void 0),ot=setTimeout(()=>{ot=null,!u&&!h&&ce(!1)},ei)),Fo();return}un()}};T.text.observe(wr);const mr=()=>e.onPeers?.(T.peerCount());T.awareness.on("change",mr),Nh(e.apiBase)?T.connect():queueMicrotask(()=>{h||(l=!0,T.stop(),e.onSolo())});const H=()=>f!==null?f:yr()?T.text.toString():e.soloText?.()??"",yr=()=>a||l&&T.text.length>0,It=g=>{g&&(n=g)},Vo=(g,S,m)=>{if(m?.held)return s(g,S),"same";if(g===t||g===At)return It(S),"same";const A=H();if(g===A)return s(g,S),a&&(ve(),$("clean")),"same";if(a){const v=t;return Ut.includes(g)||Sn(v,g,A)?(s(g,S),Dt&&(Me===null||g===Me||Sn(v,Me,g))&&(ve(),$("clean")),"same"):A!==t||T.peerCount()>0?"blocked":(s(g,S),Kt(g),ve(),"merged")}if(!T.text.length&&!e.soloApply)return"blocked";const D=he(t,g,A);return D.ok?(At!==null&&(Ne=!0),s(g,S),Kt(D.text),D.text!==g?un():At===null&&$("clean"),D.text===A?"same":"merged"):"blocked"};let dn=null;const jo=()=>{if(!a)return Fe();if(W||h)return Promise.resolve();if(!u)return d>0?ce(!1):Promise.resolve();if(!Dt)return Promise.resolve();if(dn)return dn;const g=Gt;$("saving");const S=(async()=>{try{const m=await $t(Mt,{update:T.encodeState()});if(h)return;m.update&&T.applyRemoteUpdate(m.update),s(m.text,m.sha),ts(g),$(Dt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof nt&&m.status===422&&kn(m)&&(clearTimeout(Nt??void 0),Nt=null,Be(H()),W))return;$(Dt?"dirty":"clean")}finally{dn=null}})();return dn=S,S};let Tt=null;const is=g=>()=>{Tt===g&&(Tt=null)},Sr=(g,S)=>{if(W)return;if(a){const x=!u&&d>0;if(!x&&!(u&&Dt))return;const R="room\0"+T.text.toString();if(Tt===R)return;Tt=R;const lt=Gt;(x?ce(!0):$t(Mt,{update:T.encodeState()},!0).then(os=>It(os.sha))).then(()=>ts(lt),is(R));return}if(p||ht){const x="park\0"+g;if(Tt===x)return;Tt=x;let R=w!==null&&b===g?w:null;for(const[lt,gt]of N)R===null&>===g&&(R=lt);R??=I(),pr(R,g,x);return}if(!g||g===t)return;const m="text\0"+g;if(Tt===m)return;if((l||c)&&!S){Fe();return}Tt=m;const A=t,D=x=>{if(!(x instanceof nt&&x.status===409))return is(m)();let R={};try{const gt=JSON.parse(x.body);gt&&typeof gt=="object"&&(R=gt)}catch{}if(typeof R.text=="string"&&(R.text===g||Sn(A,g,R.text)))return;ht=!0;let lt=w!==null&&b===g?w:null;for(const[gt,os]of N)lt===null&&os===g&&(lt=gt);lt??=I(),w=lt,b=g,pr(lt,g,m,gt=>{ht=!1,e.onConflictCopy?.(gt)})},v=x=>{x.parked&&e.onConflictCopy?.(x.parked)};l||c?gn(cn(e.path),g,n,vt,!0,!0).then(v,D):$t(Mt,{...o(g),park_on_conflict:!0},!0).then(v,D)},kr=()=>{h||Sr(H(),!0)},br=()=>{Tt=null};return typeof window<"u"&&(window.addEventListener("pagehide",kr),window.addEventListener("pageshow",br)),{collab:T,current:H,merge:Vo,rebase:It,saveNow:jo,askingShrink:()=>W!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",kr),window.removeEventListener("pageshow",br)),clearTimeout(Xt??void 0),clearTimeout(Nt??void 0),$e(),clearTimeout(it??void 0),it=null;const g=H();h=!0,f=g,W?e.onShrinkWithdrawn?.(W):Sr(g,!1),clearTimeout(ot??void 0),T.awareness.off("change",mr),T.text.unobserve(wr),T.destroy()}}}export{oe as D,ti as S,tu as U,Qh as a,da as b,ma as c,Zr as d,Zh as e,Ns as f,ie as g,qh as h,xt as i,eu as m,nu as o,Kh as r,Xh as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 3b198090..56b72fd4 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + From 8942b1bfe8b86e8fa09fb8e0e343b843fbbfce36 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:27:46 +0900 Subject: [PATCH 06/34] fix(webapp): validate .json/.jsonl three-way merges on the client --- architecture/webapp-frontend.md | 2 +- internal/webapp/frontend/src/lib/merge3.ts | 36 +++++ .../webapp/frontend/src/lib/sharedfile.ts | 21 +-- .../src/lib/sharedfile_restore.test.ts | 148 +++++++++++++++++- ...{Editor-Bf_MRt-m.js => Editor-CWQeqJPd.js} | 2 +- ...dit-eZmLVOyc.js => VisualEdit-CNasvd30.js} | 2 +- .../{index-ClgB4GHM.js => index-AIvST0b2.js} | 4 +- ...ile-C8ckGCkQ.js => sharedfile-BHUrOeP7.js} | 19 +-- internal/webapp/static/index.html | 2 +- 9 files changed, 207 insertions(+), 29 deletions(-) rename internal/webapp/static/assets/{Editor-Bf_MRt-m.js => Editor-CWQeqJPd.js} (99%) rename internal/webapp/static/assets/{VisualEdit-eZmLVOyc.js => VisualEdit-CNasvd30.js} (97%) rename internal/webapp/static/assets/{index-ClgB4GHM.js => index-AIvST0b2.js} (99%) rename internal/webapp/static/assets/{sharedfile-C8ckGCkQ.js => sharedfile-BHUrOeP7.js} (56%) diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index d5836ba9..96b0d1f6 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -189,7 +189,7 @@ classDiagram +sidebarSearch.ts useSidebarSearch setFilterQuery registerFilterResults +collab.ts CollabDoc peerCount isRemote onStalled encodeState applySplices applyRemoteUpdate (y-websocket to the hub-held document; stop only when there is no room route) +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once) - +merge3.ts merge3 merge3PreferRight diffSplices applySplices retainsChanges (TS port of internal/textmerge) + +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them) +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room) +sharedfile.ts rebase (the head sha moved because a co-editor saved) diff --git a/internal/webapp/frontend/src/lib/merge3.ts b/internal/webapp/frontend/src/lib/merge3.ts index 76b0449b..9d3fb7b9 100644 --- a/internal/webapp/frontend/src/lib/merge3.ts +++ b/internal/webapp/frontend/src/lib/merge3.ts @@ -312,6 +312,42 @@ export function merge3PreferRight(base: string, left: string, right: string): st return withTrailing(base, left, right, text); } +/* Whether a MERGED text may be written to `path` — the hub's + validMergedText (upload.go, syncer/merge.go): two valid JSON edits can + merge line by line into JSON that is not, and that merge is a conflict. + Extension compared case-insensitively, as Go's filepath.Ext lowered. */ +export function validMergedText(path: string, merged: string): boolean { + const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + const dot = name.lastIndexOf("."); + const ext = dot >= 0 ? name.slice(dot).toLowerCase() : ""; + const valid = (s: string) => { + try { + JSON.parse(s); + return true; + } catch { + return false; + } + }; + if (ext === ".json") return valid(merged); + if (ext === ".jsonl") { + for (const line of merged.split("\n")) { + const t = line.trim(); + if (t.length > 0 && !valid(t)) return false; + } + } + return true; +} + +/* merge3 for a file at `path`. Only a real merge — both sides moved, two + different ways — is held to validMergedText, as the hub holds it: a side + that alone changed the text is that side's own text (an editor mid-way + through typing JSON is not a conflict). */ +export function merge3ForPath(path: string, base: string, a: string, b: string): Merge3Result { + const res = merge3(base, a, b); + if (!res.ok || a === b || a === base || b === base) return res; + return validMergedText(path, res.text) ? res : { ok: false }; +} + /* The splices that turn `oldText` into `newText`, touching as little as possible: line hunks, refined to token hunks, trimmed to the characters that actually differ. Every untouched character keeps its identity in a diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index 83f25fad..91d266b8 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -1,6 +1,6 @@ import { CollabDoc, type CollabStatus } from "./collab"; import { hasCollabRoute } from "./collabroute"; -import { diffSplices, merge3, retainsChanges } from "./merge3"; +import { diffSplices, merge3ForPath, retainsChanges } from "./merge3"; import { HttpError, putText, syncCollab } from "../api/http"; import { conflictName } from "./conflict"; import { fetchBlobText, fileURLFor } from "../hooks/useBlob"; @@ -185,6 +185,9 @@ export type SharedFileOptions = { single-flight loop that rebases over other writers with merge3, and parks a conflict copy only for a genuine same-token conflict. */ export function openSharedFile(opts: SharedFileOptions): SharedFile { + // Every merge here is of this file: a .json/.jsonl merge that is not + // valid JSON is a conflict, as the hub's is. + const mergeForPath = (base: string, a: string, b: string) => merge3ForPath(opts.path, base, a, b); /* The text `base` names: the last version of the file this buffer is known to be built on. Every local change is (buffer − saved); every outside write is (next − saved). That is what makes a three-way merge possible. */ @@ -537,7 +540,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { return false; } const cur = current(); - const res = merge3(from, head.text, cur); + const res = mergeForPath(from, head.text, cur); if (!res.ok || !applyText(res.text)) { // The same words changed two different ways: genuinely contended. // Theirs is the file (it got there first); ours goes beside it. Only @@ -570,7 +573,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { if (landed) { roomNeedsFlush = true; // The room holds `sent`: what the buffer adds is only past it. - const res = merge3(landed.sent, peek.text, current()); + const res = mergeForPath(landed.sent, peek.text, current()); if (res.ok && applyText(res.text)) { saved = peek.text; savedSha = undefined; @@ -619,7 +622,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } const room = typeof theirs.text === "string" ? theirs.text : null; if (room !== null) { - const res = merge3(saved, room, current()); + const res = mergeForPath(saved, room, current()); if (res.ok && applyText(res.text)) { // Rebased onto the room: send the merge, as a diff against it. saved = room; @@ -649,7 +652,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { // Joined while this was out: the join merged the same buffer into the // shared document, which now holds the truth. if (hubHoldsIt) return "stop"; - const res = merge3(text, out.text, current()); + const res = mergeForPath(text, out.text, current()); // The buffer is now built on `out.text` even with typing past `text` in // it: that is the base the join and the next checkpoint diff against. if (res.ok && applyText(res.text)) { @@ -1022,7 +1025,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { const local = opts.soloText?.(); if (local === undefined || local === saved) return finishJoin(); const hub = collab.text.toString(); - const res = merge3(saved, hub, local); + const res = mergeForPath(saved, hub, local); if (res.ok) return finishJoin(() => collab.applySplices(diffSplices(hub, res.text))); pendingJoin = true; // One name for every attempt at the same text: a retry re-writes the same @@ -1222,7 +1225,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { write is (next − saved); both survive unless they changed the same words differently, and only then is this the caller's banner. */ if (!collab.text.length && !opts.soloApply) return "blocked"; - const res = merge3(saved, next, cur); + const res = mergeForPath(saved, next, cur); if (!res.ok) return "blocked"; if (inFlightSentText !== null) disturbed = true; adopt(next, nextSha); @@ -1387,7 +1390,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { if (typeof theirs.text === "string" && (theirs.text === text || retainsChanges(from, text, theirs.text))) { // Already in the hub's text: a page that lives on is built on it now. if (!gone && !hubHoldsIt) { - const res = merge3(text, theirs.text, current()); + const res = mergeForPath(text, theirs.text, current()); if (res.ok && applyText(res.text)) { saved = theirs.text; savedSha = undefined; @@ -1443,7 +1446,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { rebase(out.sha); return; } - const res = merge3(text, out.text, current()); + const res = mergeForPath(text, out.text, current()); if (res.ok && applyText(res.text)) { adopt(out.text, out.sha); if (current() === saved) setState("clean"); diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 8f237d81..90306cff 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -53,7 +53,7 @@ registerHooks({ const { CollabDoc } = await import("./collab.ts"); const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); const { parseConflict } = await import("./conflict.ts"); -const { merge3, merge3PreferRight } = await import("./merge3.ts"); +const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts"); /* toEqual's semantics: a property that is undefined is a property that is absent. Only plain objects and arrays are rebuilt; anything else (a @@ -613,12 +613,37 @@ test("merge3PreferRight lets only the colliding words take the patch", () => { assert.equal(merge3PreferRight("log\n", "log\nb\n", "log\na\n"), "log\na\nb\n"); }); +/* The hub's validMergedText, in the browser: line merges of two valid JSON + edits can be invalid JSON, and only a REAL merge is held to it. */ +test("validMergedText and merge3ForPath hold .json/.jsonl merges to valid JSON", () => { + // Two inserts at one anchor: a line merge, but not JSON. + same(merge3("[\n]\n", "[\n1\n]\n", "[\n2\n]\n"), { ok: true, text: "[\n1\n2\n]\n" }); + assert.equal(validMergedText("data.json", "[\n1\n2\n]\n"), false); + assert.equal(validMergedText("DIR/Data.JSON", "[\n1\n2\n]\n"), false); // extension case-insensitive + assert.equal(validMergedText("notes.md", "[\n1\n2\n]\n"), true); + assert.equal(validMergedText("data.json.bdrive-conflict-x-20261111T102030Z", "[\n1\n2\n]\n"), true); + same(merge3ForPath("data.json", "[\n]\n", "[\n1\n]\n", "[\n2\n]\n"), { ok: false }); + same(merge3ForPath("notes.md", "[\n]\n", "[\n1\n]\n", "[\n2\n]\n"), { ok: true, text: "[\n1\n2\n]\n" }); + // One side alone is its own text, valid or mid-typing: never a conflict. + same(merge3ForPath("data.json", "[\n]\n", "[\n]\n", "[\n2,\n"), { ok: true, text: "[\n2,\n" }); + + // JSONL: two valid lines at one anchor merge; a broken line does not. + same(merge3ForPath("events.jsonl", '{"x":0}\n', '{"x":0}\n{"a":1}\n', '{"x":0}\n{"b":2}\n'), { + ok: true, + text: '{"x":0}\n{"a":1}\n{"b":2}\n', + }); + assert.equal(validMergedText("events.jsonl", '{"a":1}\n\n \n{"b":2}'), true); + same(merge3ForPath("events.jsonl", '{"x":0}\n', '{"x":0}\n{"a":1}\n', '{"x":0}\n{"b":\n'), { ok: false }); + assert.equal(validMergedText("events.jsonl", '{"a":1}\n{"b":'), false); +}); + /* A staging checkpoint the room refuses 409 while newer typing waits behind it (its idle timer already fired into the in-flight loop). The refusal is settled for the buffer as it is NOW: the conflict copy carries the newer words, typing that lands while the copy is on the wire goes to the room next, and a tab closed mid-park parks the newest words keepalive. */ -function stagingConflictHarness() { +function stagingConflictHarness(o: { path?: string; seed?: string } = {}) { + const seed = o.seed ?? "v0\n"; const connect = mock.method(CollabDoc.prototype, "connect", () => {}); const posts: { base_text?: string; text?: string }[] = []; const puts: { url: string; body: string; keepalive?: boolean }[] = []; @@ -636,12 +661,12 @@ function stagingConflictHarness() { roomAnswers.push(d); return d.promise; }) as typeof fetch; - const state = { buffer: "v0\n" }; + const state = { buffer: seed }; const copies: string[] = []; const file = openSharedFile({ apiBase: "/api/p/proj/", - path: "notes.md", - seed: "v0\n", + path: o.path ?? "notes.md", + seed, baseSha: "sha-0", who: "tester", me: { name: "t", colour: "oklch(0.7 0.1 200)" }, @@ -705,6 +730,119 @@ test("staging 409 parks the NEWER buffer typed while the checkpoint was out, nev } }); +/* data.json: a staging checkpoint refused 409 by a room that inserted "1" + where the buffer inserted "2". The line merge "[1 2]" is not JSON, so the + buffer is parked beside the file — never rebased and re-sent as one. */ +test("staging 409 on a .json file parks an invalid JSON merge instead of sending it", async () => { + fakeTimers(); + const h = stagingConflictHarness({ path: "data.json", seed: "[\n]\n" }); + try { + h.state.buffer = "[\n2\n]\n"; + void h.file.saveNow(); + await advance(0); + same(h.posts, [{ base: "sha-0", base_text: "[\n]\n", text: "[\n2\n]\n" }]); + h.roomAnswers[0].resolve( + new Response(JSON.stringify({ error: "the same lines changed", sha: "sha-1", text: "[\n1\n]\n" }), { status: 409 }), + ); + await advance(0); + assert.equal(h.puts.length, 1); + assert.ok(h.puts[0].url.includes("data.json.bdrive-conflict-tester-")); + assert.equal(h.puts[0].body, "[\n2\n]\n"); + assert.equal(h.state.buffer, "[\n2\n]\n"); // never rebased into "[1 2]" + h.putAnswers[0].resolve(h.ok({ sha: "sha-copy" })); + await advance(60_000); + assert.equal(h.copies.length, 1); + assert.equal(h.posts.length, 1); + h.file.destroy(); + assert.ok(h.posts.every((p) => p.text !== "[\n1\n2\n]\n")); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + +test("solo 409 on a .json file parks an invalid JSON merge instead of writing it", async () => { + fakeTimers(); + try { + const puts: Array<{ url: string; body: string }> = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + const u = decodeURIComponent(String(url)); + const method = init?.method ?? "GET"; + if (method === "GET") return new Response("[\n1\n]\n", { status: 200, headers: { ETag: `"sha-1"` } }); + puts.push({ url: u, body: String(init?.body) }); + if (u.includes("bdrive-conflict")) return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 }); + return new Response(JSON.stringify({ error: "changed", sha: "sha-1" }), { status: 409 }); + }) as typeof fetch; + let buffer = "[\n]\n"; + let solo = false; + const states: string[] = []; + const copies: string[] = []; + const file = openSharedFile({ + apiBase: "/api/", + path: "data.json", + seed: "[\n]\n", + baseSha: "sha-0", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onState: (s) => states.push(s), + onConflictCopy: (c) => copies.push(c), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "[\n2\n]\n"; + await file.saveNow(); + assert.equal(puts.length, 2); + assert.ok(puts[0].url.includes("upload/content?path=data.json")); + assert.equal(puts[0].body, "[\n2\n]\n"); + assert.ok(puts[1].url.includes("data.json.bdrive-conflict-")); + assert.equal(puts[1].body, "[\n2\n]\n"); + assert.equal(buffer, "[\n2\n]\n"); + assert.equal(copies.length, 1); + assert.equal(states.at(-1), "clean"); + await advance(60_000); + assert.ok(puts.every((p) => p.body !== "[\n1\n2\n]\n")); + file.destroy(); + } finally { + realTimers(); + } +}); + +test("late join on a .json file parks an invalid JSON merge and takes the room's text", async () => { + fakeTimers(); + const h = stagingConflictHarness({ path: "data.json", seed: "[\n]\n" }); + try { + h.state.buffer = "[\n2\n]\n"; + const sock = { destroy() {} }; + const c = h.file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void }; + c.ws = sock; + h.file.collab.doc.transact(() => h.file.collab.text.insert(0, "[\n1\n]\n"), sock); + c.onStatus("live"); + c.onReady(); + await advance(0); + assert.equal(h.puts.length, 1); + assert.ok(h.puts[0].url.includes("data.json.bdrive-conflict-tester-")); + assert.equal(h.puts[0].body, "[\n2\n]\n"); + assert.equal(h.file.collab.text.toString(), "[\n1\n]\n"); // nothing spliced in + h.putAnswers[0].resolve(h.ok({ sha: "sha-copy" })); + await advance(0); + assert.equal(h.copies.length, 1); + assert.equal(h.file.collab.text.toString(), "[\n1\n]\n"); + assert.equal(h.file.current(), "[\n1\n]\n"); + same(h.posts, []); + h.file.destroy(); + } finally { + realTimers(); + h.connect.mock.restore(); + } +}); + test("staging 409 whose newer typing clears the clash is rebased onto the room, not parked", async () => { fakeTimers(); const h = stagingConflictHarness(); diff --git a/internal/webapp/static/assets/Editor-Bf_MRt-m.js b/internal/webapp/static/assets/Editor-CWQeqJPd.js similarity index 99% rename from internal/webapp/static/assets/Editor-Bf_MRt-m.js rename to internal/webapp/static/assets/Editor-CWQeqJPd.js index bd87c112..78244cdc 100644 --- a/internal/webapp/static/assets/Editor-Bf_MRt-m.js +++ b/internal/webapp/static/assets/Editor-CWQeqJPd.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-ClgB4GHM.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-C8ckGCkQ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-AIvST0b2.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BHUrOeP7.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-eZmLVOyc.js b/internal/webapp/static/assets/VisualEdit-CNasvd30.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-eZmLVOyc.js rename to internal/webapp/static/assets/VisualEdit-CNasvd30.js index 0b46581f..3e8ff9d3 100644 --- a/internal/webapp/static/assets/VisualEdit-eZmLVOyc.js +++ b/internal/webapp/static/assets/VisualEdit-CNasvd30.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-ClgB4GHM.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-C8ckGCkQ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-AIvST0b2.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-BHUrOeP7.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-ClgB4GHM.js b/internal/webapp/static/assets/index-AIvST0b2.js similarity index 99% rename from internal/webapp/static/assets/index-ClgB4GHM.js rename to internal/webapp/static/assets/index-AIvST0b2.js index 988eb8aa..a8b77b0a 100644 --- a/internal/webapp/static/assets/index-ClgB4GHM.js +++ b/internal/webapp/static/assets/index-AIvST0b2.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Bf_MRt-m.js","assets/sharedfile-C8ckGCkQ.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-eZmLVOyc.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CWQeqJPd.js","assets/sharedfile-BHUrOeP7.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CNasvd30.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Bf_MRt-m.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-eZmLVOyc.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CWQeqJPd.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CNasvd30.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!l,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&o.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&o.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,l.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,o as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-C8ckGCkQ.js b/internal/webapp/static/assets/sharedfile-BHUrOeP7.js similarity index 56% rename from internal/webapp/static/assets/sharedfile-C8ckGCkQ.js rename to internal/webapp/static/assets/sharedfile-BHUrOeP7.js index caae5eed..b5662aa9 100644 --- a/internal/webapp/static/assets/sharedfile-C8ckGCkQ.js +++ b/internal/webapp/static/assets/sharedfile-BHUrOeP7.js @@ -1,16 +1,17 @@ -import{H as et,h as Sn,i as Ht,k as zo,f as Tr,e as xr,l as bn,m as Go}from"./index-ClgB4GHM.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const mt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ci=e=>e!==0?e<0:1/e<0,Lr=1,Or=2,ps=4,ws=8,ze=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,Ln=Number.MAX_SAFE_INTEGER,Rr=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&mt(e)===e),ai=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Ur=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rGe.encode(e),hl=Ge?al:cl;let Ye=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ye&&Ye.decode(new Uint8Array).length===1&&(Ye=null);const ul=(e,t)=>Zo(t,()=>e).join("");class rn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new rn,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=mt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ci(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=mt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=mt(t/128)},Ls=new Uint8Array(3e4),dl=Ls.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),Mr=new DataView(new ArrayBuffer(4)),kl=e=>(Mr.setFloat32(0,e),Mr.getFloat32(0)===e),Xe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Nr=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new rn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Nr(this),this.count=1,this.s=t)}toUint8Array(){return Nr(this),F(this.encoder)}}const $r=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new rn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):($r(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return $r(this),F(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new rn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),F(t)}}const Et=e=>new Error(e),wt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},hi=Et("Unexpected end of array"),ui=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posLn)throw ui}throw hi},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posLn)throw ui}throw hi},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>Ye.decode(K(e)),Yt=Ye?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Yt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Fr extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ci(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=mt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ll=crypto.getRandomValues.bind(crypto),fi=()=>Ll(new Uint32Array(1))[0],Ol="10000000-1000-4000-8000"+-1e11,Rl=()=>Ol.replace(/[018]/g,e=>(e^fi()&15>>e/4).toString(16)),Gt=Date.now,Br=e=>new Promise(e);Promise.all.bind(Promise);const Vr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let di=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(di=localStorage,Gs=!1)}catch{}const gi=di,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Qe=Symbol("Equality"),pi=(e,t)=>e===t||!!e?.[Qe]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},On=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},on=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||On(e)===On(t)&&on(e,(n,s)=>(n!==void 0||Xs(t,s))&&pi(t[s],n)),Pl=Object.freeze,wi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&wi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Qe]!=null)return e[Qe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var mi={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",yi=typeof window<"u"&&typeof document<"u"&&!Xt;let St;const Yl=()=>{if(St===void 0)if(Xt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Ur(t,"-")}`,n),St.set(`-${Ur(t,"-")}`,n)}})):St=rt();return St},Os=e=>Yl().has(e),Rn=e=>Vr(Xt?mi[e.toUpperCase().replaceAll("-","_")]:gi.getItem(e)),ki=e=>Os("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Xt&&Wl(mi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Os("--no-colors")&&!ki("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Os("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),Si=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=Si(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=yi?Ql:Zl,sc=yi?tc:ec,rc=e=>{const t=Si(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),jr=e=>e.next()>=.5,ks=(e,t,n)=>mt(e.next()*(n+1-t)+t),bi=(e,t,n)=>mt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>bi(e,t,n),lc=e=>ai(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Qe]?pi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?on(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Qe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){wt()}get nullable(){return Me(this,Qn)}get optional(){return new Ci(this)}cast(t){return Hr(t,this),t}expect(t){return Hr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),_i=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ei=e=>{if(Ie.check(e))return[uc(e)];if(_i.check(e))return e.shape.map(t=>t+"");if(Ui.check(e))return["[+-]?\\d+.?\\d*"];if(Mi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ei).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ei).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Ci extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Ci);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):on(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Di extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&on(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ai=(e,t)=>new Di(e,t),kc=J(Di);class Ii extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&on(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ii(e);J(Ii);class Ti extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const xi=(...e)=>new Ti(e),bc=J(Ti),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>Ze(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Oi=()=>!0,Mn=G(Oi),xc=J(tr,e=>e.shape===Oi),nr=G(e=>typeof e=="bigint"),Lc=G(e=>e===nr),Ri=G(e=>typeof e=="symbol");G(e=>e===Ri);const Se=G(e=>typeof e=="number"),Ui=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Mi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Oc=G(e=>e===Kn),vi=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,vi,nr,Kn,Ri);(()=>{const e=xi(Mn),t=Ai(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const Ze=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=Ze(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(Ze));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Hr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ze(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),Ni=vc(Mn).if(Ui,(e,t)=>ks(t,Rr,Ln)).if(Mi,(e,t)=>cc(t)).if(Oc,(e,t)=>jr(t)).if(Lc,(e,t)=>BigInt(ks(t,Rr,Ln))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(jr(t))continue;r=r.shape}n[s]=Ni(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=bi(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,vi,nr,Kn,xi(Se),Ai(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;rNi(Ze(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n($i(e,Vc(t)),e),eu=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const nu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),$i=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Fi=Ft(),Bi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),Vi=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...ji(e)),Pi.forEach(t=>t.print(e))},Hi=(...e)=>{console.warn(...ji(e)),e.unshift(sr),Pi.forEach(t=>t.print(e))},Pi=zt(),Ji=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Ji(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Ji(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,a=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=mt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Wi=fi;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Wi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Br(a=>{this.on("load",()=>{this.isLoaded=!0,a(this)})});const c=()=>Br(a=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),a())};this.on("sync",u)});this.on("sync",a=>{a===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Yi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class qi extends Yi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Fr(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Fr(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((f,p)=>f-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=n.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=n.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const l=new ro,c=new Map,a=(f,p)=>{const y=c.get(f);(y==null||y>p)&&c.set(f,p)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const f of s){const p=f.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[f]),r=r.filter(S=>S!==p)}s.length=0};for(;;){if(u.constructor!==dt){const p=At(h,u.id.client,()=>P(t,u.id.client))-u.id.clock;if(p<0)s.push(u),a(u.id.client,u.id.clock-1),d();else{const y=u.getMissing(e,t);if(y!==null){s.push(u);const S=n.get(y)||{refs:[],i:0};if(S.refs.length===S.i)a(y,P(t,y)),d();else{u=S.refs[S.i++];continue}}else(p===0||p0)u=s.pop();else if(o!==null&&o.i0){const f=new oe;return or(f,l,new Map),_(f.restEncoder,0),{missing:c,update:f.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),a=aa(r,l,c),u=l.pendingStructs;if(u){for(const[d,f]of u.missing)if(ff)&&u.missing.set(d,f)}u.update=Nn([u.update,a.update])}}else l.pendingStructs=a;const h=Pr(s,r,l);if(l.pendingDs){const d=new xe(Kt(l.pendingDs));E(d.restDecoder);const f=Pr(d,r,l);h&&f?l.pendingDs=Nn([h,f]):l.pendingDs=h||f}else l.pendingDs=h;if(i){const d=l.pendingStructs.update;l.pendingStructs=null,Xi(r.doc,d)}},n,!1),Xi=(e,t,n,s=xe)=>{const r=Kt(t);ua(r,e,n,new s(r))},Ki=(e,t,n)=>Xi(e,t,n,qi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=Zi(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===cn)return Oa(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Qi=(e,t)=>da(e,t,new cn),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new Yi(Kt(e))),to=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>to(e,ts(t.store)),wa=(e,t=new Gi)=>(e instanceof Map?to(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new zi);class ya{constructor(){this.l=[]}}const Jr=()=>new ya,Wr=(e,t)=>e.l.push(t),Yr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},eo=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),no=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class so{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const su=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new so(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=no(e):s=D(e._item.id.client,e._item.id.clock),new so(s,r,t,n)},ru=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,a=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const u=n?$s(s,r):_a(s,r),h=u.item;if(!(h instanceof M))return null;if(c=h.parent,c._item===null||!c._item.deleted){a=h.deleted||!h.countable?0:u.diff+(l>=0?0:1);let d=h.left;for(;d!==null;)!d.deleted&&d.countable&&(a+=d.length),d=d.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:u}=n?$s(s,i):{item:_e(s,i)};if(u instanceof M&&u.content instanceof Tt)c=u.content.type;else return null}else throw at();l>=0?a=c._length:a=0}return ba(c,a,e.assoc)},iu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ln(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class ro{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},io=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=mt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},qr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ft&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},oo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Gr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,zt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let a=Ct(i,l.clock),u=i[a];a{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,a=r[c];c>0&&a.id.clock>=o.clock;a=r[c])c-=1+xn(r,c)}})},lo=(e,t)=>{if(tl.push(()=>{(a._item===null||!a._item.deleted)&&a._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,a)=>{a._dEH.l.length>0&&(a._item===null||!a._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=a,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),l.push(()=>{eo(a._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((u,h)=>{const d=n.beforeState.get(h)||0;if(d!==u){const f=r.clients.get(h),p=ae(Ct(f,d),1);for(let y=f.length-1;y>=p;)y-=1+xn(f,y)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,f=r.clients.get(h),p=Ct(f,d);p+11||p>0&&xn(f,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Fi,"[yjs] ",Bi,Vi,"Changed the client-id because another client seems to be using it."),s.clientID=Wi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const u=new cn;zr(u,n)&&s.emit("update",[u.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const u=new oe;zr(u,n)&&s.emit("updateV2",[u.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(u=>{u.clientID=s.clientID,u.collectionid==null&&(u.collectionid=s.collectionid),s.subdocs.add(u)}),a.forEach(u=>s.subdocs.delete(u)),s.emit("subdocs",[{loaded:c,added:l,removed:a},s,n]),a.forEach(u=>u.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):lo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&lo(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Xr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Kr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,a=t.pop(),u=new Set,h=[];let d=!1;Te(l,a.insertions,f=>{if(f instanceof M){if(f.redone!==null){let{item:p,diff:y}=$s(c,f.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),f=p}!f.deleted&&i.some(p=>p===l.doc||vn(p,f))&&h.push(f)}}),Te(l,a.deletions,f=>{f instanceof M&&i.some(p=>p===l.doc||vn(p,f))&&!ln(a.insertions,f.id)&&u.add(f)}),u.forEach(f=>{d=Ao(l,f,u,a.insertions,e.ignoreRemoteMapChanges,e)!==null||d});for(let f=h.length-1;f>=0;f--){const p=h[f];e.deleteFilter(p)&&(p.delete(l),d=!0)}e.currStackItem=d?a:null}l.changed.forEach((c,a)=>{c.has(null)&&a._searchMarker&&(a._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class ou extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(S=>c.changedParentTypes.has(S)||S===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const a=this.undoing,u=this.redoing,h=a?this.redoStack:this.undoStack;a?this.stopCapturing():u||this.clear(!1,!0);const d=new ve;c.afterState.forEach((S,w)=>{const b=c.beforeState.get(w)||0,O=S-b;O>0&&tn(d,w,b,O)});const f=Gt();let p=!1;if(this.lastChange>0&&f-this.lastChange0&&!a&&!u){const S=h[h.length-1];S.deletions=Us([S.deletions,c.deleteSet]),S.insertions=Us([S.insertions,d])}else h.push(new xa(c.deleteSet,d)),p=!0;!a&&!u&&(this.lastChange=f),Te(c,c.deleteSet,S=>{S instanceof M&&this.scope.some(w=>w===c.doc||vn(w,S))&&gr(S,!0)});const y=[{stackItem:h[h.length-1],origin:c.origin,type:a?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Hi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Xr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Xr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Kr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Kr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*La(e){const t=E(e.restDecoder);for(let n=0;nNn(e,qi,cn),Ra=(e,t)=>{if(e.constructor===ft){const{client:n,clock:s}=e.id;return new ft(D(n,s+t),e.length-t)}else if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(u=>new t(Kt(u)));let r=s.map(u=>new lr(u,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const p=d.curr.id.clock-f.curr.id.clock;return p===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===dt?1:-1:p}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const u=r[0],h=u.curr.id.client;if(i!==null){let d=u.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=u.next(),f=!0;if(d===null||d.id.client!==h||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:d,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===dt?i.struct.length-=p:d=Ra(d,p)),i.struct.mergeWith(d)||(Jt(l,i.struct,i.offset),i={struct:d,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==dt;d=u.next())Jt(l,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(u=>ir(u)),a=Us(c);return Ne(o,a),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=Zi(t),i=new s,o=new cr(i),l=new n(Kt(e)),c=new lr(l,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=r.get(h)||0;if(c.curr.constructor===dt){c.next();continue}if(u.id.clock+u.length>d)for(Jt(o,u,ae(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}ar(o);const a=ir(l);return Ne(i,a),i.toUint8Array()},co=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:F(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&co(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{co(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let a=i.curr;a!==null;a=i.next())Jt(l,t(a),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,cn),Qr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return ln(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Qr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Qr);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let a=n._start;a!==null;a=a.right)a.deleted?this.deletes(a)&&!this.adds(a)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=a.length,r.add(a)):this.adds(a)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(a.content.getContent()),s.add(a)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=a.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Hi("Invalid access: Add Yjs type to a document before reading data.")},ao=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},ho=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ao){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;eo(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Jr(),this._dEH=Jr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw wt()}clone(){throw wt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Wr(this._eH,t)}observeDeep(t){Wr(this._dEH,t)}unobserve(t){Yr(this._eH,t)}unobserveDeep(t){Yr(this._dEH,t)}toJSON(){}}const uo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},fo=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return nn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},po=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let a=[];const u=()=>{a.length>0&&(r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(a)),r.integrate(e,0),a=[])};s.forEach(h=>{if(h===null)a.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new an(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},wo=()=>Et("Length exceeded!"),mo=(e,t,n,s)=>{if(n>t._length)throw wo();if(n===0)return t._searchMarker&&en(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},yo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw wo();t._searchMarker&&en(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new an(s);break;case he:l=new hn(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new M(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},So=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return po(this,t)}toArray(){return fo(this)}slice(t=0,n=this.length){return uo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return go(this,t)}forEach(t){nn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return So(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return Zr(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return Zr(e,o,n)}},bo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,a=n.right,u=new M(D(i,P(r.store,i)),c,c&&c.lastId,a,a&&a.id,t,null,new W(l,o));u.integrate(e,0),n.right=u,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},_o=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Eo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],a=n.currentAttributes.get(l)??null;if(!Wt(a,c)){o.set(l,a);const{left:u,right:h}=n;n.right=new M(D(i,P(r.store,i)),u,u&&u.lastId,h,h&&h.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:a,right:u,index:h}=n;t._searchMarker&&en(t._searchMarker,n.index,c.getLength()),u=new M(D(o,P(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=h,n.forward(),bo(e,t,n,l)},ti=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:a}=n.right.content,u=r[c];if(u!==void 0){if(Wt(u,a))l.delete(c);else{if(s===0)break t;l.set(c,a)}n.right.delete(e)}else n.currentAttributes.set(c,a);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new M(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}bo(e,t,n,l)},Co=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const a=i.content;o.set(a.key,a)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const a=t.content;if(a.constructor===W){const{key:u,value:h}=a,d=s.get(u)??null;(o.get(u)!==a||d===h)&&(t.delete(e),l++,!c&&(r.get(u)??null)===h&&d!==h&&(d===null?r.delete(u):r.set(u,d))),!c&&!t.deleted&&$e(r,a)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Co(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&oo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==ft&&t.add(o.parent)})}U(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof ft||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ei=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let a="",u=0,h=0;const d=()=>{if(l!==null){let f=null;switch(l){case"delete":h>0&&(f={delete:h}),h=0;break;case"insert":(typeof a=="object"||a.length>0)&&(f={insert:a},r.size>0&&(f.attributes={},r.forEach((p,y)=>{p!==null&&(f.attributes[y]=p)}))),a="";break;case"retain":u>0&&(f={retain:u},jl(c)||(f.attributes=$l({},c))),u=0;break}f&&n.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(d(),l="insert",a=o.content.getContent()[0],d()):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(d(),l="insert"),a+=o.content.str):this.deletes(o)?(l!=="delete"&&(d(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(d(),l="retain"),u+=o.length);break;case W:{const{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(f)??null;Wt(y,p)?p!==null&&o.delete(s):(l==="retain"&&d(),Wt(p,i.get(f)??null)?delete c[f]:c[f]=p)}}else if(this.deletes(o)){i.set(f,p);const y=r.get(f)??null;Wt(y,p)||(l==="retain"&&d(),c[f]=y)}else if(!o.deleted){i.set(f,p);const y=c[f];y!==void 0&&(Wt(y,p)?y!==null&&o.delete(s):(l==="retain"&&d(),p===null?delete c[f]:c[f]=p))}o.deleted||(l==="insert"&&d(),$e(r,o.content));break}}o=o.right}for(d();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ti(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ei(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function a(){if(l.length>0){const h={};let d=!1;i.forEach((p,y)=>{d=!0,h[y]=p});const f={insert:l};d&&(f.attributes=h),r.push(f),l=""}}const u=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const h=i.get("ychange");t!==void 0&&!we(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(a(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(a(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(a(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{a();const h={insert:c.content.getContent()[0]};if(i.size>0){const d={};h.attributes=d,i.forEach((f,p)=>{d[p]=f})}r.push(h);break}case W:we(c,t)&&(a(),$e(i,c.content));break}c=c.right}a()};return t||n?U(o,h=>{t&&Ms(h,t),n&&Ms(h,n),u()},"cleanup"):u(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{ei(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ti(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Oe;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return go(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),nn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return fo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return po(this,t)}slice(t=0,n=this.length){return uo(this,t,n)}forEach(t){nn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return So(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return nn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Le{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw wt()}mergeWith(t){return!1}write(t,n,s){throw wt()}integrate(t,n){throw wt()}}const sh=0;class ft extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),io(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class an{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new an(this.content)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new an(e.readBuf());class sn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new sn(this.len)}splice(t){const n=new sn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){tn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new sn(e.readLen()),Do=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class hn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hn(Do(this.doc.guid,this.opts))}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new hn(Do(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw wt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ni=(e,t)=>js(e,n=>ln(n.deletions,t)),Ao=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,a=t.redone;if(a!==null)return st(e,a);let u=t.parent._item,h=null,d;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Ao(e,u,n,s,r,i)===null))return null;for(;u.redone!==null;)u=st(e,u.redone)}const f=u===null?t.parent:u.content.type;if(t.parentSub===null){for(h=t.left,d=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===u){h=w;break}h=h.left}for(;d!==null;){let w=d;for(;w!==null&&w.parent._item!==u;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===u){d=w;break}d=d.right}}else{if(d=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||ln(s,h.right.id)||ni(i.undoStack,h.right.id)||ni(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=st(e,h.redone);if(h&&h.right!==null)return null}else h=f._map.get(t.parentSub)||null;h!==null&&h.parent._item!==u&&(h=f._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),S=new M(y,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=y,gr(S,!0),S.integrate(e,0),S};class M extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Or:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Or)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=qr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ft||this.right&&this.right.constructor===ft)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===ft?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=qr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),tn(t.deleteSet,this.id.client,this.id.clock,this.length),Gr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new ft(this.id,this.length)):this.content=new sn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:ze);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const a=no(l);t.writeParentInfo(!0),t.writeString(a)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const Io=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},xo="__ $YJS$ __";To[xo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");To[xo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){gi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=zt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Oo=0,wr=1,Ro=2,Fs=(e,t)=>{_(e,Oo);const n=ma(t);H(e,n)},Uo=(e,t,n)=>{_(e,wr),H(e,Qi(t,n))},Th=(e,t,n)=>Uo(t,n,K(e)),Mo=(e,t,n,s)=>{try{Ki(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Ro),H(e,t)},Lh=Mo,Oh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Oo:Th(e,t,n);break;case wr:Mo(e,n,s,r);break;case Ro:Lh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Yt(e))},Cs=3e4;class vo extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Gt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},mt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Gt()});const o=[],l=[],c=[],a=[];t===null?a.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||a.length>0)&&this.emit("change",[{added:o,updated:c,removed:a},"local"]),this.emit("update",[{added:o,updated:l,removed:a},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},qe=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Kt(t),r=Gt(),i=[],o=[],l=[],c=[],a=E(s);for(let u=0;u0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,No=3,Ce=1,Nh=2,un=[];un[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Oh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};un[No]=(e,t,n,s,r)=>{_(e,Ce),H(e,qe(n.awareness,Array.from(n.awareness.getStates().keys())))};un[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};un[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const si=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),$o=(e,t,n)=>{const s=Kt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Fo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Fo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt();const s=$o(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(F(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(F(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,qe(e.awareness,[e.doc.clientID])),t.send(F(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new vo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:a=-1,maxBackoffTime:u=2500,disableBc:h=!1,shouldReconnect:d=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=u,this.shouldReconnect=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=un.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=Q();_(f,ne),Fs(f,s),this.ws.send(F(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const y=$o(this,new Uint8Array(f),!1);Js(y)>1&&me(this.bcChannel,F(y),this)}},this._updateHandler=(f,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,f),Ds(this,F(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:y},S)=>{const w=f.concat(p).concat(y),b=Q();_(b,Ce),H(b,qe(i,w)),Ds(this,F(b))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&si{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Qi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ri||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?a[w-1]:null,O=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let T;w===0?T=0:L===-w||L!==w&&b[L-1+w-1]=r&&$>=i){u=w;break}}a.push(O)}if(u<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let d=r,f=i;for(let w=u;w>0;w--){const b=a[w-1],O=d-f,L=O===-w||O!==w&&b[O-1+w-1]B&&f>gt;)d--,f--,h.push(d,f);d=T,f=$}for(;d>0&&f>0;)d--,f--,h.push(d,f);const p=[];let y=0,S=0;for(let w=h.length-2;w>=0;w-=2){const b=h[w],O=h[w+1];(b>y||O>S)&&p.push({aS:n+y,aE:n+b,bS:n+S,bE:n+O}),y=b+1,S=O+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +import{H as et,h as Sn,i as Ht,k as zo,f as Tr,e as xr,l as bn,m as Go}from"./index-AIvST0b2.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},Dt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){Dt(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const wt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ci=e=>e!==0?e<0:1/e<0,Or=1,Lr=2,ps=4,ws=8,ze=32,Nt=64,ct=128,Wn=31,Ts=63,se=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Rr=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&wt(e)===e),ai=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Ur=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rGe.encode(e),hl=Ge?al:cl;let Ye=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ye&&Ye.decode(new Uint8Array).length===1&&(Ye=null);const ul=(e,t)=>Zo(t,()=>e).join("");class rn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new rn,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>se;)q(e,ct|se&t),t=wt(t/128);q(e,se&t)},Ws=(e,t)=>{const n=ci(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=wt(t/64);t>0;)q(e,(t>se?ct:0)|se&t),t=wt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ce(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),Mr=new DataView(new ArrayBuffer(4)),kl=e=>(Mr.setFloat32(0,e),Mr.getFloat32(0)===e),Xe=(e,t)=>{switch(typeof t){case"string":q(e,119),re(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(Ce(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Nr=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new rn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Nr(this),this.count=1,this.s=t)}toUint8Array(){return Nr(this),B(this.encoder)}}const $r=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new rn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):($r(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new rn;return this.sarr.push(this.s),this.s="",re(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const _t=e=>new Error(e),pt=()=>{throw _t("Method unimplemented")},at=()=>{throw _t("Unexpected case")},hi=_t("Unexpected end of array"),ui=_t("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),De=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw ui}throw hi},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw ui}throw hi},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(De(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(De(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>Ye.decode(K(e)),Wt=Ye?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-De(e)](e);class Fr extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ci(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=wt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),fi=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^fi()&15>>e/4).toString(16)),zt=Date.now,Br=e=>new Promise(e);Promise.all.bind(Promise);const Vr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let di=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(di=localStorage,Gs=!1)}catch{}const gi=di,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Qe=Symbol("Equality"),pi=(e,t)=>e===t||!!e?.[Qe]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},on=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&on(e,(n,s)=>(n!==void 0||Xs(t,s))&&pi(t[s],n)),Pl=Object.freeze,wi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&wi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ye=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Qe]!=null)return e[Qe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var mi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",yi=typeof window<"u"&&typeof document<"u"&&!Gt;let kt;const Yl=()=>{if(kt===void 0)if(Gt){kt=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");kt.set(`--${Ur(t,"-")}`,n),kt.set(`-${Ur(t,"-")}`,n)}})):kt=rt();return kt},Ls=e=>Yl().has(e),Rn=e=>Vr(Gt?mi[e.toUpperCase().replaceAll("-","_")]:gi.getItem(e)),ki=e=>Ls("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Gt&&Wl(mi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!ki("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),Si=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=Si(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=yi?Ql:Zl,sc=yi?tc:ec,rc=e=>{const t=Si(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),jr=e=>e.next()>=.5,ks=(e,t,n)=>wt(e.next()*(n+1-t)+t),bi=(e,t,n)=>wt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>bi(e,t,n),lc=e=>ai(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Qe]?pi(e,t):Ce(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?on(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ye(this.shape,t.shape)}[ac](){return!0}[Qe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){pt()}get nullable(){return Ue(this,Qn)}get optional(){return new Ci(this)}cast(t){return Hr(t,this),t}expect(t){return Hr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),_i=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ei=e=>{if(Ae.check(e))return[uc(e)];if(_i.check(e))return e.shape.map(t=>t+"");if(Ui.check(e))return["[+-]?\\d+.?\\d*"];if(Mi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ei).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ei).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Ci extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Ci);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):on(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Di extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&on(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ai=(e,t)=>new Di(e,t),kc=J(Di);class Ii extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&on(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ii(e);J(Ii);class Ti extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=Ce(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const xi=(...e)=>new Ti(e),bc=J(Ti),_c=G(e=>Ce(e));class Oi extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Oi(e,t);J(Oi);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ue=(...e)=>e.findIndex(t=>Un.check(t))>=0?Ue(...e.map(t=>Ze(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Li=()=>!0,Mn=G(Li),xc=J(tr,e=>e.shape===Li),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ri=G(e=>typeof e=="symbol");G(e=>e===Ri);const ke=G(e=>typeof e=="number"),Ui=G(e=>e===ke),Ae=G(e=>typeof e=="string"),Mi=G(e=>e===Ae),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),vi=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Ue(ke,Ae,Qn,vi,nr,Kn,Ri);(()=>{const e=xi(Mn),t=Ai(Ae,Mn),n=Ue(ke,Ae,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const Ze=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=Ze(e[n]);return wc(t)}else{if(_c.check(e))return Ue(...e.map(Ze));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Hr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw _t(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ze(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),Ni=vc(Mn).if(Ui,(e,t)=>ks(t,Rr,On)).if(Mi,(e,t)=>cc(t)).if(Lc,(e,t)=>jr(t)).if(Oc,(e,t)=>BigInt(ks(t,Rr,On))).if(Un,(e,t)=>de(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(jr(t))continue;r=r.shape}n[s]=Ni(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=bi(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=de(t,e.res);return()=>n}).if(xc,(e,t)=>de(t,Ss(t,[ke,Ae,Qn,vi,nr,Kn,xi(ke),Ai(Ue("a","b","c"),ke)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;rNi(Ze(t),e),At=typeof document<"u"?document:{},Nc=e=>At.createElement(e),$c=()=>At.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>At.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n($i(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),$i=(e,t)=>e.appendChild(t),Pc=At.ELEMENT_NODE,Jc=At.TEXT_NODE;At.CDATA_SECTION_NODE;At.COMMENT_NODE;const Wc=At.DOCUMENT_NODE;At.DOCUMENT_TYPE_NODE;const Yc=At.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Fi=Ft(),Bi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),Vi=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...ji(e)),Pi.forEach(t=>t.print(e))},Hi=(...e)=>{console.warn(...ji(e)),e.unshift(sr),Pi.forEach(t=>t.print(e))},Pi=qt(),Ji=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Ji(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Ji(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class Me{constructor(){this.clients=new Map}}const Ie=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=wt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ce(r.len,i.clock+i.len-r.clock)):(s{const t=new Me;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{Dt(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new Me,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},ve=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Me,n=E(e.restDecoder);for(let s=0;s0){const o=Dt(t.clients,r,()=>[]);for(let l=0;l{const s=new Me,r=E(e.restDecoder);for(let i=0;i0){const i=new ie;return _(i.restEncoder,0),ve(i,s),i.toUint8Array()}return null},Wi=fi;class ae extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Wi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Br(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Br(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=Dt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,_e)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,xe)}getXmlElement(t=""){return this.get(t,Le)}getXmlFragment(t=""){return this.get(t,oe)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ae({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Yi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class qi extends Yi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return De(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class Te extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Fr(K(t),De),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Fr(K(t),De),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new Se(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Se(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ce(s,t[0].id.clock);const r=Et(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new ro,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==dt){const p=Dt(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new ie;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new Te(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Pr(s,r,l);if(l.pendingDs){const f=new Te(Xt(l.pendingDs));E(f.restDecoder);const d=Pr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Xi(r.doc,f)}},n,!1),Xi=(e,t,n,s=Te)=>{const r=Xt(t);ua(r,e,n,new s(r))},Ki=(e,t,n)=>Xi(e,t,n,qi),fa=(e,t,n=new Map)=>{or(e,t.store,n),ve(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new ie)=>{const s=Zi(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===cn)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===ie)return Nn(r)}return r[0]},Qi=(e,t)=>da(e,t,new cn),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new Yi(Xt(e))),to=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>to(e,ts(t.store)),wa=(e,t=new Gi)=>(e instanceof Map?to(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new zi);class ya{constructor(){this.l=[]}}const Jr=()=>new ya,Wr=(e,t)=>e.l.push(t),Yr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},eo=(e,t,n)=>Ks(e.l,[t,n]);class Se{constructor(t,n){this.client=t,this.clock=n}}const me=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new Se(e,t),no=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class so{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new so(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=no(e):s=D(e._item.id.client,e._item.id.clock),new so(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=be(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof M))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:be(s,i)};if(a instanceof M&&a.content instanceof It)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&me(e.item,t.item)&&me(e.type,t.type)&&e.assoc===t.assoc,pe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ln(t.ds,e.id),Ms=(e,t)=>{const n=Dt(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class ro{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},io=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Et=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=wt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Et(n,t.clock)]},be=Ca,vs=(e,t,n)=>{const s=Et(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},qr=(e,t,n)=>{const s=t.clients.get(n.client),r=Et(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ft&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Et(s,t.id.clock)]=n},oo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),ve(e,t.deleteSet),!0),Gr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&Dt(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Et(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Et(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},lo=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{eo(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ce(Et(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Et(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Fi,"[yjs] ",Bi,Vi,"Changed the client-id because another client seems to be using it."),s.clientID=Wi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new cn;zr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new ie;zr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):lo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&lo(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Xr=(e,t,n)=>{Ie(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Kr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Ie(l,h.insertions,d=>{if(d instanceof M){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Ie(l,h.deletions,d=>{d instanceof M&&i.some(p=>p===l.doc||vn(p,d))&&!ln(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Ao(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=Ce(t)?t[0].doc:t instanceof ae?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new Me;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&tn(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Ie(c,c.deleteSet,b=>{b instanceof M&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=Ce(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Hi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Xr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Xr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Kr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Kr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,qi,cn),Ra=(e,t)=>{if(e.constructor===ft){const{client:n,clock:s}=e.id;return new ft(D(n,s+t),e.length-t)}else if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=Te,n=ie)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===dt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===dt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==dt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return ve(o,h),o.toUint8Array()},Ua=(e,t,n=Te,s=ie)=>{const r=Zi(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===dt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ce(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return ve(i,h),i.toUint8Array()},co=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&co(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{co(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return ve(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,Te,cn),Qr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return ln(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw _t(Qr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw _t(Qr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Hi("Invalid access: Add Yjs type to a document before reading data.")},ao=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},ho=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ao){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ce(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;Dt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;eo(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Jr(),this._dEH=Jr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw pt()}clone(){throw pt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Wr(this._eH,t)}observeDeep(t){Wr(this._dEH,t)}unobserve(t){Yr(this._eH,t)}unobserveDeep(t){Yr(this._dEH,t)}toJSON(){}}const uo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},fo=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return nn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},po=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new le(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new an(new Uint8Array(u))),r.integrate(e,0);break;case ae:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new It(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},wo=()=>_t("Length exceeded!"),mo=(e,t,n,s)=>{if(n>t._length)throw wo();if(n===0)return t._searchMarker&&en(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},yo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw wo();t._searchMarker&&en(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new le([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new le([s]);break;case Uint8Array:l=new an(s);break;case ae:l=new hn(s);break;default:if(s instanceof z)l=new It(s);else throw new Error("Unexpected content type")}new M(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},So=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&pe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class _e extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new _e;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new _e}clone(){const t=new _e;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return po(this,t)}toArray(){return fo(this)}slice(t=0,n=this.length){return uo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return go(this,t)}forEach(t){nn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new _e;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class xe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new xe}clone(){const t=new xe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return So(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new xe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||Ne(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||Ne(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return Zr(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return Zr(e,o,n)}},bo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new M(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},Ne=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},_o=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Eo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new M(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r),c=s.constructor===String?new Ct(s):s instanceof z?new It(s):new he(s);let{left:h,right:a,index:u}=n;t._searchMarker&&en(t._searchMarker,n.index,c.getLength()),a=new M(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),bo(e,t,n,l)},ti=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new M(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Ct(c)),n.right.integrate(e,0),n.forward()}bo(e,t,n,l)},Co=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&Ne(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?Ne(o,r.content):(t+=Co(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&oo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==ft&&t.add(o.parent)})}U(n,s=>{Ie(e,e.deleteSet,r=>{if(r instanceof ft||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ei=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case It:case he:case Ct:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case It:case he:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Ct:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),Ne(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ct&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ti(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ei(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(pe(c,t)||n!==void 0&&pe(c,n))switch(c.content.constructor){case Ct:{const u=i.get("ychange");t!==void 0&&!pe(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!pe(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case It:case he:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:pe(c,t)&&(h(),Ne(i,c.content));break}c=c.right}h()};return t||n?U(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{ei(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ti(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Oe;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Le||n.constructor===oe)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class oe extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new oe}clone(){const t=new oe;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return go(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),nn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw _t("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return fo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return po(this,t)}slice(t=0,n=this.length){return uo(this,t,n)}forEach(t){nn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new oe;class Le extends oe{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Le(this.nodeName)}clone(){const t=new Le(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return So(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return nn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Le(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends xe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw pt()}mergeWith(t){return!1}write(t,n,s){throw pt()}integrate(t,n){throw pt()}}const sh=0;class ft extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),io(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class an{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new an(this.content)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new an(e.readBuf());class sn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new sn(this.len)}splice(t){const n=new sn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){tn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new sn(e.readLen()),Do=(e,t)=>new ae({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class hn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hn(Do(this.doc.guid,this.opts))}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new hn(Do(e.readString(),e.readAny()));class he{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new he(this.embed)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new he(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Ct(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class It{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new It(this.type._copy())}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new It(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=be(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ni=(e,t)=>js(e,n=>ln(n.deletions,t)),Ao=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Ao(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||ln(s,u.right.id)||ni(i.undoStack,u.right.id)||ni(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new M(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class M extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Lr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Or)>0}set keep(t){this.keep!==t&&(this.info^=Or)}get countable(){return(this.info&Lr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Se&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=qr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ft||this.right&&this.right.constructor===ft)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Se){const s=be(n,this.parent);s.constructor===ft?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=qr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),me(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),tn(t.deleteSet,this.id.client,this.id.clock,this.length),Gr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new ft(this.id,this.length)):this.content=new sn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:ze);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=no(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===Se?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const Io=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},xo="__ $YJS$ __";To[xo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");To[xo]=!0;const Oo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){gi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>Dt(Oo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Oo.delete(e)),s},we=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Lo=0,wr=1,Ro=2,Fs=(e,t)=>{_(e,Lo);const n=ma(t);H(e,n)},Uo=(e,t,n)=>{_(e,wr),H(e,Qi(t,n))},Th=(e,t,n)=>Uo(t,n,K(e)),Mo=(e,t,n,s)=>{try{Ki(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Ro),H(e,t)},Oh=Mo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Lo:Th(e,t,n);break;case wr:Mo(e,n,s,r);break;case Ro:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class vo extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},wt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ye(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},qe=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ee=0,No=3,Ee=1,Nh=2,un=[];un[ee]=(e,t,n,s,r)=>{_(e,ee);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};un[No]=(e,t,n,s,r)=>{_(e,Ee),H(e,qe(n.awareness,Array.from(n.awareness.getStates().keys())))};un[Ee]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};un[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const si=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),$o=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Fo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Fo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=$o(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ee),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ee),H(s,qe(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&we(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new vo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=un.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ee),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=$o(this,new Uint8Array(d),!1);Js(y)>1&&we(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ee),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ee),H(S,qe(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&si{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Qi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ri||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let L;w===0?L=0:O===-w||O!==w&&S[O-1+w-1]=r&&v>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=L,d=v}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` `)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),a=_t(o,i),u=[...Ue(a,_t(l,i)).map(S=>({h:S,toks:l,side:0})),...Ue(a,_t(c,i)).map(S=>({h:S,toks:c,side:1}))];u.sort((S,w)=>S.h.aS-w.h.aS||S.h.aE-w.h.aE||S.side-w.side);const h=(S,w,b)=>S.slice(w,b).join(""),d=(S,w,b,O)=>{let L="",T=b;for(const $ of S)$.side===w&&(L+=h(o,T,$.h.aS)+h($.toks,$.h.bS,$.h.bE),T=$.h.aE);return L+h(o,T,O)};let f="",p=0,y=0;for(;yB.side)).size===1){f+=d(S,S[0].side,w,b);continue}const L=d(S,0,w,b),T=d(S,1,w,b);if(L===T){f+=L;continue}if(w===b){const B=qh(L,T,s!==As,o.length===0);if(B===null){if(!r)return null;f+=T;continue}f+=B;continue}if(s===As)return null;const $=s===Pn?Jn(h(o,w,b),L,T,As):Jn(h(o,w,b),L,T,s+1,r);if($===null){if(!r)return null;f+=T;continue}f+=$}return f+h(o,p,o.length)}const se=e=>e===""||e.endsWith(` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=St(e,s),l=St(t,s),c=St(n,s),h=bt(o,i),a=[...Re(h,bt(l,i)).map(b=>({h:b,toks:l,side:0})),...Re(h,bt(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",L=S;for(const v of b)v.side===w&&(O+=u(o,L,v.h.aS)+u(v.toks,v.h.bS,v.h.bE),L=v.h.aE);return O+u(o,L,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),L=f(b,1,w,S);if(O===L){d+=O;continue}if(w===S){const F=qh(O,L,s!==As,o.length===0);if(F===null){if(!r)return null;d+=L;continue}d+=F;continue}if(s===As)return null;const v=s===Pn?Jn(u(o,w,S),O,L,As):Jn(u(o,w,S),O,L,s+1,r);if(v===null){if(!r)return null;d+=L;continue}d+=v}return d+u(o,p,o.length)}const ne=e=>e===""||e.endsWith(` `)?e:e+` `;function Bo(e,t,n,s){let r=t.endsWith(` `);return r===e.endsWith(` `)&&(r=n.endsWith(` `)),s===""||r===s.endsWith(` `)?s:r?s+` -`:s.slice(0,-1)}function Pt(e,t,n){const s=Jn(se(e),se(t),se(n),qt);return s===null?{ok:!1}:{ok:!0,text:Bo(e,t,n,s)}}function lu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),qt,!0)??se(n);return Bo(e,t,n,s)}function ii(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,qt),i=bt(t,qt),o=a=>{const u=new Array(a.length+1);u[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;O>=55296&&O<=56319&&w--;const L=b>0?p.charCodeAt(p.length-b):0;L>=56320&&L<=57343&&b--,S+=w,p=p.slice(w,p.length-b),y=y.slice(w,y.length-b),(p.length||y.length)&&s.push({index:S,deleteCount:p.length,insertText:y}),a=d,u=f}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,qt),s),i=Ue(_t(bt(e,qt),s),r),o=Ue(r,_t(bt(n,qt),s));for(const c of i)for(const a of o)if(c.bSc.bE):!(a.aE<=c.bS||a.aS>=c.bE))return!1}else if(a.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function We(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const oi=700,pe=[2e3,4e3,8e3,15e3],li=2e3,Gh=4,Xh=64,Kh=8,Qh=32e3,Zh=32;function cu(e){let t=e.seed,n=e.baseSha;const s=(g,k)=>{t=g,r=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let r=e.baseSha;const i=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},o=(g,k=tt)=>{const m=i(k);return r&&r===n&&t.length>Qh?{base:n,text:g,...m?{prior_sent:m}:{}}:{base:n,base_text:t,text:g,...m?{prior_sent:m}:{}}};let l=!1,c=!1,a=!1,u=!1,h=!1,d=0,f=null,p=!1,y=!1,S=!1,w=null,b=null,O="",L=0;const T=(g=Date.now())=>{const k=Math.max(g,L+1e3);return L=k,zo(e.path,e.who||"browser",new Date(k))},$=new Map;let B=0,gt=!1,ht=null,Qt=0,rs=!1,tt=null,xt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>Zh&&Bt.shift())};let Lt=!1,Fe=null,Zt=0;const Be=()=>{Lt=!1,Fe=null},is=g=>{Zt===g&&Be()};let it=0,pt=0,fn=null,te=null,os=!1,Vt=null,Ot=null,Ve=!1,ee=null,ut=null;const v=g=>e.onState?.(g),dn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let gn=null,ls=0;const je=()=>{clearTimeout(gn??void 0),gn=null},pn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||h||a)return;je();const m=pe[Math.min(ls,pe.length-1)];ls++,gn=setTimeout(()=>{gn=null,!h&&!a&&He()},m)},kr=()=>{je(),ls=0},wn=()=>{je(),ee&&clearTimeout(ee),ee=setTimeout(()=>{He()},oi)},Rt=g=>{if(h)return f=g,!0;const k=N();if(k===g)return!0;const m=ii(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const A of m)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},He=()=>{if(a)return Promise.resolve();if(p)return y?Promise.resolve():Pe();if(te)return os=!0,te;const g=(async()=>{try{for(;Vt;)await Vt;await Vo()}finally{te=null}})();return te=g,g},Vo=async()=>{let g=0;for(;;){if(os=!1,Y||a||S)return;const k=N();if(k===t&&!xt){v("clean");return}if(v("saving"),e.onWriting?.(),gt){if(w!==null&&b===k){if(await mn(k,O)==="stop")return;continue}gt=!1}const m=l||c?await jo(k):await Po(k);if(m==="stop")return;if(m==="rebased"){if(++g>Gh){await mn(N(),n??"");return}continue}if(!os){v(N()===t&&!xt?"clean":"dirty");return}}};let yt=!1;const jo=async g=>{Ot=g,Ve=!1;let k;try{k=await Sn(dn(e.path),g,n,yt)}catch(m){return Ot=null,m instanceof et&&m.status===422&&We(m)?(yt=!1,fe(g),"stop"):m instanceof et&&m.status===409?await cs(t,!1)?"rebased":"stop":(v("error"),pn(m),"stop")}return Ot=null,yt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(Ve||s(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await Tr(xr(e.apiBase,e.path))}catch(R){return v("error"),N()!==t&&pn(R),!1}if(m.kind!=="text")return v("error"),!1;const A=N(),C=Pt(g,m.text,A);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await mn(A,m.sha??"")==="rebased"):(s(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ho=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){xt=!0;const m=Pt(k.sent,g.text,N());m.ok&&Rt(m.text)?(t=g.text,r=void 0,ot(g.sha)):(t=k.sent,r=void 0)}},Po=async g=>{Ot=g,Ve=!1;let k;const m=tt;try{tt={sent:g,from:t,prev:m},k=await Ht(jt,{...o(g,m),...yt?{confirm_shrink:!0}:{}})}catch(C){if(Ot=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return c=!0,"rebased";if(C instanceof et&&C.status===422&&We(C))return yt=!1,fe(g),"stop";if(C instanceof et&&C.status===409&&!a){let R={};try{R=JSON.parse(C.body)}catch{}const j=typeof R.text=="string"?R.text:null;if(j!==null){const X=Pt(t,j,N());if(X.ok&&Rt(X.text))return t=j,r=void 0,ot(R.sha),"rebased"}return mn(N(),R.sha??"")}return v(a?"dirty":"error"),pn(C),"stop"}if(Ot=null,yt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,xt=!1,a)return"stop";const A=Pt(g,k.text,N());return A.ok&&Rt(A.text)&&(Ve||s(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const fe=g=>{Y||h||!e.onShrinkRefused||(v("error"),Y={was:bn(t),now:bn(g),confirm:async()=>{if(!h){if(a){v("saving"),e.onWriting?.();const k=it,m=Zt;try{const A=await Ht(jt,{update:x.encodeState(),base:n,confirm_shrink:!0});s(A.text,A.sha),as(k,m);const C=!Lt&&pt>=it;v(C?"clean":"dirty"),e.onSaved?.(t),!u&&!h&&pt{if(!h)try{const k=await Tr(xr(e.apiBase,e.path));if(h||k.kind!=="text")return;if(s(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await de(!1),h)return;v(pt>=it&&!Lt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Be(),v("clean")}catch{v("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let kt=null;const Jo=()=>{kt&&clearTimeout(kt),kt=setTimeout(()=>{const g=N();Go(bn(t),bn(g))&&fe(g)},oi)},Sr=async(g,k,m=T())=>{const A=++B;let C=m;for(let R=1;;R++){const j=C;$.set(j,g);try{return await Sn(dn(j),g,void 0,!1,!1,!1,!0),A===B&&!a&&(t=g,r=void 0,k&&(n=k),v("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&R{const C=(R,j)=>{Sn(dn(R),k,void 0,!1,!0,!0,!0).then(X=>A?.(X.parked??R),X=>{if(X instanceof et&&X.status===409&&j{(w===null||b!==g)&&(w=T(),b=g);const m=w;O=k,gt=!0;const A=await Sr(g,k,m);return h?"stop":A?(pn(A.err),"stop"):(gt=!1,b===g&&(w=null,b=null,O=""),N()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(h||u)&&(d=it-pt,e.onPending?.(d))},Wo=()=>{h||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!h&&de(!1)},li))},de=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,A=Zt;return Ht(jt,{update:x.encodeState(),base:n},!0).then(C=>{ot(C.sha),as(m,A)})}if(fn)return fn;const k=(async()=>{try{for(;!u&&!h&&!Y&&pt{p=!1,w=null,b=null,Qt=0,clearTimeout(ht??void 0),ht=null,xt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Pe=async()=>{if(h||a||y||S)return;if(clearTimeout(ht??void 0),ht=null,ee&&clearTimeout(ee),ee=null,te||Vt){S=!0;try{for(;te||Vt;)await(te??Vt)}finally{S=!1}if(h||a)return;if(!u){N()!==t&&wn();return}}if(tt!==null&&!c){let j;S=!0;try{j=await Ht(jt,{peek:!0})}catch{if(h||a)return;const X=pe[Math.min(Qt,pe.length-1)];Qt++,ht=setTimeout(()=>{ht=null,Pe()},X);return}finally{S=!1}if(h||a)return;if(Ho(j),!u){(N()!==t||xt)&&wn();return}}const g=e.soloText?.();if(g===void 0||g===t)return hs();const k=x.text.toString(),m=Pt(t,k,g);if(m.ok)return hs(()=>x.applySplices(ii(k,m.text)));p=!0,(w===null||b!==g)&&(w=T(),b=g),y=!0;let A;try{A=await Sr(g,n??"",w)}finally{y=!1}if(h)return;if(!A)return e.soloText?.()!==g?(w=null,b=null,Pe()):hs(()=>{t=x.text.toString()});const C=A.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const R=pe[Math.min(Qt,pe.length-1)];Qt++,ht=setTimeout(()=>{ht=null,Pe()},R)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(l=!0),u&&(ut&&clearTimeout(ut),ut=null,je(),a||Pe(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!h&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if(v("dirty"),a){Lt=!0,Fe=m,Zt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!h&&de(!1)},li)),Jo();return}wn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{h||(l=!0,x.stop(),e.onSolo())});const N=()=>f!==null?f:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||l&&x.text.length>0,ot=g=>{g&&(n=g)},Yo=(g,k,m)=>{if(m?.held)return s(g,k),"same";if(g===t||g===Ot)return ot(k),"same";const A=N();if(g===A)return s(g,k),a&&(Be(),v("clean")),"same";if(a){const R=t;return Bt.includes(g)||Dn(R,g,A)?(s(g,k),Lt&&(Fe===null||g===Fe||Dn(R,Fe,g))&&(Be(),v("clean")),"same"):A!==t||x.peerCount()>0?"blocked":(s(g,k),Rt(g),Be(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=Pt(t,g,A);return C.ok?(Ot!==null&&(Ve=!0),s(g,k),Rt(C.text),C.text!==g?wn():Ot===null&&v("clean"),C.text===A?"same":"merged"):"blocked"};let yn=null;const qo=()=>{if(!a)return He();if(Y||h)return Promise.resolve();if(!u)return d>0?de(!1):Promise.resolve();if(!Lt)return Promise.resolve();if(yn)return yn;const g=Zt;v("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(h)return;m.update&&x.applyRemoteUpdate(m.update),s(m.text,m.sha),is(g),v(Lt?"dirty":"clean"),e.onSaved?.(t)}catch(m){if(h||m instanceof et&&m.status===422&&We(m)&&(clearTimeout(kt??void 0),kt=null,fe(N()),Y))return;v(Lt?"dirty":"clean")}finally{yn=null}})();return yn=k,k};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const I=!u&&d>0;if(!I&&!(u&&Lt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Zt;(I?de(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(p||gt){if(!g.trim())return;const I="park\0"+g;if(Ut===I)return;Ut=I;let V=w!==null&&b===g?w:null;for(const[Mt,lt]of $)V===null&<===g&&(V=Mt);V??=T(),br(V,g,I);return}if(g===t&&!xt)return;const m="text\0"+g;if(Ut===m)return;if((l||c)&&!k){He();return}Ut=m;const A=t,C=!(l||c),R=tt,j={sent:g,from:A,prev:R};C&&(tt=j);const X=I=>{if(C&&I instanceof et&&[400,401,403,404,405,409,413].includes(I.status)&&tt===j&&(tt=R),I instanceof et&&I.status===422&&We(I)){kn(m)(),h||(clearTimeout(kt??void 0),kt=null,fe(N()));return}if(!(I instanceof et&&I.status===409))return kn(m)();let V={};try{const lt=JSON.parse(I.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(A,g,V.text))){if(!h&&!a){const lt=Pt(g,V.text,N());lt.ok&&Rt(lt.text)&&(t=V.text,r=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;gt=!0;let Mt=w!==null&&b===g?w:null;for(const[lt,ds]of $)Mt===null&&ds===g&&(Mt=lt);Mt??=T(),w=Mt,b=g,br(Mt,g,m,lt=>{gt=!1,e.onConflictCopy?.(lt)})},Je=(I,V)=>{t=g,r=void 0,ot(V),!h&&N()===g&&v("clean"),e.onConflictCopy?.(I)};let us;C?us=Ht(jt,{...o(g,R),park_on_conflict:!0},!0).then(I=>{if(yt=!1,tt===j&&(tt=null),xt=!1,I.parked)return Je(I.parked,I.sha);if(I.update&&x.applyRemoteUpdate(I.update),h||a||typeof I.text!="string"){ot(I.sha);return}const V=Pt(g,I.text,N());V.ok&&Rt(V.text)&&(s(I.text,I.sha),N()===t&&v("clean")),e.onSaved?.(I.text)},X):us=Sn(dn(e.path),g,n,yt,!0,!0).then(I=>{if(yt=!1,I.parked)return Je(I.parked,I.sha);if(I.merged){h?ot(I.sha):cs(g,!0);return}s(g,I.sha),!h&&N()===t&&v("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{h||Dr(N(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:N,merge:Yo,rebase:ot,saveNow:qo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(ee??void 0),clearTimeout(kt??void 0),je(),clearTimeout(ht??void 0),ht=null;const g=N();h=!0,f=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,oi as S,ou as U,ru as a,ka as b,Ea as c,ii as d,iu as e,Ps as f,ae as g,eu as h,vt as i,lu as m,cu as o,su as r,nu as t}; +`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(ne(e),ne(t),ne(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Bo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(ne(e),ne(t),ne(n),Yt,!0)??ne(n);return Bo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` +`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function ii(e,t){if(e===t)return[];const n=[],s=new Map,r=St(e,Yt),i=St(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=bt(St(t,Yt),s),i=Re(bt(St(e,Yt),s),r),o=Re(r,bt(St(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function We(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const oi=700,ge=[2e3,4e3,8e3,15e3],li=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",L=0;const v=(g=Date.now())=>{const k=Math.max(g,L+1e3);return L=k,zo(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,Tt=!1,ht=null,$e=0,rs=!1,tt=null,xt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let Ot=!1,Fe=null,Qt=0;const Be=()=>{Ot=!1,Fe=null},is=g=>{Qt===g&&Be()};let it=0,gt=0,fn=null,Zt=null,os=!1,Vt=null,Lt=null,Ve=!1,te=null,ut=null;const N=g=>e.onState?.(g),dn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let gn=null,ls=0;const je=()=>{clearTimeout(gn??void 0),gn=null},pn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;je();const m=ge[Math.min(ls,ge.length-1)];ls++,gn=setTimeout(()=>{gn=null,!f&&!a&&He()},m)},kr=()=>{je(),ls=0},wn=()=>{je(),te&&clearTimeout(te),te=setTimeout(()=>{He()},oi)},Rt=g=>{if(f)return p=g,!0;const k=$();if(k===g)return!0;const m=ii(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},He=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Pe();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await Vo()}finally{Zt=null}})();return Zt=g,g},Vo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=$();if(k===n&&!xt){N("clean");return}if(N("saving"),e.onWriting?.(),Tt){if(S!==null&&A===k){if(await mn(k,O)==="stop")return;continue}Tt=!1}const m=c||h?await jo(k):await Po(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await mn($(),s??"");return}continue}if(!os){N($()===n&&!xt?"clean":"dirty");return}}};let mt=!1;const jo=async g=>{Lt=g,Ve=!1;let k;try{k=await Sn(dn(e.path),g,s,mt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&We(m)?(mt=!1,ue(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":(N("error"),pn(m),"stop")}return Lt=null,mt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(Ve||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await Tr(xr(e.apiBase,e.path))}catch(R){return N("error"),$()!==n&&pn(R),!1}if(m.kind!=="text")return N("error"),!1;const I=$(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await mn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ho=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){xt=!0;const m=t(k.sent,g.text,$());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Po=async g=>{Lt=g,Ve=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...mt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&We(C))return mt=!1,ue(g),"stop";if(C instanceof et&&C.status===409&&!a){let R={};try{R=JSON.parse(C.body)}catch{}const j=typeof R.text=="string"?R.text:null;if(j!==null){const X=t(n,j,$());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(R.sha),"rebased"}return mn($(),R.sha??"")}return N(a?"dirty":"error"),pn(C),"stop"}if(Lt=null,mt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,xt=!1,a)return"stop";const I=t(g,k.text,$());return I.ok&&Rt(I.text)&&(Ve||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ue=g=>{Y||f||!e.onShrinkRefused||(N("error"),Y={was:bn(n),now:bn(g),confirm:async()=>{if(!f){if(a){N("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!Ot&>>=it;N(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&>{if(!f)try{const k=await Tr(xr(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;N(gt>=it&&!Ot?"clean":"dirty");return}gt=it,d&&(d=0,e.onPending?.(0)),Be(),N("clean")}catch{N("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let yt=null;const Jo=()=>{yt&&clearTimeout(yt),yt=setTimeout(()=>{const g=$();Go(bn(n),bn(g))&&ue(g)},oi)},Sr=async(g,k,m=v())=>{const I=++Kt;let C=m;for(let R=1;;R++){const j=C;F.set(j,g);try{return await Sn(dn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),N("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&R{const C=(R,j)=>{Sn(dn(R),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??R),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=v(),A=g);const m=S;O=k,Tt=!0;const I=await Sr(g,k,m);return f?"stop":I?(pn(I.err),"stop"):(Tt=!1,A===g&&(S=null,A=null,O=""),$()!==g?"rebased":"stop")},as=(g,k)=>{gt=Math.max(gt,g),is(k),!(f||u)&&(d=it-gt,e.onPending?.(d))},Wo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},li))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(gt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(fn)return fn;const k=(async()=>{try{for(;!u&&!f&&!Y&>{y=!1,S=null,A=null,$e=0,clearTimeout(ht??void 0),ht=null,xt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Pe=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){$()!==n&&wn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=ge[Math.min($e,ge.length-1)];$e++,ht=setTimeout(()=>{ht=null,Pe()},X);return}finally{w=!1}if(f||a)return;if(Ho(j),!u){($()!==n||xt)&&wn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(ii(k,m.text)));y=!0,(S===null||A!==g)&&(S=v(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Pe()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const R=ge[Math.min($e,ge.length-1)];$e++,ht=setTimeout(()=>{ht=null,Pe()},R)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,je(),a||Pe(),gt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if(N("dirty"),a){Ot=!0,Fe=m,Qt+=1,u||(it+=1,d=it-gt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},li)),Jo();return}wn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const $=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},Yo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=$();if(g===I)return r(g,k),a&&(Be(),N("clean")),"same";if(a){const R=n;return Bt.includes(g)||Dn(R,g,I)?(r(g,k),Ot&&(Fe===null||g===Fe||Dn(R,Fe,g))&&(Be(),N("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Be(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(Ve=!0),r(g,k),Rt(C.text),C.text!==g?wn():Lt===null&&N("clean"),C.text===I?"same":"merged"):"blocked"};let yn=null;const qo=()=>{if(!a)return He();if(Y||f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!Ot)return Promise.resolve();if(yn)return yn;const g=Qt;N("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),N(Ot?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&We(m)&&(clearTimeout(yt??void 0),yt=null,ue($()),Y))return;N(Ot?"dirty":"clean")}finally{yn=null}})();return yn=k,k};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&Ot))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(y||Tt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=v(),br(V,g,T);return}if(g===n&&!xt)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){He();return}Ut=m;const I=n,C=!(c||h),R=tt,j={sent:g,from:I,prev:R};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=R),T instanceof et&&T.status===422&&We(T)){kn(m)(),f||(clearTimeout(yt??void 0),yt=null,ue($()));return}if(!(T instanceof et&&T.status===409))return kn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,$());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;Tt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=v(),S=Mt,A=g,br(Mt,g,m,lt=>{Tt=!1,e.onConflictCopy?.(lt)})},Je=(T,V)=>{n=g,i=void 0,ot(V),!f&&$()===g&&N("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,R),park_on_conflict:!0},!0).then(T=>{if(mt=!1,tt===j&&(tt=null),xt=!1,T.parked)return Je(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,$());V.ok&&Rt(V.text)&&(r(T.text,T.sha),$()===n&&N("clean")),e.onSaved?.(T.text)},X):us=Sn(dn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return Je(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&$()===n&&N("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr($(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:$,merge:Yo,rebase:ot,saveNow:qo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(yt??void 0),je(),clearTimeout(ht??void 0),ht=null;const g=$();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{ae as D,oi as S,au as U,lu as a,ka as b,Ea as c,ii as d,cu as e,Ps as f,ce as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 56b72fd4..6dc8ff17 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + From a94090bf9d99df9a700e8b31694daba541be8e8b Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:37:40 +0900 Subject: [PATCH 07/34] fix(webapp): check shrink synchronously on explicit save and after Done timeout --- internal/webapp/frontend/src/apps/Browser.tsx | 11 +- .../frontend/src/components/FileView.tsx | 27 ++- .../webapp/frontend/src/lib/sharedfile.ts | 18 +- .../src/lib/sharedfile_restore.test.ts | 155 +++++++++++++----- ...{Editor-CWQeqJPd.js => Editor-CUIsP4dU.js} | 2 +- ...dit-CNasvd30.js => VisualEdit-Dl8vJRj-.js} | 2 +- .../{index-AIvST0b2.js => index-YIhaBYDQ.js} | 34 ++-- ...ile-BHUrOeP7.js => sharedfile-CSb7vEsh.js} | 22 +-- internal/webapp/static/index.html | 2 +- 9 files changed, 193 insertions(+), 80 deletions(-) rename internal/webapp/static/assets/{Editor-CWQeqJPd.js => Editor-CUIsP4dU.js} (99%) rename internal/webapp/static/assets/{VisualEdit-CNasvd30.js => VisualEdit-Dl8vJRj-.js} (97%) rename internal/webapp/static/assets/{index-AIvST0b2.js => index-YIhaBYDQ.js} (87%) rename internal/webapp/static/assets/{sharedfile-BHUrOeP7.js => sharedfile-CSb7vEsh.js} (57%) diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx index 82aeee37..bf9f17a4 100644 --- a/internal/webapp/frontend/src/apps/Browser.tsx +++ b/internal/webapp/frontend/src/apps/Browser.tsx @@ -1157,17 +1157,14 @@ export default function Browser(props: { navigate(urlForPath(path, project?.id, version, route.full, true)); return; } - // Save and leave: the flush gets a moment, never a veto — a - // hub that does not answer must not trap the user in the - // editor. Only a question the user must answer keeps them here. + // Save and leave: FileView's flush bounds its own wait, so a + // hub that does not answer never traps the user in the editor. + // Only a question the user must answer keeps them here. const target = urlForPath(path, project?.id, version, route.full, false); const here = window.location.pathname + window.location.search; let okToLeave = true; try { - okToLeave = await Promise.race([ - editFlushRef.current?.() ?? Promise.resolve(true), - new Promise((r) => setTimeout(() => r(true), 1_500)), - ]); + okToLeave = await (editFlushRef.current?.() ?? Promise.resolve(true)); } catch { // The editor's own teardown still sends what it holds. } diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx index d0e87b43..569595e6 100644 --- a/internal/webapp/frontend/src/components/FileView.tsx +++ b/internal/webapp/frontend/src/components/FileView.tsx @@ -511,20 +511,41 @@ function EditView(props: Parameters[0]) { void qc.invalidateQueries({ queryKey: ["render", apiBase, path] }); }; const { flushRef } = props; + /* A read that came back empty yet names a version: the file may hold more + than this buffer was seeded with, so only the hub can tell a shrink (its + 422), and its answer gets longer before Done gives up waiting. */ + const onlyHubSeesShrink = data?.kind === "text" && data.text === "" && !!data.sha; useEffect(() => { if (!flushRef) return; + /* Save and leave: the save gets a moment, never a veto — a hub that does + not answer must not trap the user in the editor. A question the user + must answer does keep them here, however it opened: before any request + (a shrink known here), or from the hub's answer within the wait. */ const flush = async () => { const f = fileHandle.current; - await f?.saveNow(); + if (!f) return true; + // Promise constructor, not withResolvers: the app targets ES2022. + let timer: ReturnType | undefined; + const waited = new Promise((r) => { + timer = setTimeout(r, onlyHubSeesShrink ? 5_000 : 1_500); + }); + try { + await Promise.race([f.saveNow(), waited]); + } catch { + // The editor's own teardown still sends what it holds. + } finally { + clearTimeout(timer); + } + if (f.askingShrink()) return false; void qc.invalidateQueries({ queryKey: ["render", apiBase, path] }); void qc.invalidateQueries({ queryKey: ["text", fileURL] }); - return !f?.askingShrink(); + return true; }; flushRef.current = flush; return () => { if (flushRef.current === flush) flushRef.current = null; }; - }, [flushRef, qc, apiBase, path, fileURL]); + }, [flushRef, qc, apiBase, path, fileURL, onlyHubSeesShrink]); // Co-editors in this document right now. A write while somebody else is in // the room is their snapshot of the document I already have — warning about // it would fire on every co-editing save. Alone, the same event means diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index 91d266b8..fb28928e 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -1243,8 +1243,24 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { or a bystander: nothing to send. Concurrent calls share one request. */ let liveFlushing: Promise | null = null; const saveNow = (): Promise => { + if (!gone) { + // The question is open: Done stays put until it is answered. + if (asking) return Promise.resolve(); + /* A sharp shrink against what the file is known to hold needs the + user's word before any request: ask at once, so Done never waits on + the network (or times out past it) to learn what is known here. A + shrink only the hub can see (a `saved` that is not the whole file) + is still its 422, answered the same way. */ + const wouldSend = hubHoldsIt ? (live ? localDirtyInRoom : pending > 0) : current() !== saved; + if (wouldSend && !confirmShrinkOnce && opts.onShrinkRefused && sharpShrink(byteLength(saved), byteLength(current()))) { + clearTimeout(shrinkTimer ?? undefined); + shrinkTimer = null; + askShrink(current()); + return Promise.resolve(); + } + } if (!hubHoldsIt) return save(); - if (asking || gone) return Promise.resolve(); + if (gone) return Promise.resolve(); if (!live) return pending > 0 ? flushOffline(false) : Promise.resolve(); if (!localDirtyInRoom) return Promise.resolve(); if (liveFlushing) return liveFlushing; diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 90306cff..9418eef4 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -2118,32 +2118,30 @@ test("a failed or bfcache-restored pagehide flush leaves the typing to be sent a } }); -/* Done in a live room the hub refuses for emptying the file: the user is - asked at once (the caller stays on the editor), a second Done sends - nothing while the question is open, and confirming writes it. */ -test("an explicit live save refused for a sharp shrink asks the user and waits", async () => { +/* Done in a live room on a buffer emptied against what the file is known to + hold: the user is asked at once, before any request (the caller stays on + the editor), a second Done sends nothing while the question is open, and + confirming writes it. */ +test("an explicit live save of a sharp shrink asks the user first and waits", async () => { fakeTimers(); const h = await heldRoom(); try { await h.goLive(); h.localEdit((t) => t.delete(0, t.length)); - h.net.status = 422; - h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); await h.file.saveNow(); - assert.equal(h.reqs.length, 1); + same(h.reqs, []); assert.equal(h.asks.length, 1); assert.equal(h.file.askingShrink(), true); assert.equal(h.states.at(-1), "error"); await h.file.saveNow(); await advance(60_000); // nor does the idle check stack a second dialog - assert.equal(h.reqs.length, 1); + same(h.reqs, []); assert.equal(h.asks.length, 1); - h.net.status = 200; await (h.asks[0] as ShrinkAsk).confirm(); - assert.equal(h.reqs.length, 2); - const body = JSON.parse(h.reqs[1].body) as { confirm_shrink?: boolean }; + assert.equal(h.reqs.length, 1); + const body = JSON.parse(h.reqs[0].body) as { confirm_shrink?: boolean }; assert.equal(body.confirm_shrink, true); assert.equal(h.file.askingShrink(), false); assert.equal(h.states.at(-1), "clean"); @@ -2172,33 +2170,30 @@ test("a restore to a state older than `saved` is an outside write, not the room' } }); -/* The same refusal with the socket down: Done's offline flush is answered - 422. No retry can land an unconfirmed shrink, so the user is asked at once - and nothing is re-sent while the question is open; confirming hands the - queued edits over and leaves nothing pending. */ -test("an offline explicit save refused for a sharp shrink asks at once and never retries unconfirmed", async () => { +/* The same shrink with the socket down: Done asks at once and sends nothing + (no retry can land an unconfirmed shrink), nothing is sent while the + question is open, and confirming hands the queued edits over and leaves + nothing pending. */ +test("an offline explicit save of a sharp shrink asks at once and never sends unconfirmed", async () => { fakeTimers(); const h = await heldRoom(); try { await h.goLive(); h.c.onStatus("offline"); h.localEdit((t) => t.delete(0, t.length)); - h.net.status = 422; - h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); await h.file.saveNow(); - assert.equal(h.reqs.length, 1); + same(h.reqs, []); assert.equal(h.file.askingShrink(), true); assert.equal(h.asks.length, 1); assert.equal(h.pendings.at(-1), 1); await advance(60_000); // the offline timer and the idle check stay quiet - assert.equal(h.reqs.length, 1); + same(h.reqs, []); assert.equal(h.asks.length, 1); - h.net.status = 200; await (h.asks[0] as ShrinkAsk).confirm(); - assert.equal(h.reqs.length, 2); - const body = JSON.parse(h.reqs[1].body) as { confirm_shrink?: boolean; update?: string }; + assert.equal(h.reqs.length, 1); + const body = JSON.parse(h.reqs[0].body) as { confirm_shrink?: boolean; update?: string }; assert.equal(body.confirm_shrink, true); assert.equal(typeof body.update, "string"); assert.equal(h.file.askingShrink(), false); @@ -2207,18 +2202,104 @@ test("an offline explicit save refused for a sharp shrink asks at once and never await advance(60_000); h.destroy(); - assert.equal(h.reqs.length, 2); + assert.equal(h.reqs.length, 1); } finally { h.done(); realTimers(); } }); -/* Keep, with the socket down, after the offline flush was refused for a - sharp shrink: that refused update had already reached the room's document, - so the room holds the shrunk text. Putting the file's bytes back is an edit - the room must get — over HTTP at once, or, if that fails, still queued for - the retry, pagehide and the unmount. */ +/* Done on a sharply shrunk buffer while the network never answers, in every + mode: the question opens at once and nothing is sent, so Done stays on the + editor instead of timing out past an unanswered save. */ +for (const mode of ["live", "offline", "staging", "solo"] as const) { + test(`Done on a sharp shrink asks at once and sends nothing, the network hung (${mode})`, async () => { + fakeTimers(); + const h = await heldRoom(mode === "solo" ? { apiBase: "/api/" } : {}); + try { + if (mode === "solo") await advance(0); // no room route: solo + if (mode === "live" || mode === "offline") await h.goLive(); + if (mode === "offline") h.c.onStatus("offline"); + h.net.hold = Promise.withResolvers().promise; // never answers + if (mode === "live" || mode === "offline") h.localEdit((t) => t.delete(0, t.length)); + else h.state.buffer = ""; + + let settled = false; + void h.file.saveNow().then(() => { + settled = true; + }); + await settle(); // no timer runs: the answer is local + assert.equal(settled, true); + assert.equal(h.file.askingShrink(), true); + assert.equal(h.asks.length, 1); + same(h.reqs, []); + } finally { + h.done(); + realTimers(); + } + }); +} + +/* A shrink only the hub can see: the read seeded an empty buffer (`saved` + is "", so nothing local is a shrink) and the hub refuses the save 422, + slowly. The question opens when the answer comes, and Done — waiting on + the save — finds it open and stays. */ +test("a shrink the hub refuses 422 after a slow answer still asks before Done leaves", async () => { + fakeTimers(); + try { + const reqs: string[] = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + reqs.push((init?.method ?? "GET") + " " + decodeURIComponent(String(url))); + // The hub answers late (fake clock: advance() moves it). + const late = Promise.withResolvers(); + setTimeout(late.resolve, 800); + await late.promise; + return new Response(JSON.stringify({ error: "would cut most of the file", shrink: true }), { status: 422 }); + }) as typeof fetch; + let buffer = ""; + let solo = false; + const asks: ShrinkAsk[] = []; + const file = openSharedFile({ + apiBase: "/api/", + path: "notes.md", + seed: "", + baseSha: "sha-big", + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onShrinkRefused: (a) => asks.push(a), + soloText: () => buffer, + soloApply: (e) => { + buffer = buffer.slice(0, e.from) + e.insert + buffer.slice(e.to); + }, + }); + await waitFor(() => assert.equal(solo, true)); + + buffer = "x\n"; + let settled = false; + void file.saveNow().then(() => { + settled = true; + }); + await advance(799); + assert.equal(reqs.length, 1); + assert.equal(settled, false); + assert.equal(file.askingShrink(), false); + await advance(1); + assert.equal(settled, true); + assert.equal(file.askingShrink(), true); + assert.equal(asks.length, 1); + file.destroy(); + } finally { + realTimers(); + } +}); + +/* Keep, with the socket down, after Done asked about a sharp shrink: the + deletion is queued in this tab's document, so putting the file's bytes + back is an edit the room must get too — over HTTP at once, or, if that + fails, still queued for the retry, pagehide and the unmount. */ for (const keepAnswer of [200, 503]) { test(`offline Keep after a shrink refusal hands the restored text to the room (answer ${keepAnswer})`, async () => { const Y = await import("yjs"); @@ -2234,10 +2315,8 @@ for (const keepAnswer of [200, 503]) { await h.goLive(); h.c.onStatus("offline"); h.localEdit((t) => t.delete(0, t.length)); - h.net.status = 422; - h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true }); await h.file.saveNow(); - assert.equal(posts().length, 1); + same(posts(), []); // asked before anything was sent assert.equal(h.file.askingShrink(), true); h.net.status = keepAnswer; @@ -2245,8 +2324,8 @@ for (const keepAnswer of [200, 503]) { await (h.asks[0] as ShrinkAsk).keep(); assert.equal(h.file.askingShrink(), false); assert.equal(h.file.current(), "a\nb\nc\n"); - assert.equal(posts().length, 2); - const sent = JSON.parse(posts()[1].body) as { update?: string; confirm_shrink?: boolean }; + assert.equal(posts().length, 1); + const sent = JSON.parse(posts()[0].body) as { update?: string; confirm_shrink?: boolean }; assert.equal(sent.confirm_shrink, undefined); assert.equal(roomText(sent.update ?? ""), "a\nb\nc\n"); @@ -2255,15 +2334,15 @@ for (const keepAnswer of [200, 503]) { assert.equal(h.states.at(-1), "clean"); await advance(60_000); h.destroy(); - assert.equal(posts().length, 2); + assert.equal(posts().length, 1); } else { // Not handed over: still queued, and a closing tab still sends it. assert.ok((h.pendings.at(-1) ?? 0) > 0); assert.equal(h.states.at(-1), "dirty"); window.dispatchEvent(new Event("pagehide")); - assert.equal(posts().length, 3); - assert.equal(posts()[2].keepalive, true); - const exit = JSON.parse(posts()[2].body) as { update?: string }; + assert.equal(posts().length, 2); + assert.equal(posts()[1].keepalive, true); + const exit = JSON.parse(posts()[1].body) as { update?: string }; assert.equal(roomText(exit.update ?? ""), "a\nb\nc\n"); } } finally { diff --git a/internal/webapp/static/assets/Editor-CWQeqJPd.js b/internal/webapp/static/assets/Editor-CUIsP4dU.js similarity index 99% rename from internal/webapp/static/assets/Editor-CWQeqJPd.js rename to internal/webapp/static/assets/Editor-CUIsP4dU.js index 78244cdc..1a758b28 100644 --- a/internal/webapp/static/assets/Editor-CWQeqJPd.js +++ b/internal/webapp/static/assets/Editor-CUIsP4dU.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-AIvST0b2.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BHUrOeP7.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-YIhaBYDQ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CSb7vEsh.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-CNasvd30.js b/internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-CNasvd30.js rename to internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js index 3e8ff9d3..b47227e8 100644 --- a/internal/webapp/static/assets/VisualEdit-CNasvd30.js +++ b/internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-AIvST0b2.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-BHUrOeP7.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-YIhaBYDQ.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-CSb7vEsh.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-AIvST0b2.js b/internal/webapp/static/assets/index-YIhaBYDQ.js similarity index 87% rename from internal/webapp/static/assets/index-AIvST0b2.js rename to internal/webapp/static/assets/index-YIhaBYDQ.js index a8b77b0a..11ed4953 100644 --- a/internal/webapp/static/assets/index-AIvST0b2.js +++ b/internal/webapp/static/assets/index-YIhaBYDQ.js @@ -1,13 +1,13 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CWQeqJPd.js","assets/sharedfile-BHUrOeP7.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CNasvd30.js"])))=>i.map(i=>d[i]); -import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ht;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ht=-1i.map(i=>d[i]); +import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Rn={};var sw;function QR(){if(sw)return Rn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ft;function st(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ft=-1)":-1p||F[d]!==ne[p]){var ce=` -`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function lt(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function hn(s){try{var a="",c=null;do a+=lt(s,c),c=s,s=s.return;while(s);return a}catch(d){return` +`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Un=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?st(c):""}function ze(s,a){switch(s.tag){case 26:case 27:case 5:return st(s.type);case 16:return st("Lazy");case 13:return s.child!==a&&a!==null?st("Suspense Fallback"):st("Suspense");case 19:return st("SuspenseList");case 0:case 15:return Vn(s.type,!1);case 11:return Vn(s.type.render,!1);case 1:return Vn(s.type,!0);case 31:return st("Activity");default:return""}}function mt(s){try{var a="",c=null;do a+=ze(s,c),c=s,s=s.return;while(s);return a}catch(d){return` Error generating stack: `+d.message+` -`+d.stack}}var Nt=Object.prototype.hasOwnProperty,Ct=e.unstable_scheduleCallback,mn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function vt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function yt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function _t(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function wt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),wt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return wt(J,G,Vc(te),ue);if(te.$$typeof===R)return wt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=wt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var wt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(wt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(wt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Et===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Et.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[sn]=s,a[kn]=c}catch(v){pt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[sn]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kwt&&(C=wt,wt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,wt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>wt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(_t(s,2),Js(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),_t(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(_t(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return Ct(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||vt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` +`+d.stack}}var pt=Object.prototype.hasOwnProperty,ht=e.unstable_scheduleCallback,hn=e.unstable_cancelCallback,Et=e.unstable_shouldYield,On=e.unstable_requestPaint,ut=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Hn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,jn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,Rt=262144,Zt=4194304;function zt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=zt(d):(C&=k,C!==0?p=zt(C):c||(c=k&~s,c!==0&&(p=zt(c))))):(k=d&~v,k!==0?p=zt(k):C!==0?p=zt(C):c||(c=d&~s,c!==0&&(p=zt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function xt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function bt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function Cn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Nt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function _n(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+kn(a)):s.value!==""+kn(a)&&(s.value=""+kn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,kn(a)):c!=null?Ia(s,C,kn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+kn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+kn(c):"",a=a!=null?""+kn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(et=De,De=null):et=De.sibling;var ct=se(J,De,te[Ke],ue);if(ct===null){De===null&&(De=et);break}s&&De&&ct.alternate===null&&a(J,De),G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct,De=et}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),Fe;if(De===null){for(;KeKe?(et=De,De=null):et=De.sibling;var ya=se(J,De,ct.value,ue);if(ya===null){De===null&&(De=et);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),lt===null?Fe=ya:lt.sibling=ya,lt=ya,De=et}if(ct.done)return c(J,De),at&&wr(J,Ke),Fe;if(De===null){for(;!ct.done;Ke++,ct=te.next())ct=de(J,ct.value,ue),ct!==null&&(G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct);return at&&wr(J,Ke),Fe}for(De=d(De);!ct.done;Ke++,ct=te.next())ct=oe(De,J,Ke,ct.value,ue),ct!==null&&(s&&ct.alternate!==null&&De.delete(ct.key===null?Ke:ct.key),G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),Fe}function jt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var Fe=te.key;G!==null;){if(G.key===Fe){if(Fe=te.type,Fe===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===Fe||typeof Fe=="object"&&Fe!==null&&Fe.$$typeof===H&&Ya(Fe)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for(Fe=te.key;G!==null;){if(G.key===Fe)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),jt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if(Fe=Y(te),typeof Fe!="function")throw Error(r(150));return te=Fe.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return jt(J,G,Vc(te),ue);if(te.$$typeof===R)return jt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var Fe=jt(J,G,te,ue);return Vi=null,Fe}catch(De){if(De===Ui||De===Pc)throw De;var lt=ss(29,De,null,J.mode);return lt.lanes=ue,lt.return=J,lt}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(dt&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(Je&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var jt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(jt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(jt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return pn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Qn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Qn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),kt===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Qn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Qn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:pn,use:Yc,useCallback:It,useContext:It,useEffect:It,useImperativeHandle:It,useLayoutEffect:It,useInsertionEffect:It,useMemo:It,useReducer:It,useRef:It,useState:It,useDebugValue:It,useDeferredValue:It,useTransition:It,useSyncExternalStore:It,useId:It,useHostTransitionStatus:It,useFormState:It,useActionState:It,useOptimistic:It,useMemoCache:It,useCacheRefresh:It};ol.useEffectEvent=It;var J0={readContext:pn,use:Yc,useCallback:function(s,a){return An().memoizedState=[s,a===void 0?null:a],s},useContext:pn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=An();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=An();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=An();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=An();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),An().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=An();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),kt===null)throw Error(r(349));(Je&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=An(),a=kt.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[Nn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(vn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Tt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=mn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Tt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Tt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Tt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Tt(a),null;case 10:return jr(a.type),Tt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Tt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(Pt!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&ut()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Tt(a),null}else 2*ut()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=ut(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Tt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Tt(a),a.subtreeFlags&6&&(a.flags|=8192)):Tt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Tt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){vt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){vt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){vt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){vt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){vt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){vt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){vt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){vt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){vt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[Nn]=a}catch(p){vt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Ft));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);vn(a,d,c),a[sn]=s,a[Nn]=c}catch(v){vt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),vn(v,d,c),v[sn]=s,$t(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kjt&&(C=jt,jt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,jt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>jt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(dt&6)!==0)throw Error(r(331));var k=dt;if(dt|=4,Px(v.current),$x(v,v.current,C,c),dt=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(Nt(s,2),Js(s))}function vt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),Nt(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,kt===s&&(Je&c)===c&&(Pt===4||Pt===3&&(Je&62914560)===Je&&300>ut()-lu?(dt&2)===0&&Wi(s,0):sm|=c,Qi===Je&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(Nt(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return ht(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=Je,v=Le(d,d===kt?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||xt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=ut(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),vn(a,"link",s),$t(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),vn(a,"link",s),$t(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),vn(d,"link",s),$t(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");$t(F),vn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),$t(v),vn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),$t(v),vn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),vn(a,"link",c),$t(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,$t(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),$t(d),vn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,$t(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),$t(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),vn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,$t(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),$t(p),vn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,$t(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),$t(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),vn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Ln(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Ln).catch(Ln):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Ln)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch(Ln))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Ln).catch(Ln)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Ln)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Ln)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Ln).catch(Ln)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Ln).catch(Ln)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):Ln;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Ln).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function tt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Ln)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function wn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return tt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(it.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(it.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(it.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(it.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(it.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` .`.concat(FT,` { overflow: hidden `).concat(r,`; padding-right: `).concat(f,"px ").concat(r,`; @@ -47,12 +47,12 @@ Error generating stack: `+d.message+` `)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return` .block-interactivity-`.concat(e,` {pointer-events: none;} .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},pO=0,oo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],l=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Xn(l),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(ot.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ht}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(ot.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(ot.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Un(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(ot.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(ot.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ht=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ht,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),lt=ye.useRef(g.duration||Y||Jw),hn=ye.useRef(null),Nt=ye.useRef(null),Ct=_===0,mn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,vt,yt)=>yt>=hs?ze:ze+vt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{lt.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=Nt.current;if(ze){const vt=ze.getBoundingClientRect().height;return Fe(vt),j(yt=>[{toastId:g.id,height:vt,position:g.position},...yt]),()=>j(yt=>yt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=Nt.current,vt=ze.style.height;ze.style.height="auto";const yt=ze.getBoundingClientRect().height;ze.style.height=vt,Fe(yt),j(Vt=>Vt.find(_t=>_t.toastId===g.id)?Vt.map(_t=>_t.toastId===g.id?{..._t,height:yt}:_t):[{toastId:g.id,height:yt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(vt=>vt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},lt.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var vt;return ye.createElement("div",{className:tr($?.loader,g==null||(vt=g.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":mn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":Ct,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(hn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,vt,yt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=Nt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((vt=Nt.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_t=new Date().getTime()-((yt=hn.current)==null?void 0:yt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/_t;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var nn,Nn;(nn=Nt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(Nn=Nt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var vt,yt,Vt;if(!Q.current||!An||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const _t=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(_t)>1)&&K(Math.abs(En)>Math.abs(_t)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&_t<0||nn.includes("bottom")&&_t>0)Nn.y=_t;else{const Jn=_t*gr(_t);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(yt=Nt.current)==null||yt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=Nt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(it.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(it.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(it.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(it.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(it.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Wn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Wn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Wn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Wn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Wn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Wn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Wn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Wn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Wn(l),x=cr(r)?Wn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Wn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Wn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Wn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(it.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(it.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ft}=je.reference,st=we.floating.style;st.setProperty("--radix-popper-available-width",`${ve}px`),st.setProperty("--radix-popper-available-height",`${Te}px`),st.setProperty("--radix-popper-anchor-width",`${Ze}px`),st.setProperty("--radix-popper-anchor-height",`${ft}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(it.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(it.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(it.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(it.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(it.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),In=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=In(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=In(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(it.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=In(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=In(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Pn=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Pn(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Pn(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(it.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(it.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(it.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(it.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ft=()=>[Ye,Oe,Me],st=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ft()}],"skew-x":[{"skew-x":ft()}],"skew-y":[{"skew-y":ft()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:st()}],"translate-x":[{"translate-x":st()}],"translate-y":[{"translate-y":st()}],"translate-z":[{"translate-z":st()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function nt(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:nt("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Tn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Xn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Xn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Xn.toasts,CL=()=>Xn.getActiveToasts(),Ww=Object.assign(SL,{success:Xn.success,info:Xn.info,warning:Xn.warning,error:Xn.error,custom:Xn.custom,message:Xn.message,promise:Xn.promise,dismiss:Xn.dismiss,loading:Xn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ft,st]=ye.useState(0),[Un,Vn]=ye.useState(0),ze=ye.useRef(g.duration||Y||Jw),mt=ye.useRef(null),pt=ye.useRef(null),ht=_===0,hn=_+1<=S,Et=g.type,On=g.dismissible!==!1,ut=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),jn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,xt,bt)=>bt>=hs?Le:Le+xt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Et==="loading";jn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{ze.current=Hn},[Hn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=pt.current;if(Le){const xt=Le.getBoundingClientRect().height;return Vn(xt),j(bt=>[{toastId:g.id,height:xt,position:g.position},...bt]),()=>j(bt=>bt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=pt.current,xt=Le.style.height;Le.style.height="auto";const bt=Le.getBoundingClientRect().height;Le.style.height=xt,Vn(bt),j(Vt=>Vt.find(Nt=>Nt.toastId===g.id)?Vt.map(Nt=>Nt.toastId===g.id?{...Nt,height:bt}:Nt):[{toastId:g.id,height:bt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),st(jn.current),j(Le=>Le.filter(xt=>xt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,jn]);ye.useEffect(()=>{if(g.promise&&Et==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},ze.current)),()=>clearTimeout(Le)},[R,x,g,Et,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var Le;if(q?.loading){var xt;return ye.createElement("div",{className:tr($?.loader,g==null||(xt=g.classNames)==null?void 0:xt.loader,"sonner-loader"),"data-visible":Et==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Et==="loading"})}const Rt=g.icon||q?.[Et]||uL(Et);var Zt,zt;return ye.createElement("li",{tabIndex:0,ref:pt,className:tr(Z,ut,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Et],g==null||(n=g.classNames)==null?void 0:n[Et]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":hn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":ht,"data-swiping":he,"data-dismissible":On,"data-type":Et,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ft:jn.current}px`,"--initial-height":be?"auto":`${Un}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!On||(mt.current=new Date,st(jn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,xt,bt;if(je||!On)return;Q.current=null;const Vt=Number(((Le=pt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Cn=Number(((xt=pt.current)==null?void 0:xt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Nt=new Date().getTime()-((bt=mt.current)==null?void 0:bt.getTime()),_n=ee==="x"?Vt:Cn,pr=Math.abs(_n)/Nt;if(Math.abs(_n)>=ML||pr>.11){st(jn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":Cn>0?"down":"up"),Ee(),ve(!0);return}else{var nn,En;(nn=pt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(En=pt.current)==null||En.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:Le=>{var xt,bt,Vt;if(!Q.current||!On||((xt=window.getSelection())==null?void 0:xt.toString().length)>0)return;const Nt=Le.clientY-Q.current.y,_n=Le.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(_n)>1||Math.abs(Nt)>1)&&K(Math.abs(_n)>Math.abs(Nt)?"x":"y");let En={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&Nt<0||nn.includes("bottom")&&Nt>0)En.y=Nt;else{const Jn=Nt*gr(Nt);En.y=Math.abs(Jn)0)En.x=_n;else{const Jn=_n*gr(_n);En.x=Math.abs(Jn)0||Math.abs(En.y)>0)&&Ze(!0),(bt=pt.current)==null||bt.style.setProperty("--swipe-amount-x",`${En.x}px`),(Vt=pt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${En.y}px`)}},Gr&&!g.jsx&&Et!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!On?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(zt=q?.close)!=null?zt:vL):null,(Et||g.icon||g.promise)&&g.icon!==null&&(q?.[Et]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?Rt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{qu(g.cancel)&&On&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Xn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Xn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:nt(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:nt("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:nt("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:nt("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:nt("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return tt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return tt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return tt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return tt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return tt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return tt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function zn(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function yt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function Fn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),yt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{yt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",St=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return St(i,DE,t[n]),St(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Pt(i)&&l){const u=IE(i,l);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&St(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?St(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&St(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&St(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&St(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else St(l,z,Q)},H=(z,Q)=>{St(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(l,z)),Se=Re(l,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?St(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):St(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(St(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?St(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):St(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&ht(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?ht(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):St(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&<(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&St(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&St(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||St(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(St(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const yt=h[X];yt&&yt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),vt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),vt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:yt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(yt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(yt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;St(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),lt=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},hn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},Nt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return St(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?hn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;St(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},Ct=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),mn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),Ct(),setTimeout(Ct);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),St(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?St(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)St(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:Nt,unregister:lt,getFieldState:Te,handleSubmit:Ut,setError:ht,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:Ct,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:hn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:mn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:Nt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:lt,setError:ht,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));St(u,"root",l),St(n,r,u)}else St(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function jt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` + color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Mn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Mn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Mn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Mn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Mn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Mn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,xn=e=>e==null;const Lv=e=>typeof e=="object";var Ut=e=>!xn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Ut(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Ut(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Ut(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Ot=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Ut(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>xn(l)?void 0:l[u],e);return Ot(i)||i===e?Ot(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ct=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var bn=e=>typeof e=="string",i8=(e,t,n,r,i)=>bn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>xn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Ut(f)||Array.isArray(f))&&(Ut(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Ut(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return Ct(i,DE,t[n]),Ct(e,n,i),e},yn=e=>Ut(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ot(e[0].attributes.value)?Ot(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(bn(e)||Array.isArray(e)&&e.every(bn)||nr(e)&&!e)return{type:n,message:bn(e)?e:"",ref:t}}var uo=e=>Ut(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Ot(u.value)&&Ot(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||xn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=bn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!xn(g)||!xn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!xn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;xn(le.value)||(Y=$>le.value),xn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";bn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),bn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!xn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&bn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Ut(j)){let Y={};for(const ae in j){if(!yn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!yn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Ut(r)&&yn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Ut(i)&&l){const u=IE(i,l);Ut(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Ut(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Ot(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Ot(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Ot(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,xn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ot(e)?e:t?e===""?NaN:e&&+e:n&&bn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Ot(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&Ct(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Ot(e)?e:Md(e)?e.source:Ut(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Ut(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Ut(t.defaultValues)||Ut(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=yn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?Ct(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!yn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&Ct(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&Ct(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&Ct(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ct(l,z,Q)},H=(z,Q)=>{Ct(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Ot(Re(l,z)),Se=Re(l,z,Ot(X)?Re(i,z):X);Ot(Se)||fe&&fe.defaultChecked||Q?Ct(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Ot(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):Ct(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(Ct(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?Ct(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!yn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Ut(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):Ct(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Ut(X))for(const fe in X){const me=X[fe];me&&ft(`${fp}.${fe}`,{message:bn(me.message)?me.message:"",type:me.type||Fs.validate})}else bn(X)||!X?ft(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),Rt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Rt&&Zt&&A([_e.name],!0);const zt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(Rt&&Zt&&A([_e.name]),zt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(zt,_e.name)?rt?f1(n.errors,zt,_e.name):Ct(n.errors,_e.name,zt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&zt[_e.name]))break}!yn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&&ze(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&Ct(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Ot(Q)?i:bn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&Ct(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&xn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Ut(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||Ct(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Rt=Array.isArray(_e)&&!_e.length||yn(_e);!xe||xe._f||xn(_e)||Rt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const Rt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...Rt&&n,name:u.mount||Rt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,Rt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=Rt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),zt=up(X,f,rt);if(Ct(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const bt=h[X];bt&&bt(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Y(X,Ee,rt),xt=!yn(Le)||zt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!Rt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),xt&&E.state.next({name:X,...zt?{}:Le});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&zt&&E.state.next({...n}),t.resolver){const{errors:bt}=await le([X]);if(A([X]),xe(Ee),!fe){!yn(Le)&&E.state.next(Le);return}const Vt=w1(n.errors,r,X),Cn=w1(bt,r,Vt.name||X);Se=Cn.error,X=Cn.name,_e=yn(bt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,Le))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Ot(z)?z:me);X=yn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&bn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!bn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Ot(z)?X:bn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ft=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;Ct(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},st=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Un=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Vn=z=>(u.mount=!0,S={...S,...z.formState},Un({...z,formState:{...x,...z.formState}})),ze=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},mt=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},pt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return Ct(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?mt({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),pt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Ot(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;Ct(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},ht=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),hn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Et=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),yn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),ht(),setTimeout(ht);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:yn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},On=(z,Q={})=>{Re(r,z)&&(Ot(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),Ct(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},ut=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=yn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),Rt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Ot(Rt)?Ct(xe,Ee,Rt):!rt&&!Ot(Zt)&&I(Ee,Zt)}}else{if(vf&&Ot(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const Rt=rt.closest("form");if(Rt){Rt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)Ct(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!yn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>ut(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},jn={control:{register:pt,unregister:ze,getFieldState:Te,handleSubmit:Et,setError:ft,_subscribe:Un,_runSchema:le,_updateIsValidating:A,_focusError:ht,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:mt,_setErrors:U,_getFieldArray:O,_reset:ut,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:hn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Vn,trigger:je,register:pt,handleSubmit:Et,watch:st,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:On,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!yn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:ze,setError:ft,setFocus:hs,getFieldState:Te};return{...jn,formControl:jn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));Ct(u,"root",l),Ct(n,r,u)}else Ct(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function _t(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` `).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>` ${l}`)];return new t(...n,i.join(` -`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}jt(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));jt(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` +`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}_t(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Dt=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Dt.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Dt.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Dt.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Dt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Dt.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Dt.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Dt.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Dt.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Dt.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Dt.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Dt.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Dt.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Dt.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Dt.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Dt.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Dt.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Dt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Dt.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Dt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Dt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Dt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Dt.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Dt.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));_t(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` if (${T}.issues.length) { if (${A} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ @@ -111,21 +111,21 @@ Error generating stack: `+d.message+` } } - `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),jt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),jt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),jt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),jt(e._zod,"optin",()=>t.innerType._zod.optin),jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),jt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",jt(e._zod,"optout",()=>t.innerType._zod.optout),jt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),jt(e._zod,"values",()=>t.in._zod.values),jt(e._zod,"optin",()=>t.in._zod.optin),jt(e._zod,"optout",()=>t.out._zod.optout),jt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),jt(e._zod,"propValues",()=>t.innerType._zod.propValues),jt(e._zod,"values",()=>t.innerType._zod.values),jt(e._zod,"optin",()=>t.innerType?._zod?.optin),jt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ + `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Sn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),Sn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Dn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),jt(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...In(cn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),l=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Dn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Dn(r.element,n);if(r.type==="set")return Dn(r.valueType,n);if(r.type==="lazy")return Dn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Dn(r.innerType,n);if(r.type==="intersection")return Dn(r.left,n)||Dn(r.right,n);if(r.type==="record"||r.type==="map")return Dn(r.keyType,n)||Dn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Dn(r.in,n)||Dn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Dn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Dn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Dn(i,n))return!0;return!!(r.rest&&Dn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return Sn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return Sn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=Sn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=Sn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=Sn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>Sn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=Sn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=Sn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=Sn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;Sn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),Lt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),Lt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),Lt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),Lt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const Lt=pe("ZodStringFormat",(e,t)=>{Dt.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),Lt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),Lt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),Lt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),Lt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),Lt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),Lt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),Lt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),Lt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),Lt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),Lt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),Lt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),Lt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),Lt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),Lt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),Lt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),Lt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),Lt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),Lt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),Lt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),_t(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:nt("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:nt("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:nt("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:nt("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:nt("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:nt("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Fn(zn(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Tn(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=tt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=tt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await wn(`/api/orgs/${e.id}/invites`),j=await Tn(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Tn(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=tt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Tn(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>wn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Tn(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await wn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=tt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await wn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await wn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:nt("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:nt("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:nt("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:nt("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:nt("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=tt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:nt("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:nt("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=tt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return tt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return tt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return tt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=tt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=tt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?Fn(w.manage_url):null,j=r?.billing?Fn(r.billing.url):null,S=Fn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&&yt("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:nt("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=tt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:nt("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:nt("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:nt("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function $n(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=$n(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!$n(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Fn(cn("install",e.id)),children:"Connect a device"})})})]}),$n(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:$n(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),l=$n(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await wn(`/api/orgs/${t.id}/invites`),j=await Tn(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive -bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` +bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Tn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>yt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&&yt("/setup/connect"),e!=="welcome"&&!t&&yt("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>yt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),yt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return tt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=tt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await wn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{wn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` `).filter(f=>f.trim()).join(` `),t.push(i),i=null)};for(const u of e.split(` `)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(` `).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=cy(e),n=[];let r=0;return e.split(` `).forEach((i,l)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:l+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` `)}function BB(e){return e.split(` -`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` +`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:nt("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CWQeqJPd.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CNasvd30.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(lt=>{Fe&<.status==="success"&&!lt.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(lt=>lt+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const lt=[];B.awareness.getStates().forEach(Ct=>{const mn=Ct.user?.name;mn&<.push(mn)}),K([...new Set(lt)]);const hn=cy(P.current),Nt=new Set;for(const Ct of B.remoteCursors()){const mn=H2(hn,Ct.pos);mn&&Nt.add(mn.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async Fe=>{try{const lt=await Rf(l),hn=je.current;if(lt.kind==="text"&&hn){const Nt=hn.merge(lt.text,lt.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const lt=je.current;return await lt?.saveNow(),we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!lt?.askingShrink()};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),ht=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=lt=>{if(lt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` -`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` -`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ht=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ht=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),gt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{gt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ht,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const lt=b.useRef(null),hn=b.useRef(null),Nt=b.useRef(null),Ct=e.panel??null,mn=!Ct&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!Ct&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!Ct,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const vt=b.useCallback(()=>{ze.current=!0,gt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),yt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):gt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ht&&yt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ht,yt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),_t=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!Ct&&i&&!!l,Jn=!Ct&&Z&&!r.view,Kr=!Ct&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,sn=!Ct&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():hn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(it){ke("Restore failed: "+it.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const it=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(it.changed_after);if(!it.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",it.undone.length," file",it.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:it.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),it.skipped.length>0&&o.jsxs("div",{children:[it.skipped.length," already hold",it.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),it.refused.length>0&&o.jsxs("div",{children:[it.refused.length," path",it.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",it.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(it){ke("Undo failed: "+it.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,it=Zs=>()=>{e.onClosePanel?.(),gt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:it("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:it(Ys)});$t("activity","Activity",cn("history",Le)),$t("insights","Insights",cn("dashboard",Le)),$t("gear","Settings",cn("settings",Le)),$t("laptop","Connect a device",cn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),it=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});mn&&it("share","Share",Ei),it("hist","History",Ts),Z&&it("download","Download",()=>lt.current?.click()),es&&it("printer","Print",Do),_i&&it("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>gt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,mn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),gt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(it){ke("Could not create "+Le+": "+it.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,rn,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(Ct)Hn=Ct.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:Nt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){gt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await Promise.race([Nt.current?.()??Promise.resolve(!0),new Promise(it=>setTimeout(()=>it(!0),1500))])}catch{}Le&&window.location.pathname+window.location.search===Ne&>(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),mn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:vt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:lt,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:hn,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>lt.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:yt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:_t}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:_t,onOpenFolder:ie=>gt(Ln(ie,l.id)),onClose:()=>{ve(!1),_t()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,BM as h,PB as i,o as j,YB as k,xV as l,KB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Tn(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=tt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await wn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CUIsP4dU.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-Dl8vJRj-.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let ze=!0;return w({cancelRefetch:!0}).then(mt=>{ze&&mt.status==="success"&&!mt.isRefetchError&&g(l)}),()=>{ze=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const ze=setInterval(()=>V(mt=>mt+1),5e3);return()=>clearInterval(ze)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const ze=()=>{const mt=[];B.awareness.getStates().forEach(hn=>{const Et=hn.user?.name;Et&&mt.push(Et)}),K([...new Set(mt)]);const pt=cy(P.current),ht=new Set;for(const hn of B.remoteCursors()){const Et=H2(pt,hn.pos);Et&&ht.add(Et.name)}D(ht)};return ze(),B.awareness.on("change",ze),()=>B.awareness.off("change",ze)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async ze=>{try{const mt=await Rf(l),pt=je.current;if(mt.kind==="text"&&pt){const ht=pt.merge(mt.text,mt.sha,{held:ze});re(ht==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e,Ze=x?.kind==="text"&&x.text===""&&!!x.sha;b.useEffect(()=>{if(!Te)return;const ze=async()=>{const mt=je.current;if(!mt)return!0;let pt;const ht=new Promise(hn=>{pt=setTimeout(hn,Ze?5e3:1500)});try{await Promise.race([mt.saveNow(),ht])}catch{}finally{clearTimeout(pt)}return mt.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Te.current=ze,()=>{Te.current===ze&&(Te.current=null)}},[Te,we,t,n,l,Ze]);const ft=b.useRef(0),st=ze=>{ke("Someone else saved this file first. Your version is beside it as "+(ze.split("/").pop()??ze))};b.useEffect(()=>{const ze=mt=>{if(mt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}ft.current>0||re(!0)}};return window.addEventListener("bdrive:changed",ze),()=>window.removeEventListener("bdrive:changed",ze)},[n,i]);const Un=M==="offline",Vn=Un&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Un?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Vn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(ze=>o.jsx(G2,{name:ze,title:ze+" is editing"},ze)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Vn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Un&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(ze=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+ze,"aria-selected":Z===ze,className:Z===ze?"on":"",onClick:()=>W(ze),children:[o.jsx(ge,{name:ze==="write"?"pencil":ze==="markdown"?"code":"eye"}),ze==="write"?"Write":ze==="markdown"?"Markdown":"Preview"]},ze))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:st,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:ze=>{ft.current=ze},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(ze=>ze.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:st,onExternal:ze=>{re(ze==="blocked"),ze==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:ze=>{ft.current=ze},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=tt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=tt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",zn(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=tt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=tt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=$n(e.perm,"admin"),x=$n(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await Tn(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Tn(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Tn(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return tt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await wn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await wn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` +`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(it.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(it.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(it.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(it.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(it.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(it.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(it.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(it.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:nt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:nt("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:nt("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:nt("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=tt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=tt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>zn(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Fn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Fn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Fn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Fn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Fn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Fn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Fn(t(e.path)),children:l})]})}function Rq(e,t){return tt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` +`),{data:r}=tt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Fn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ft=V===null?-1:q.indexOf(V),st=Te.key==="j"?Math.min(q.length-1,ft+1):Math.max(0,ft===-1?0:ft-1);ee(q[st])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ft=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const st=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ft?[ft,st]:st}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=tt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await Tn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=tt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=tt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),yt(zn(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const $e of _H(H))Ne.add($e);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const $e=new Set(Ne);return $e.has(ie)?$e.delete(ie):$e.add(ie),$e})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{yt(zn(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>yt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ft,st]=b.useState(!1),[Un,Vn]=b.useState("");b.useEffect(()=>n3(ie=>{Vn(ie??""),st(!0)}),[]);const ze=b.useRef(null),mt=b.useRef(null),pt=b.useRef(null),ht=e.panel??null,hn=!ht&&i&&!!l&&(Z||U)&&$n(l.perm,"write"),Et=ie=>K2(_,ie)?.me,On=!ht&&Z&&!L&&(!i||!!l&&$n(Et(M)??l.perm,"write")),ut=!!r.editing&&On;b.useEffect(()=>{if(!On||!Z||ut)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[On,Z,ut]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let $e=0;$emr||[],[mr]),z=jn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!ht,[rt,Rt]=b.useState(null),Zt=b.useRef(null),zt=b.useRef(null),Le=b.useRef(!1);b.useEffect(()=>{Le.current=!1},[M]);const xt=b.useCallback(()=>{Le.current=!0,yt(zn(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),bt=b.useCallback(()=>{Le.current?(Le.current=!1,history.back()):yt(zn(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ft&&bt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ft,bt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?zt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:Cn}=mE(l?.id,i&&!!l),Nt=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),_n=Z?(Cn||[]).filter(ie=>ie.path===M):[],{data:pr}=tt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,En=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await Tn(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!ht&&i&&!!l,Jn=!ht&&Z&&!r.view,Kr=!ht&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!ut,sn=!ht&&(Z||i&&!!l&&U),Nn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():mt.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await Tn(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&$n(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,$e)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+($e?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await wn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(ot){ke("Restore failed: "+ot.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),$t=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await wn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,$e=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const ot=await wn(n+"undo-run",{...$e,preview:!0}),Ft=new Set(ot.changed_after);if(!ot.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",ot.undone.length," file",ot.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:ot.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),Ft.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),Ft.size>0&&o.jsxs("div",{className:"undo-warn",children:[Ft.size," file",Ft.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Ft.size===1?"that change":"those changes"," too."]}),ot.skipped.length>0&&o.jsxs("div",{children:[ot.skipped.length," already hold",ot.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),ot.refused.length>0&&o.jsxs("div",{children:[ot.refused.length," path",ot.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",ot.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await wn(n+"undo-run",$e);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(ot){ke("Undo failed: "+ot.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Vn(""),st($e=>!$e))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=$e=>ie.push($e);if(i&&l){const $e=l.id,ot=Zs=>()=>{e.onClosePanel?.(),yt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:ot("/"+$e)});const Ft=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:ot(Ys)});Ft("activity","Activity",cn("history",$e)),Ft("insights","Insights",cn("dashboard",$e)),Ft("gear","Settings",cn("settings",$e)),Ft("laptop","Connect a device",cn("install",$e))}if(i&&l&&M){const $e=M.slice(M.lastIndexOf("/")+1),ot=(Ft,Zs,ps)=>Ne({icon:Ft,label:Zs,hint:$e,kind:"action",group:$e,run:ps});hn&&ot("share","Share",Ei),ot("hist","History",Ts),Z&&ot("download","Download",()=>ze.current?.click()),es&&ot("printer","Print",Do),_i&&ot("copy","Copy",zo)}if(i)for(const $e of e.projects||[])(!l||$e.id!==l.id)&&Ne({icon:"folder",label:$e.name,kind:"project",group:"Projects",run:()=>yt("/"+$e.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const $e of y.keys())Ne({icon:"folder",label:$e,kind:"folder",run:()=>I($e)});for(const $e of m)qr($e.path)||Ne({icon:"doc",label:$e.path,kind:"file",run:()=>I($e.path)});return ie},[i,l,M,Z,hn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),kn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&kn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&$n(l.perm,"write"),Io=b.useCallback(ie=>!!l&&$n(Et(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const $e=(ie?ie+"/":"")+Ne;if(Yr.has($e)||y.has($e)){ke($e+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent($e),""),await f.invalidateQueries({queryKey:["tree",n]}),yt(zn($e,l?.id,void 0,!1,!0)),ds()}catch(ot){ke("Could not create "+$e+": "+ot.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await Tn(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&$n(l.perm,"write")?async ie=>{const Ne=(Cn||[]).find($e=>$e.path===ie);if(Ne){const $e=await Tn(Ne.url);ke($e?"Share link copied":Ne.url,!$e);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>yt(cn("dashboard",l.id,ie)):void 0,remove:ms?$t:void 0}),[Fa,Ia,Io,rn,i,l,Cn,I,re,ms,$t,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,qn;if(ht)qn=ht.body;else if(r.view==="dashboard")Ks="wide",qn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",qn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:$t,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>zn(ie,l?.id,Ne),onFilters:ie=>yt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)qn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)qn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)qn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);qn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:ut,editSource:Bs,me:Gr,commentable:Hn,flushRef:pt});return Hn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:jn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),qn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):qn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(qn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),qn]}));const jc=ht?ht.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!ut&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Hn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),On&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{ut||(jp(),gS(f,n,M))},onFocus:()=>{ut||(jp(),gS(f,n,M))},title:ut?"Stop editing":"Edit this file",onClick:async()=>{if(!ut){yt(zn(M,l?.id,L,r.full,!0));return}const ie=zn(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let $e=!0;try{$e=await(pt.current?.()??Promise.resolve(!0))}catch{}$e&&window.location.pathname+window.location.search===Ne&&yt(ie)},children:[!ut&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:ut?"Done":"Edit"})]}),ut&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),hn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:xt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Nn,ref:ze,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:mt,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>ze.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:En,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),yt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:kn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:kn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:zt,onClick:bt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!ht&&Z&&o.jsx(b7,{shares:_n,canRevoke:!!l&&$n(l.perm,"write"),onChanged:Nt}),qn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:Rt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:Cn||[],onChanged:Nt,onOpenFolder:ie=>yt(zn(ie,l.id)),onClose:()=>{ve(!1),Nt()}}),Hn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:jn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:$n(l?.perm,"admin")}),o.jsx(cq,{open:ft,onClose:()=>st(!1),candidates:zf,recent:xc,initialQuery:Un})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?yt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await wn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),yt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);yt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>yt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Fn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):zn(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Fn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),yt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:zn(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),yt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),yt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return wn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:zn(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-BHUrOeP7.js b/internal/webapp/static/assets/sharedfile-CSb7vEsh.js similarity index 57% rename from internal/webapp/static/assets/sharedfile-BHUrOeP7.js rename to internal/webapp/static/assets/sharedfile-CSb7vEsh.js index b5662aa9..111fbb4f 100644 --- a/internal/webapp/static/assets/sharedfile-BHUrOeP7.js +++ b/internal/webapp/static/assets/sharedfile-CSb7vEsh.js @@ -1,17 +1,17 @@ -import{H as et,h as Sn,i as Ht,k as zo,f as Tr,e as xr,l as bn,m as Go}from"./index-AIvST0b2.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},Dt=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){Dt(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const wt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ci=e=>e!==0?e<0:1/e<0,Or=1,Lr=2,ps=4,ws=8,ze=32,Nt=64,ct=128,Wn=31,Ts=63,se=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Rr=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&wt(e)===e),ai=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Ur=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rGe.encode(e),hl=Ge?al:cl;let Ye=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ye&&Ye.decode(new Uint8Array).length===1&&(Ye=null);const ul=(e,t)=>Zo(t,()=>e).join("");class rn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new rn,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>se;)q(e,ct|se&t),t=wt(t/128);q(e,se&t)},Ws=(e,t)=>{const n=ci(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=wt(t/64);t>0;)q(e,(t>se?ct:0)|se&t),t=wt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ce(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),Mr=new DataView(new ArrayBuffer(4)),kl=e=>(Mr.setFloat32(0,e),Mr.getFloat32(0)===e),Xe=(e,t)=>{switch(typeof t){case"string":q(e,119),re(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(Ce(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Nr=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new rn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Nr(this),this.count=1,this.s=t)}toUint8Array(){return Nr(this),B(this.encoder)}}const $r=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new rn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):($r(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new rn;return this.sarr.push(this.s),this.s="",re(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const _t=e=>new Error(e),pt=()=>{throw _t("Method unimplemented")},at=()=>{throw _t("Unexpected case")},hi=_t("Unexpected end of array"),ui=_t("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),De=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw ui}throw hi},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw ui}throw hi},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(De(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(De(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>Ye.decode(K(e)),Wt=Ye?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-De(e)](e);class Fr extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ci(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=wt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),fi=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^fi()&15>>e/4).toString(16)),zt=Date.now,Br=e=>new Promise(e);Promise.all.bind(Promise);const Vr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let di=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(di=localStorage,Gs=!1)}catch{}const gi=di,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Qe=Symbol("Equality"),pi=(e,t)=>e===t||!!e?.[Qe]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},on=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&on(e,(n,s)=>(n!==void 0||Xs(t,s))&&pi(t[s],n)),Pl=Object.freeze,wi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&wi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ye=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Qe]!=null)return e[Qe](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var mi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",yi=typeof window<"u"&&typeof document<"u"&&!Gt;let kt;const Yl=()=>{if(kt===void 0)if(Gt){kt=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");kt.set(`--${Ur(t,"-")}`,n),kt.set(`-${Ur(t,"-")}`,n)}})):kt=rt();return kt},Ls=e=>Yl().has(e),Rn=e=>Vr(Gt?mi[e.toUpperCase().replaceAll("-","_")]:gi.getItem(e)),ki=e=>Ls("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Gt&&Wl(mi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!ki("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),Si=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=Si(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=yi?Ql:Zl,sc=yi?tc:ec,rc=e=>{const t=Si(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),jr=e=>e.next()>=.5,ks=(e,t,n)=>wt(e.next()*(n+1-t)+t),bi=(e,t,n)=>wt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>bi(e,t,n),lc=e=>ai(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Qe]?pi(e,t):Ce(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?on(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ye(this.shape,t.shape)}[ac](){return!0}[Qe](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){pt()}get nullable(){return Ue(this,Qn)}get optional(){return new Ci(this)}cast(t){return Hr(t,this),t}expect(t){return Hr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),_i=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ei=e=>{if(Ae.check(e))return[uc(e)];if(_i.check(e))return e.shape.map(t=>t+"");if(Ui.check(e))return["[+-]?\\d+.?\\d*"];if(Mi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ei).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ei).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Ci extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Ci);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):on(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Di extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&on(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ai=(e,t)=>new Di(e,t),kc=J(Di);class Ii extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&on(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ii(e);J(Ii);class Ti extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=Ce(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const xi=(...e)=>new Ti(e),bc=J(Ti),_c=G(e=>Ce(e));class Oi extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Oi(e,t);J(Oi);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Ue=(...e)=>e.findIndex(t=>Un.check(t))>=0?Ue(...e.map(t=>Ze(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Li=()=>!0,Mn=G(Li),xc=J(tr,e=>e.shape===Li),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ri=G(e=>typeof e=="symbol");G(e=>e===Ri);const ke=G(e=>typeof e=="number"),Ui=G(e=>e===ke),Ae=G(e=>typeof e=="string"),Mi=G(e=>e===Ae),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),vi=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Ue(ke,Ae,Qn,vi,nr,Kn,Ri);(()=>{const e=xi(Mn),t=Ai(Ae,Mn),n=Ue(ke,Ae,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const Ze=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=Ze(e[n]);return wc(t)}else{if(_c.check(e))return Ue(...e.map(Ze));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Hr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw _t(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:Ze(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),Ni=vc(Mn).if(Ui,(e,t)=>ks(t,Rr,On)).if(Mi,(e,t)=>cc(t)).if(Lc,(e,t)=>jr(t)).if(Oc,(e,t)=>BigInt(ks(t,Rr,On))).if(Un,(e,t)=>de(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(jr(t))continue;r=r.shape}n[s]=Ni(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=bi(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=de(t,e.res);return()=>n}).if(xc,(e,t)=>de(t,Ss(t,[ke,Ae,Qn,vi,nr,Kn,xi(ke),Ai(Ue("a","b","c"),ke)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;rNi(Ze(t),e),At=typeof document<"u"?document:{},Nc=e=>At.createElement(e),$c=()=>At.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>At.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n($i(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),$i=(e,t)=>e.appendChild(t),Pc=At.ELEMENT_NODE,Jc=At.TEXT_NODE;At.CDATA_SECTION_NODE;At.COMMENT_NODE;const Wc=At.DOCUMENT_NODE;At.DOCUMENT_TYPE_NODE;const Yc=At.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Fi=Ft(),Bi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),Vi=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...ji(e)),Pi.forEach(t=>t.print(e))},Hi=(...e)=>{console.warn(...ji(e)),e.unshift(sr),Pi.forEach(t=>t.print(e))},Pi=qt(),Ji=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Ji(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Ji(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class Me{constructor(){this.clients=new Map}}const Ie=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=wt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ce(r.len,i.clock+i.len-r.clock)):(s{const t=new Me;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{Dt(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new Me,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},ve=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new Me,n=E(e.restDecoder);for(let s=0;s0){const o=Dt(t.clients,r,()=>[]);for(let l=0;l{const s=new Me,r=E(e.restDecoder);for(let i=0;i0){const i=new ie;return _(i.restEncoder,0),ve(i,s),i.toUint8Array()}return null},Wi=fi;class ae extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Wi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Br(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Br(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&U(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return U(this,t,n)}get(t,n=z){const s=Dt(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,_e)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,xe)}getXmlElement(t=""){return this.get(t,Le)}getXmlFragment(t=""){return this.get(t,oe)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new ae({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,U(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Yi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class qi extends Yi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return De(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class Te extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Fr(K(t),De),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Fr(K(t),De),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new Se(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Se(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ce(s,t[0].id.clock);const r=Et(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new ro,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==dt){const p=Dt(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new ie;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new Te(e))=>U(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Pr(s,r,l);if(l.pendingDs){const f=new Te(Xt(l.pendingDs));E(f.restDecoder);const d=Pr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Xi(r.doc,f)}},n,!1),Xi=(e,t,n,s=Te)=>{const r=Xt(t);ua(r,e,n,new s(r))},Ki=(e,t,n)=>Xi(e,t,n,qi),fa=(e,t,n=new Map)=>{or(e,t.store,n),ve(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new ie)=>{const s=Zi(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===cn)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===ie)return Nn(r)}return r[0]},Qi=(e,t)=>da(e,t,new cn),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new Yi(Xt(e))),to=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>to(e,ts(t.store)),wa=(e,t=new Gi)=>(e instanceof Map?to(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new zi);class ya{constructor(){this.l=[]}}const Jr=()=>new ya,Wr=(e,t)=>e.l.push(t),Yr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},eo=(e,t,n)=>Ks(e.l,[t,n]);class Se{constructor(t,n){this.client=t,this.clock=n}}const me=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new Se(e,t),no=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class so{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new so(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=no(e):s=D(e._item.id.client,e._item.id.clock),new so(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=be(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof M))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:be(s,i)};if(a instanceof M&&a.content instanceof It)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&me(e.item,t.item)&&me(e.type,t.type)&&e.assoc===t.assoc,pe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ln(t.ds,e.id),Ms=(e,t)=>{const n=Dt(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class ro{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},io=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Et=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=wt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Et(n,t.clock)]},be=Ca,vs=(e,t,n)=>{const s=Et(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},qr=(e,t,n)=>{const s=t.clients.get(n.client),r=Et(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ft&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Et(s,t.id.clock)]=n},oo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),ve(e,t.deleteSet),!0),Gr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&Dt(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof M&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Et(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Et(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},lo=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{eo(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ce(Et(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Et(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Fi,"[yjs] ",Bi,Vi,"Changed the client-id because another client seems to be using it."),s.clientID=Wi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new cn;zr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new ie;zr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):lo(e,t+1)}}},U=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&lo(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Xr=(e,t,n)=>{Ie(e,n.deletions,s=>{s instanceof M&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Kr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;U(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Ie(l,h.insertions,d=>{if(d instanceof M){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Ie(l,h.deletions,d=>{d instanceof M&&i.some(p=>p===l.doc||vn(p,d))&&!ln(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Ao(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=Ce(t)?t[0].doc:t instanceof ae?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new Me;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&tn(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Ie(c,c.deleteSet,b=>{b instanceof M&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=Ce(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Hi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Xr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Xr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Kr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Kr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,qi,cn),Ra=(e,t)=>{if(e.constructor===ft){const{client:n,clock:s}=e.id;return new ft(D(n,s+t),e.length-t)}else if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new M(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=Te,n=ie)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===dt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===dt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==dt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return ve(o,h),o.toUint8Array()},Ua=(e,t,n=Te,s=ie)=>{const r=Zi(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===dt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ce(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return ve(i,h),i.toUint8Array()},co=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&co(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{co(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return ve(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,Te,cn),Qr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return ln(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw _t(Qr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw _t(Qr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Hi("Invalid access: Add Yjs type to a document before reading data.")},ao=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},ho=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ao){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ce(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;Dt(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;eo(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Jr(),this._dEH=Jr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw pt()}clone(){throw pt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Wr(this._eH,t)}observeDeep(t){Wr(this._dEH,t)}unobserve(t){Yr(this._eH,t)}unobserveDeep(t){Yr(this._dEH,t)}toJSON(){}}const uo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},fo=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return nn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},po=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new le(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new an(new Uint8Array(u))),r.integrate(e,0);break;case ae:r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new M(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new It(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},wo=()=>_t("Length exceeded!"),mo=(e,t,n,s)=>{if(n>t._length)throw wo();if(n===0)return t._searchMarker&&en(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},yo=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw wo();t._searchMarker&&en(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new le([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new le([s]);break;case Uint8Array:l=new an(s);break;case ae:l=new hn(s);break;default:if(s instanceof z)l=new It(s);else throw new Error("Unexpected content type")}new M(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},So=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&pe(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class _e extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new _e;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new _e}clone(){const t=new _e;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?U(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return po(this,t)}toArray(){return fo(this)}slice(t=0,n=this.length){return uo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return go(this,t)}forEach(t){nn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new _e;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class xe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new xe}clone(){const t=new xe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return So(this,t)}clear(){this.doc!==null?U(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new xe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||Ne(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Zr=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||Ne(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return Zr(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return Zr(e,o,n)}},bo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new M(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},Ne=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},_o=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Eo=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new M(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r),c=s.constructor===String?new Ct(s):s instanceof z?new It(s):new he(s);let{left:h,right:a,index:u}=n;t._searchMarker&&en(t._searchMarker,n.index,c.getLength()),a=new M(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),bo(e,t,n,l)},ti=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;_o(n,r);const l=Eo(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new M(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Ct(c)),n.right.integrate(e,0),n.forward()}bo(e,t,n,l)},Co=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&Ne(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return U(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?Ne(o,r.content):(t+=Co(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&oo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==ft&&t.add(o.parent)})}U(n,s=>{Ie(e,e.deleteSet,r=>{if(r instanceof ft||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ei=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case It:case he:case Ct:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];U(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case It:case he:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Ct:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),Ne(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ct&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?U(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ti(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ei(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(pe(c,t)||n!==void 0&&pe(c,n))switch(c.content.constructor){case Ct:{const u=i.get("ychange");t!==void 0&&!pe(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!pe(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case It:case he:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:pe(c,t)&&(h(),Ne(i,c.content));break}c=c.right}h()};return t||n?U(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?U(s,r=>{ei(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?U(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ti(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Oe;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Le||n.constructor===oe)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class oe extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new oe}clone(){const t=new oe;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return go(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),nn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?U(this.doc,s=>{mo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)U(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw _t("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?U(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return fo(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return po(this,t)}slice(t=0,n=this.length){return uo(this,t,n)}forEach(t){nn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new oe;class Le extends oe{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Le(this.nodeName)}clone(){const t=new Le(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?U(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?U(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return So(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return nn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Le(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends xe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw pt()}mergeWith(t){return!1}write(t,n,s){throw pt()}integrate(t,n){throw pt()}}const sh=0;class ft extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),io(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class an{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new an(this.content)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new an(e.readBuf());class sn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new sn(this.len)}splice(t){const n=new sn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){tn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new sn(e.readLen()),Do=(e,t)=>new ae({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class hn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hn(Do(this.doc.guid,this.opts))}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new hn(Do(e.readString(),e.readAny()));class he{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new he(this.embed)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new he(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Ct(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class It{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new It(this.type._copy())}splice(t){throw pt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new It(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=be(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof M);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new M(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ni=(e,t)=>js(e,n=>ln(n.deletions,t)),Ao=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Ao(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||ln(s,u.right.id)||ni(i.undoStack,u.right.id)||ni(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new M(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class M extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Lr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Or)>0}set keep(t){this.keep!==t&&(this.info^=Or)}get countable(){return(this.info&Lr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Se&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=qr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ft||this.right&&this.right.constructor===ft)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===M?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===M&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Se){const s=be(n,this.parent);s.constructor===ft?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=qr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),me(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),tn(t.deleteSet,this.id.client,this.id.clock,this.length),Gr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new ft(this.id,this.length)):this.content=new sn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:ze);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=no(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===Se?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const Io=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},xo="__ $YJS$ __";To[xo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");To[xo]=!0;const Oo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){gi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>Dt(Oo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Oo.delete(e)),s},we=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Lo=0,wr=1,Ro=2,Fs=(e,t)=>{_(e,Lo);const n=ma(t);H(e,n)},Uo=(e,t,n)=>{_(e,wr),H(e,Qi(t,n))},Th=(e,t,n)=>Uo(t,n,K(e)),Mo=(e,t,n,s)=>{try{Ki(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Ro),H(e,t)},Oh=Mo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Lo:Th(e,t,n);break;case wr:Mo(e,n,s,r);break;case Ro:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class vo extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},wt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ye(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},qe=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ee=0,No=3,Ee=1,Nh=2,un=[];un[ee]=(e,t,n,s,r)=>{_(e,ee);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};un[No]=(e,t,n,s,r)=>{_(e,Ee),H(e,qe(n.awareness,Array.from(n.awareness.getStates().keys())))};un[Ee]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};un[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const si=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),$o=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Fo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Fo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=$o(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ee),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ee),H(s,qe(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&we(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new vo(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=un.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ee),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=$o(this,new Uint8Array(d),!1);Js(y)>1&&we(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ee),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ee),H(S,qe(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&si{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Qi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ri||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let L;w===0?L=0:O===-w||O!==w&&S[O-1+w-1]=r&&v>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=L,d=v}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-YIhaBYDQ.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const yt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&yt(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=yt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=yt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=yt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),kl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Et=e=>new Error(e),mt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},ui=Et("Unexpected end of array"),fi=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=yt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ki=typeof window<"u"&&typeof document<"u"&&!Gt;let St;const Yl=()=>{if(St===void 0)if(Gt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Mr(t,"-")}`,n),St.set(`-${Mr(t,"-")}`,n)}})):St=rt();return St},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),Si=e=>Ls("--"+e)||Rn(e)!==null,ql=Si("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!Si("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=ki?Ql:Zl,sc=ki?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,ks=(e,t,n)=>yt(e.next()*(n+1-t)+t),_i=(e,t,n)=>yt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){mt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),kc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const Se=G(e=>typeof e=="number"),Mi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>ks(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(ks(t,Ur,On))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,Ni,nr,Kn,Oi(Se),Ii(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;r$i(tn(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=yt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==gt){const p=At(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof Tt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=yt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==dt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Ct(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Ct(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Ct(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&en(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===gt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===gt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==gt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===gt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw mt()}clone(){throw mt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Et("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},ko=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},So=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==dt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof dt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return So(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):So(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw mt()}mergeWith(t){return!1}write(t,n,s){throw mt()}integrate(t,n){throw mt()}}const sh=0;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===dt||this.right&&this.right.constructor===dt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===dt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new dt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},yt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ce),H(S,ze(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&S[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` `)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=St(e,s),l=St(t,s),c=St(n,s),h=bt(o,i),a=[...Re(h,bt(l,i)).map(b=>({h:b,toks:l,side:0})),...Re(h,bt(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",L=S;for(const v of b)v.side===w&&(O+=u(o,L,v.h.aS)+u(v.toks,v.h.bS,v.h.bE),L=v.h.aE);return O+u(o,L,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),L=f(b,1,w,S);if(O===L){d+=O;continue}if(w===S){const F=qh(O,L,s!==As,o.length===0);if(F===null){if(!r)return null;d+=L;continue}d+=F;continue}if(s===As)return null;const v=s===Pn?Jn(u(o,w,S),O,L,As):Jn(u(o,w,S),O,L,s+1,r);if(v===null){if(!r)return null;d+=L;continue}d+=v}return d+u(o,p,o.length)}const ne=e=>e===""||e.endsWith(` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),h=_t(o,i),a=[...Ue(h,_t(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,_t(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",R=S;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),R=f(b,1,w,S);if(O===R){d+=O;continue}if(w===S){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,S),O,R,As):Jn(u(o,w,S),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(` `)?e:e+` -`;function Bo(e,t,n,s){let r=t.endsWith(` +`;function Vo(e,t,n,s){let r=t.endsWith(` `);return r===e.endsWith(` `)&&(r=n.endsWith(` `)),s===""||r===s.endsWith(` `)?s:r?s+` -`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(ne(e),ne(t),ne(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Bo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(ne(e),ne(t),ne(n),Yt,!0)??ne(n);return Bo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` -`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function ii(e,t){if(e===t)return[];const n=[],s=new Map,r=St(e,Yt),i=St(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=bt(St(t,Yt),s),i=Re(bt(St(e,Yt),s),r),o=Re(r,bt(St(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function We(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const oi=700,ge=[2e3,4e3,8e3,15e3],li=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",L=0;const v=(g=Date.now())=>{const k=Math.max(g,L+1e3);return L=k,zo(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,Tt=!1,ht=null,$e=0,rs=!1,tt=null,xt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let Ot=!1,Fe=null,Qt=0;const Be=()=>{Ot=!1,Fe=null},is=g=>{Qt===g&&Be()};let it=0,gt=0,fn=null,Zt=null,os=!1,Vt=null,Lt=null,Ve=!1,te=null,ut=null;const N=g=>e.onState?.(g),dn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let gn=null,ls=0;const je=()=>{clearTimeout(gn??void 0),gn=null},pn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;je();const m=ge[Math.min(ls,ge.length-1)];ls++,gn=setTimeout(()=>{gn=null,!f&&!a&&He()},m)},kr=()=>{je(),ls=0},wn=()=>{je(),te&&clearTimeout(te),te=setTimeout(()=>{He()},oi)},Rt=g=>{if(f)return p=g,!0;const k=$();if(k===g)return!0;const m=ii(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},He=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Pe();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await Vo()}finally{Zt=null}})();return Zt=g,g},Vo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=$();if(k===n&&!xt){N("clean");return}if(N("saving"),e.onWriting?.(),Tt){if(S!==null&&A===k){if(await mn(k,O)==="stop")return;continue}Tt=!1}const m=c||h?await jo(k):await Po(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await mn($(),s??"");return}continue}if(!os){N($()===n&&!xt?"clean":"dirty");return}}};let mt=!1;const jo=async g=>{Lt=g,Ve=!1;let k;try{k=await Sn(dn(e.path),g,s,mt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&We(m)?(mt=!1,ue(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":(N("error"),pn(m),"stop")}return Lt=null,mt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(Ve||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await Tr(xr(e.apiBase,e.path))}catch(R){return N("error"),$()!==n&&pn(R),!1}if(m.kind!=="text")return N("error"),!1;const I=$(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await mn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Ho=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){xt=!0;const m=t(k.sent,g.text,$());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Po=async g=>{Lt=g,Ve=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...mt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&We(C))return mt=!1,ue(g),"stop";if(C instanceof et&&C.status===409&&!a){let R={};try{R=JSON.parse(C.body)}catch{}const j=typeof R.text=="string"?R.text:null;if(j!==null){const X=t(n,j,$());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(R.sha),"rebased"}return mn($(),R.sha??"")}return N(a?"dirty":"error"),pn(C),"stop"}if(Lt=null,mt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,xt=!1,a)return"stop";const I=t(g,k.text,$());return I.ok&&Rt(I.text)&&(Ve||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ue=g=>{Y||f||!e.onShrinkRefused||(N("error"),Y={was:bn(n),now:bn(g),confirm:async()=>{if(!f){if(a){N("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!Ot&>>=it;N(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&>{if(!f)try{const k=await Tr(xr(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;N(gt>=it&&!Ot?"clean":"dirty");return}gt=it,d&&(d=0,e.onPending?.(0)),Be(),N("clean")}catch{N("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let yt=null;const Jo=()=>{yt&&clearTimeout(yt),yt=setTimeout(()=>{const g=$();Go(bn(n),bn(g))&&ue(g)},oi)},Sr=async(g,k,m=v())=>{const I=++Kt;let C=m;for(let R=1;;R++){const j=C;F.set(j,g);try{return await Sn(dn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),N("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&R{const C=(R,j)=>{Sn(dn(R),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??R),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=v(),A=g);const m=S;O=k,Tt=!0;const I=await Sr(g,k,m);return f?"stop":I?(pn(I.err),"stop"):(Tt=!1,A===g&&(S=null,A=null,O=""),$()!==g?"rebased":"stop")},as=(g,k)=>{gt=Math.max(gt,g),is(k),!(f||u)&&(d=it-gt,e.onPending?.(d))},Wo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},li))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(gt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(fn)return fn;const k=(async()=>{try{for(;!u&&!f&&!Y&>{y=!1,S=null,A=null,$e=0,clearTimeout(ht??void 0),ht=null,xt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Pe=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){$()!==n&&wn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=ge[Math.min($e,ge.length-1)];$e++,ht=setTimeout(()=>{ht=null,Pe()},X);return}finally{w=!1}if(f||a)return;if(Ho(j),!u){($()!==n||xt)&&wn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(ii(k,m.text)));y=!0,(S===null||A!==g)&&(S=v(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Pe()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const R=ge[Math.min($e,ge.length-1)];$e++,ht=setTimeout(()=>{ht=null,Pe()},R)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,je(),a||Pe(),gt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if(N("dirty"),a){Ot=!0,Fe=m,Qt+=1,u||(it+=1,d=it-gt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},li)),Jo();return}wn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const $=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},Yo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=$();if(g===I)return r(g,k),a&&(Be(),N("clean")),"same";if(a){const R=n;return Bt.includes(g)||Dn(R,g,I)?(r(g,k),Ot&&(Fe===null||g===Fe||Dn(R,Fe,g))&&(Be(),N("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Be(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(Ve=!0),r(g,k),Rt(C.text),C.text!==g?wn():Lt===null&&N("clean"),C.text===I?"same":"merged"):"blocked"};let yn=null;const qo=()=>{if(!a)return He();if(Y||f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!Ot)return Promise.resolve();if(yn)return yn;const g=Qt;N("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),N(Ot?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&We(m)&&(clearTimeout(yt??void 0),yt=null,ue($()),Y))return;N(Ot?"dirty":"clean")}finally{yn=null}})();return yn=k,k};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&Ot))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(y||Tt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=v(),br(V,g,T);return}if(g===n&&!xt)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){He();return}Ut=m;const I=n,C=!(c||h),R=tt,j={sent:g,from:I,prev:R};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=R),T instanceof et&&T.status===422&&We(T)){kn(m)(),f||(clearTimeout(yt??void 0),yt=null,ue($()));return}if(!(T instanceof et&&T.status===409))return kn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,$());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;Tt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=v(),S=Mt,A=g,br(Mt,g,m,lt=>{Tt=!1,e.onConflictCopy?.(lt)})},Je=(T,V)=>{n=g,i=void 0,ot(V),!f&&$()===g&&N("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,R),park_on_conflict:!0},!0).then(T=>{if(mt=!1,tt===j&&(tt=null),xt=!1,T.parked)return Je(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,$());V.ok&&Rt(V.text)&&(r(T.text,T.sha),$()===n&&N("clean")),e.onSaved?.(T.text)},X):us=Sn(dn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return Je(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&$()===n&&N("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr($(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:$,merge:Yo,rebase:ot,saveNow:qo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(yt??void 0),je(),clearTimeout(ht??void 0),ht=null;const g=$();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{ae as D,oi as S,au as U,lu as a,ka as b,Ea as c,ii as d,cu as e,Ps as f,ce as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t}; +`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` +`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,Yt),i=bt(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,Yt),s),i=Ue(_t(bt(e,Yt),s),r),o=Ue(r,_t(bt(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",R=0;const N=(g=Date.now())=>{const k=Math.max(g,R+1e3);return R=k,Go(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,xt=!1,ht=null,Fe=0,rs=!1,tt=null,Ot=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let kt=!1,Be=null,Qt=0;const Ve=()=>{kt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,pt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},kr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const k=L();if(k===g)return!0;const m=oi(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=L();if(k===n&&!Ot){$("clean");return}if($("saving"),e.onWriting?.(),xt){if(S!==null&&A===k){if(await yn(k,O)==="stop")return;continue}xt=!1}const m=c||h?await Ho(k):await Jo(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!Ot?"clean":"dirty");return}}};let wt=!1;const Ho=async g=>{Lt=g,je=!1;let k;try{k=await bn(gn(e.path),g,s,wt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(wt=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,wt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){Ot=!0;const m=t(k.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...wt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return wt=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,wt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,Ot=!1,a)return"stop";const I=t(g,k.text,L());return I.ok&&Rt(I.text)&&(je||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ee=g=>{Y||f||!e.onShrinkRefused||($("error"),Y={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!kt&&pt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&pt{if(!f)try{const k=await xr(Or(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;$(pt>=it&&!kt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let ft=null;const Wo=()=>{ft&&clearTimeout(ft),ft=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},Sr=async(g,k,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=N(),A=g);const m=S;O=k,xt=!0;const I=await Sr(g,k,m);return f?"stop":I?(wn(I.err),"stop"):(xt=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(f||u)&&(d=it-pt,e.onPending?.(d))},Yo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const k=(async()=>{try{for(;!u&&!f&&!Y&&pt{y=!1,S=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,Ot=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||Ot)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(oi(k,m.text)));y=!0,(S===null||A!==g)&&(S=N(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if($("dirty"),a){kt=!0,Be=m,Qt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=L();if(g===I)return r(g,k),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,k),kt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,k),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let kn=null;const zo=()=>{if(!f){if(Y)return Promise.resolve();if((a?u?kt:d>0:L()!==n)&&!wt&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(ft??void 0),ft=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!kt)return Promise.resolve();if(kn)return kn;const g=Qt;$("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(kt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(ft??void 0),ft=null,ee(L()),Y))return;$(kt?"dirty":"clean")}finally{kn=null}})();return kn=k,k};let Ut=null;const Sn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&kt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),Sn(V));return}if(y||xt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!Ot)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){Sn(m)(),f||(clearTimeout(ft??void 0),ft=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return Sn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;xt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),S=Mt,A=g,br(Mt,g,m,lt=>{xt=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(wt=!1,tt===j&&(tt=null),Ot=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,wt,!0,!0).then(T=>{if(wt=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(ft??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,au as U,lu as a,ka as b,Ea as c,oi as d,cu as e,Ps as f,ae as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 6dc8ff17..e5bf76cb 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + From 87c64063d53f32e4a60208d788eb7b3f719263ba Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:44:32 +0900 Subject: [PATCH 08/34] fix(webapp): await server shrink verdict before Done leaves --- .../frontend/src/components/FileView.tsx | 26 ++++--- .../webapp/frontend/src/lib/sharedfile.ts | 16 +++++ .../src/lib/sharedfile_restore.test.ts | 71 +++++++++++++++++-- ...{Editor-CUIsP4dU.js => Editor-DzIcnMyR.js} | 2 +- ...dit-Dl8vJRj-.js => VisualEdit-CQ41m5Hk.js} | 2 +- .../{index-YIhaBYDQ.js => index-CiZlXtW0.js} | 34 ++++----- ...ile-CSb7vEsh.js => sharedfile-UW7NkjEZ.js} | 20 +++--- internal/webapp/static/index.html | 2 +- 8 files changed, 128 insertions(+), 45 deletions(-) rename internal/webapp/static/assets/{Editor-CUIsP4dU.js => Editor-DzIcnMyR.js} (99%) rename internal/webapp/static/assets/{VisualEdit-Dl8vJRj-.js => VisualEdit-CQ41m5Hk.js} (97%) rename internal/webapp/static/assets/{index-YIhaBYDQ.js => index-CiZlXtW0.js} (89%) rename internal/webapp/static/assets/{sharedfile-CSb7vEsh.js => sharedfile-UW7NkjEZ.js} (77%) diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx index 569595e6..89d08b51 100644 --- a/internal/webapp/frontend/src/components/FileView.tsx +++ b/internal/webapp/frontend/src/components/FileView.tsx @@ -511,26 +511,30 @@ function EditView(props: Parameters[0]) { void qc.invalidateQueries({ queryKey: ["render", apiBase, path] }); }; const { flushRef } = props; - /* A read that came back empty yet names a version: the file may hold more - than this buffer was seeded with, so only the hub can tell a shrink (its - 422), and its answer gets longer before Done gives up waiting. */ - const onlyHubSeesShrink = data?.kind === "text" && data.text === "" && !!data.sha; useEffect(() => { if (!flushRef) return; /* Save and leave: the save gets a moment, never a veto — a hub that does not answer must not trap the user in the editor. A question the user - must answer does keep them here, however it opened: before any request - (a shrink known here), or from the hub's answer within the wait. */ + must answer does keep them here, however it opened. The one exception + to the moment: a save only the hub can refuse as a shrink is waited out + in full, since leaving before its answer would close the editor under + the question it opens. */ const flush = async () => { const f = fileHandle.current; if (!f) return true; + const mustSettle = f.mayServerRefuseShrink(); + const saving = f.saveNow(); // Promise constructor, not withResolvers: the app targets ES2022. let timer: ReturnType | undefined; - const waited = new Promise((r) => { - timer = setTimeout(r, onlyHubSeesShrink ? 5_000 : 1_500); - }); try { - await Promise.race([f.saveNow(), waited]); + if (mustSettle) await saving; + else + await Promise.race([ + saving, + new Promise((r) => { + timer = setTimeout(r, 1_500); + }), + ]); } catch { // The editor's own teardown still sends what it holds. } finally { @@ -545,7 +549,7 @@ function EditView(props: Parameters[0]) { return () => { if (flushRef.current === flush) flushRef.current = null; }; - }, [flushRef, qc, apiBase, path, fileURL, onlyHubSeesShrink]); + }, [flushRef, qc, apiBase, path, fileURL]); // Co-editors in this document right now. A write while somebody else is in // the room is their snapshot of the document I already have — warning about // it would fire on every co-editing save. Alone, the same event means diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index fb28928e..0970763d 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -72,6 +72,10 @@ const MAX_REBASES = 4; const MAX_CONFLICT_TRIES = 64; const MAX_EXIT_COPY_TRIES = 8; +// The sha of no bytes: a base naming it is a known-empty file, which nothing +// can shrink. +const EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + // Above this, a staging checkpoint names its ancestor by sha alone when it can // (the hub reads the blob) instead of carrying it as text. const INLINE_BASE_MAX = 32_000; @@ -91,6 +95,12 @@ export type SharedFile = { /** A shrink question is waiting on the user: leaving now would leave it unanswered (Done stays on the editor). */ askingShrink(): boolean; + /** A save now could still be refused by the hub as a sharp shrink that + nothing here can see: `saved` is empty while the base names a non-empty + version, or a solo write lands on a file a peer may have grown. Done + then waits for the save's outcome, however long, rather than leave on a + timer before the question could open. */ + mayServerRefuseShrink(): boolean; /** Fold an outside write — an agent, a CLI, another device — into the open document. "blocked" means the caller should SAY so instead, because this refused to resolve it. `held` says the hub has already put this text @@ -1500,6 +1510,12 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { rebase, saveNow, askingShrink: () => asking !== null, + mayServerRefuseShrink: () => { + if (asking || gone || confirmShrinkOnce || !opts.onShrinkRefused) return false; + if (!base || base === EMPTY_SHA256) return false; + if (hubHoldsIt) return saved === "" && (localDirtyInRoom || pending > 0); + return (saved === "" && (current() !== "" || roomNeedsFlush)) || ((solo || noRoomHttp) && current() !== saved); + }, destroy() { if (typeof window !== "undefined") { window.removeEventListener("pagehide", onPageHide); diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 9418eef4..d0b8843a 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -2242,8 +2242,9 @@ for (const mode of ["live", "offline", "staging", "solo"] as const) { /* A shrink only the hub can see: the read seeded an empty buffer (`saved` is "", so nothing local is a shrink) and the hub refuses the save 422, - slowly. The question opens when the answer comes, and Done — waiting on - the save — finds it open and stays. */ + ten seconds later. The file says so (mayServerRefuseShrink), so Done waits + the save out instead of leaving on a timer; the question opens when the + answer comes, and Done finds it open and stays. */ test("a shrink the hub refuses 422 after a slow answer still asks before Done leaves", async () => { fakeTimers(); try { @@ -2252,7 +2253,7 @@ test("a shrink the hub refuses 422 after a slow answer still asks before Done le reqs.push((init?.method ?? "GET") + " " + decodeURIComponent(String(url))); // The hub answers late (fake clock: advance() moves it). const late = Promise.withResolvers(); - setTimeout(late.resolve, 800); + setTimeout(late.resolve, 10_000); await late.promise; return new Response(JSON.stringify({ error: "would cut most of the file", shrink: true }), { status: 422 }); }) as typeof fetch; @@ -2278,11 +2279,12 @@ test("a shrink the hub refuses 422 after a slow answer still asks before Done le await waitFor(() => assert.equal(solo, true)); buffer = "x\n"; + assert.equal(file.mayServerRefuseShrink(), true); let settled = false; void file.saveNow().then(() => { settled = true; }); - await advance(799); + await advance(9_999); assert.equal(reqs.length, 1); assert.equal(settled, false); assert.equal(file.askingShrink(), false); @@ -2290,12 +2292,73 @@ test("a shrink the hub refuses 422 after a slow answer still asks before Done le assert.equal(settled, true); assert.equal(file.askingShrink(), true); assert.equal(asks.length, 1); + assert.equal(file.mayServerRefuseShrink(), false); // the question is open file.destroy(); } finally { realTimers(); } }); +/* When a save could meet a shrink refusal nothing here can see — and when + it cannot, so Done keeps its short wait. */ +test("mayServerRefuseShrink is true only where the hub alone can see a shrink", async () => { + fakeTimers(); + const solos: SharedFile[] = []; + try { + globalThis.fetch = (async () => new Response("{}", { status: 200 })) as typeof fetch; + const openSolo = async (seed: string, baseSha: string | undefined, buffer: string) => { + let solo = false; + const file = openSharedFile({ + apiBase: "/api/", + path: "notes.md", + seed, + baseSha, + me: { name: "t", colour: "oklch(0.7 0.1 200)" }, + onReady: () => {}, + onSolo: () => { + solo = true; + }, + onShrinkRefused: () => {}, + soloText: () => buffer, + soloApply: () => {}, + }); + solos.push(file); + await waitFor(() => assert.equal(solo, true)); + return file; + }; + // Empty `saved`, a version that is not the empty file: only the hub knows. + assert.equal((await openSolo("", "sha-big", "x\n")).mayServerRefuseShrink(), true); + // Solo over a file a peer may have grown since it was read. + assert.equal((await openSolo("a\nb\nc\n", "sha-a", "a\nb\n")).mayServerRefuseShrink(), true); + // No version to be conditional on, or the version of no bytes. + assert.equal((await openSolo("", undefined, "x\n")).mayServerRefuseShrink(), false); + const empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + assert.equal((await openSolo("", empty, "x\n")).mayServerRefuseShrink(), false); + // Nothing to save. + assert.equal((await openSolo("a\nb\nc\n", "sha-a", "a\nb\nc\n")).mayServerRefuseShrink(), false); + } finally { + for (const f of solos) f.destroy(); + await settle(); // their unmount saves land on this test's fetch + realTimers(); + } + + // A room, live or staging, over a non-empty `saved`: every shrink is local. + for (const mode of ["live", "staging"] as const) { + fakeTimers(); + const h = await heldRoom(); + try { + if (mode === "live") { + await h.goLive(); + h.localEdit((t) => t.insert(t.length, "d\n")); + } else h.state.buffer = "a\nb\nc\nd\n"; + assert.equal(h.file.mayServerRefuseShrink(), false); + } finally { + h.done(); + realTimers(); + } + } +}); + /* Keep, with the socket down, after Done asked about a sharp shrink: the deletion is queued in this tab's document, so putting the file's bytes back is an edit the room must get too — over HTTP at once, or, if that diff --git a/internal/webapp/static/assets/Editor-CUIsP4dU.js b/internal/webapp/static/assets/Editor-DzIcnMyR.js similarity index 99% rename from internal/webapp/static/assets/Editor-CUIsP4dU.js rename to internal/webapp/static/assets/Editor-DzIcnMyR.js index 1a758b28..b8b1a50c 100644 --- a/internal/webapp/static/assets/Editor-CUIsP4dU.js +++ b/internal/webapp/static/assets/Editor-DzIcnMyR.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-YIhaBYDQ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CSb7vEsh.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-CiZlXtW0.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-UW7NkjEZ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js b/internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js similarity index 97% rename from internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js rename to internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js index b47227e8..635a1eff 100644 --- a/internal/webapp/static/assets/VisualEdit-Dl8vJRj-.js +++ b/internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js @@ -1 +1 @@ -import{r as i,j as y,w as ge,a as me}from"./index-YIhaBYDQ.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-CSb7vEsh.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; +import{r as i,j as y,w as ge,a as me}from"./index-CiZlXtW0.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-UW7NkjEZ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit}; diff --git a/internal/webapp/static/assets/index-YIhaBYDQ.js b/internal/webapp/static/assets/index-CiZlXtW0.js similarity index 89% rename from internal/webapp/static/assets/index-YIhaBYDQ.js rename to internal/webapp/static/assets/index-CiZlXtW0.js index 11ed4953..08bcf5a6 100644 --- a/internal/webapp/static/assets/index-YIhaBYDQ.js +++ b/internal/webapp/static/assets/index-CiZlXtW0.js @@ -1,13 +1,13 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CUIsP4dU.js","assets/sharedfile-CSb7vEsh.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-Dl8vJRj-.js"])))=>i.map(i=>d[i]); -import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Rn={};var sw;function QR(){if(sw)return Rn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,ft;function st(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",ft=-1i.map(i=>d[i]); +import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,mt;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",mt=-1)":-1p||F[d]!==ne[p]){var ce=` -`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Un=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?st(c):""}function ze(s,a){switch(s.tag){case 26:case 27:case 5:return st(s.type);case 16:return st("Lazy");case 13:return s.child!==a&&a!==null?st("Suspense Fallback"):st("Suspense");case 19:return st("SuspenseList");case 0:case 15:return Vn(s.type,!1);case 11:return Vn(s.type.render,!1);case 1:return Vn(s.type,!0);case 31:return st("Activity");default:return""}}function mt(s){try{var a="",c=null;do a+=ze(s,c),c=s,s=s.return;while(s);return a}catch(d){return` +`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function it(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function nn(s){try{var a="",c=null;do a+=it(s,c),c=s,s=s.return;while(s);return a}catch(d){return` Error generating stack: `+d.message+` -`+d.stack}}var pt=Object.prototype.hasOwnProperty,ht=e.unstable_scheduleCallback,hn=e.unstable_cancelCallback,Et=e.unstable_shouldYield,On=e.unstable_requestPaint,ut=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Hn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,jn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,Rt=262144,Zt=4194304;function zt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=zt(d):(C&=k,C!==0?p=zt(C):c||(c=k&~s,c!==0&&(p=zt(c))))):(k=d&~v,k!==0?p=zt(k):C!==0?p=zt(C):c||(c=d&~s,c!==0&&(p=zt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function xt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function bt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function Cn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Nt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function _n(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function an(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+kn(a)):s.value!==""+kn(a)&&(s.value=""+kn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,kn(a)):c!=null?Ia(s,C,kn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+kn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+kn(c):"",a=a!=null?""+kn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(et=De,De=null):et=De.sibling;var ct=se(J,De,te[Ke],ue);if(ct===null){De===null&&(De=et);break}s&&De&&ct.alternate===null&&a(J,De),G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct,De=et}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),Fe;if(De===null){for(;KeKe?(et=De,De=null):et=De.sibling;var ya=se(J,De,ct.value,ue);if(ya===null){De===null&&(De=et);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),lt===null?Fe=ya:lt.sibling=ya,lt=ya,De=et}if(ct.done)return c(J,De),at&&wr(J,Ke),Fe;if(De===null){for(;!ct.done;Ke++,ct=te.next())ct=de(J,ct.value,ue),ct!==null&&(G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct);return at&&wr(J,Ke),Fe}for(De=d(De);!ct.done;Ke++,ct=te.next())ct=oe(De,J,Ke,ct.value,ue),ct!==null&&(s&&ct.alternate!==null&&De.delete(ct.key===null?Ke:ct.key),G=v(ct,G,Ke),lt===null?Fe=ct:lt.sibling=ct,lt=ct);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),Fe}function jt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var Fe=te.key;G!==null;){if(G.key===Fe){if(Fe=te.type,Fe===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===Fe||typeof Fe=="object"&&Fe!==null&&Fe.$$typeof===H&&Ya(Fe)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for(Fe=te.key;G!==null;){if(G.key===Fe)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),jt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if(Fe=Y(te),typeof Fe!="function")throw Error(r(150));return te=Fe.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return jt(J,G,Vc(te),ue);if(te.$$typeof===R)return jt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var Fe=jt(J,G,te,ue);return Vi=null,Fe}catch(De){if(De===Ui||De===Pc)throw De;var lt=ss(29,De,null,J.mode);return lt.lanes=ue,lt.return=J,lt}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(dt&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(Je&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var jt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(jt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(jt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return pn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Qn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Qn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),kt===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Qn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Qn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,nn(s,c)}}var ol={readContext:pn,use:Yc,useCallback:It,useContext:It,useEffect:It,useImperativeHandle:It,useLayoutEffect:It,useInsertionEffect:It,useMemo:It,useReducer:It,useRef:It,useState:It,useDebugValue:It,useDeferredValue:It,useTransition:It,useSyncExternalStore:It,useId:It,useHostTransitionStatus:It,useFormState:It,useActionState:It,useOptimistic:It,useMemoCache:It,useCacheRefresh:It};ol.useEffectEvent=It;var J0={readContext:pn,use:Yc,useCallback:function(s,a){return An().memoizedState=[s,a===void 0?null:a],s},useContext:pn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=An();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=An();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=An();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=An();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),An().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=An();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),kt===null)throw Error(r(349));(Je&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=An(),a=kt.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[sn]=a,v[Nn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(vn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Tt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=mn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[sn]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[sn]=a,a.stateNode=s}return Tt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Tt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[sn]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Tt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Tt(a),null;case 10:return jr(a.type),Tt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Tt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(Pt!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&ut()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Tt(a),null}else 2*ut()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=ut(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Tt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Tt(a),a.subtreeFlags&6&&(a.flags|=8192)):Tt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Tt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){vt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){vt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){vt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){vt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){vt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){vt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){vt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){vt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){vt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[Nn]=a}catch(p){vt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Ft));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);vn(a,d,c),a[sn]=s,a[Nn]=c}catch(v){vt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,dn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,dn=a;dn!==null;)if(a=dn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,dn=s;else for(;dn!==null;){switch(a=dn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),vn(v,d,c),v[sn]=s,$t(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kjt&&(C=jt,jt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,jt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>jt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(on=0,Xi=ua=null,Ar=0,(dt&6)!==0)throw Error(r(331));var k=dt;if(dt|=4,Px(v.current),$x(v,v.current,C,c),dt=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(Nt(s,2),Js(s))}function vt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),Nt(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,kt===s&&(Je&c)===c&&(Pt===4||Pt===3&&(Je&62914560)===Je&&300>ut()-lu?(dt&2)===0&&Wi(s,0):sm|=c,Qi===Je&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(Nt(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return ht(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=Je,v=Le(d,d===kt?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||xt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=ut(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}on!==0&&on!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=an(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),vn(a,"link",s),$t(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+an(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+an(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+an(c.imageSizes)+'"]')):p+='[href="'+an(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),vn(a,"link",s),$t(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+an(d)+'"][href="'+an(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),vn(d,"link",s),$t(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");$t(F),vn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),$t(v),vn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),$t(v),vn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+an(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),vn(a,"link",c),$t(a),s.head.appendChild(a))}function so(s){return'[src="'+an(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+an(c.href)+'"]');if(d)return a.instance=d,$t(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),$t(d),vn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,$t(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),$t(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),vn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,$t(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),$t(p),vn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,$t(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),$t(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),vn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Ln(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Ln).catch(Ln):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Ln)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch(Ln))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Ln).catch(Ln)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Ln)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Ln)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Ln).catch(Ln)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Ln).catch(Ln)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),fn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=fn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):Ln;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Ln).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function tt(e,t){return tj(e,XS)}function FM(e,t){const n=fn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Ln)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function wn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return tt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],it=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(it.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(it.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(it.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(it.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(it.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` +`+d.stack}}var yt=Object.prototype.hasOwnProperty,ht=e.unstable_scheduleCallback,sn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function xt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function bt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Et(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function ln(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function jt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),jt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return jt(J,G,Vc(te),ue);if(te.$$typeof===R)return jt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=jt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,rn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var jt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(jt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(jt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Nt===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,rn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Nt===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Nt.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[an]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[an]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[an]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[an]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[an]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){gt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){gt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){gt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){gt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){gt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){gt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){gt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){gt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){gt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){gt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[an]=s,a[kn]=c}catch(v){gt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[an]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kjt&&(C=jt,jt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,jt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>jt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(cn=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(Et(s,2),Js(s))}function gt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),Et(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Nt===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(Et(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return ht(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Nt?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||xt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}cn!==0&&cn!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=ln(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+ln(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+ln(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+ln(c.imageSizes)+'"]')):p+='[href="'+ln(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+ln(d)+'"][href="'+ln(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+ln(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+ln(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+ln(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var fn=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),fn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){fn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),fn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){fn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return fn.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){fn.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){fn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){fn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){fn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return fn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;fn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return fn.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=fn.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return fn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=fn.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),mn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(fn.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=mn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(fn.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),` .`.concat(FT,` { overflow: hidden `).concat(r,`; padding-right: `).concat(f,"px ").concat(r,`; @@ -47,12 +47,12 @@ Error generating stack: `+d.message+` `)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return` .block-interactivity-`.concat(e,` {pointer-events: none;} .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},pO=0,oo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],l=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(it.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(it.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(it.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(it.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(it.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Wn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Wn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Wn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Wn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Wn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Wn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Wn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Wn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Wn(l),x=cr(r)?Wn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Wn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Wn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Wn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(it.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(it.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:ft}=je.reference,st=we.floating.style;st.setProperty("--radix-popper-available-width",`${ve}px`),st.setProperty("--radix-popper-available-height",`${Te}px`),st.setProperty("--radix-popper-anchor-width",`${Ze}px`),st.setProperty("--radix-popper-anchor-height",`${ft}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(it.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(it.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(it.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(it.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(it.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(it.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),In=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=In(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=In(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(it.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=In(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=In(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=In(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Pn=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Pn(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Pn(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(it.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(it.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(it.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(it.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],ft=()=>[Ye,Oe,Me],st=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:ft()}],"skew-x":[{"skew-x":ft()}],"skew-y":[{"skew-y":ft()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:st()}],"translate-x":[{"translate-x":st()}],"translate-y":[{"translate-y":st()}],"translate-z":[{"translate-z":st()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function nt(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:nt("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Tn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Xn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Xn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Xn.toasts,CL=()=>Xn.getActiveToasts(),Ww=Object.assign(SL,{success:Xn.success,info:Xn.info,warning:Xn.warning,error:Xn.error,custom:Xn.custom,message:Xn.message,promise:Xn.promise,dismiss:Xn.dismiss,loading:Xn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[ft,st]=ye.useState(0),[Un,Vn]=ye.useState(0),ze=ye.useRef(g.duration||Y||Jw),mt=ye.useRef(null),pt=ye.useRef(null),ht=_===0,hn=_+1<=S,Et=g.type,On=g.dismissible!==!1,ut=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),jn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,xt,bt)=>bt>=hs?Le:Le+xt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Et==="loading";jn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{ze.current=Hn},[Hn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=pt.current;if(Le){const xt=Le.getBoundingClientRect().height;return Vn(xt),j(bt=>[{toastId:g.id,height:xt,position:g.position},...bt]),()=>j(bt=>bt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=pt.current,xt=Le.style.height;Le.style.height="auto";const bt=Le.getBoundingClientRect().height;Le.style.height=xt,Vn(bt),j(Vt=>Vt.find(Nt=>Nt.toastId===g.id)?Vt.map(Nt=>Nt.toastId===g.id?{...Nt,height:bt}:Nt):[{toastId:g.id,height:bt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),st(jn.current),j(Le=>Le.filter(xt=>xt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,jn]);ye.useEffect(()=>{if(g.promise&&Et==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},ze.current)),()=>clearTimeout(Le)},[R,x,g,Et,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var Le;if(q?.loading){var xt;return ye.createElement("div",{className:tr($?.loader,g==null||(xt=g.classNames)==null?void 0:xt.loader,"sonner-loader"),"data-visible":Et==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Et==="loading"})}const Rt=g.icon||q?.[Et]||uL(Et);var Zt,zt;return ye.createElement("li",{tabIndex:0,ref:pt,className:tr(Z,ut,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Et],g==null||(n=g.classNames)==null?void 0:n[Et]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":hn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":ht,"data-swiping":he,"data-dismissible":On,"data-type":Et,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ft:jn.current}px`,"--initial-height":be?"auto":`${Un}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!On||(mt.current=new Date,st(jn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,xt,bt;if(je||!On)return;Q.current=null;const Vt=Number(((Le=pt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Cn=Number(((xt=pt.current)==null?void 0:xt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Nt=new Date().getTime()-((bt=mt.current)==null?void 0:bt.getTime()),_n=ee==="x"?Vt:Cn,pr=Math.abs(_n)/Nt;if(Math.abs(_n)>=ML||pr>.11){st(jn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":Cn>0?"down":"up"),Ee(),ve(!0);return}else{var nn,En;(nn=pt.current)==null||nn.style.setProperty("--swipe-amount-x","0px"),(En=pt.current)==null||En.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:Le=>{var xt,bt,Vt;if(!Q.current||!On||((xt=window.getSelection())==null?void 0:xt.toString().length)>0)return;const Nt=Le.clientY-Q.current.y,_n=Le.clientX-Q.current.x;var pr;const nn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(_n)>1||Math.abs(Nt)>1)&&K(Math.abs(_n)>Math.abs(Nt)?"x":"y");let En={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(nn.includes("top")||nn.includes("bottom"))if(nn.includes("top")&&Nt<0||nn.includes("bottom")&&Nt>0)En.y=Nt;else{const Jn=Nt*gr(Nt);En.y=Math.abs(Jn)0)En.x=_n;else{const Jn=_n*gr(_n);En.x=Math.abs(Jn)0||Math.abs(En.y)>0)&&Ze(!0),(bt=pt.current)==null||bt.style.setProperty("--swipe-amount-x",`${En.x}px`),(Vt=pt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${En.y}px`)}},Gr&&!g.jsx&&Et!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!On?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(zt=q?.close)!=null?zt:vL):null,(Et||g.icon||g.promise)&&g.icon!==null&&(q?.[Et]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?Rt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{qu(g.cancel)&&On&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Xn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Xn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:nt(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:nt("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:nt("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:nt("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:nt("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return tt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=fn();return()=>e.fetchQuery(dE)}function fE(e){return tt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return tt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return tt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return tt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return tt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=fn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function zn(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function yt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function Fn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),yt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{yt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Xn(l),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(ot.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:mt}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${mt}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(ot.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(ot.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Un(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(ot.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(ot.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],un=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=un("color"),t=un("font"),n=un("text"),r=un("font-weight"),i=un("tracking"),l=un("leading"),u=un("breakpoint"),f=un("container"),h=un("spacing"),m=un("radius"),y=un("shadow"),g=un("inset-shadow"),w=un("text-shadow"),x=un("drop-shadow"),j=un("blur"),S=un("perspective"),E=un("aspect"),_=un("ease"),N=un("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],mt=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:mt()}],"skew-x":[{"skew-x":mt()}],"skew-y":[{"skew-y":mt()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[mt,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),it=ye.useRef(g.duration||Y||Jw),nn=ye.useRef(null),yt=ye.useRef(null),ht=_===0,sn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,xt,bt)=>bt>=hs?ze:ze+xt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{it.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=yt.current;if(ze){const xt=ze.getBoundingClientRect().height;return Fe(xt),j(bt=>[{toastId:g.id,height:xt,position:g.position},...bt]),()=>j(bt=>bt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=yt.current,xt=ze.style.height;ze.style.height="auto";const bt=ze.getBoundingClientRect().height;ze.style.height=xt,Fe(bt),j(Vt=>Vt.find(Et=>Et.toastId===g.id)?Vt.map(Et=>Et.toastId===g.id?{...Et,height:bt}:Et):[{toastId:g.id,height:bt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(xt=>xt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},it.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var xt;return ye.createElement("div",{className:tr($?.loader,g==null||(xt=g.classNames)==null?void 0:xt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:yt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":sn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":ht,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?mt:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(nn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,xt,bt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=yt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((xt=yt.current)==null?void 0:xt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Et=new Date().getTime()-((bt=nn.current)==null?void 0:bt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/Et;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var rn,Nn;(rn=yt.current)==null||rn.style.setProperty("--swipe-amount-x","0px"),(Nn=yt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var xt,bt,Vt;if(!Q.current||!An||((xt=window.getSelection())==null?void 0:xt.toString().length)>0)return;const Et=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const rn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(Et)>1)&&K(Math.abs(En)>Math.abs(Et)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(rn.includes("top")||rn.includes("bottom"))if(rn.includes("top")&&Et<0||rn.includes("bottom")&&Et>0)Nn.y=Et;else{const Jn=Et*gr(Et);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(bt=yt.current)==null||bt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=yt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=mn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function dn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function vt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),vt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{vt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Mn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Mn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Mn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Mn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Mn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Mn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Mn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Mn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Mn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,xn=e=>e==null;const Lv=e=>typeof e=="object";var Ut=e=>!xn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Ut(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Ut(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Ut(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Ot=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Ut(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>xn(l)?void 0:l[u],e);return Ot(i)||i===e?Ot(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ct=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var bn=e=>typeof e=="string",i8=(e,t,n,r,i)=>bn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>xn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Ut(f)||Array.isArray(f))&&(Ut(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Ut(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return Ct(i,DE,t[n]),Ct(e,n,i),e},yn=e=>Ut(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ot(e[0].attributes.value)?Ot(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(bn(e)||Array.isArray(e)&&e.every(bn)||nr(e)&&!e)return{type:n,message:bn(e)?e:"",ref:t}}var uo=e=>Ut(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Ot(u.value)&&Ot(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||xn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=bn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!xn(g)||!xn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!xn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;xn(le.value)||(Y=$>le.value),xn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";bn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),bn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!xn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&bn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Ut(j)){let Y={};for(const ae in j){if(!yn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!yn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Ut(r)&&yn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Ut(i)&&l){const u=IE(i,l);Ut(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Ut(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Ot(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Ot(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Ot(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,xn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ot(e)?e:t?e===""?NaN:e&&+e:n&&bn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Ot(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&Ct(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Ot(e)?e:Md(e)?e.source:Ut(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Ut(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Ut(t.defaultValues)||Ut(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=yn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?Ct(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!yn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&Ct(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&Ct(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&Ct(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ct(l,z,Q)},H=(z,Q)=>{Ct(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Ot(Re(l,z)),Se=Re(l,z,Ot(X)?Re(i,z):X);Ot(Se)||fe&&fe.defaultChecked||Q?Ct(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Ot(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):Ct(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(Ct(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?Ct(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!yn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Ut(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):Ct(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Ut(X))for(const fe in X){const me=X[fe];me&&ft(`${fp}.${fe}`,{message:bn(me.message)?me.message:"",type:me.type||Fs.validate})}else bn(X)||!X?ft(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),Rt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Rt&&Zt&&A([_e.name],!0);const zt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(Rt&&Zt&&A([_e.name]),zt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(zt,_e.name)?rt?f1(n.errors,zt,_e.name):Ct(n.errors,_e.name,zt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&zt[_e.name]))break}!yn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&&ze(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&Ct(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Ot(Q)?i:bn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&Ct(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&xn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Ut(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||Ct(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Rt=Array.isArray(_e)&&!_e.length||yn(_e);!xe||xe._f||xn(_e)||Rt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const Rt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...Rt&&n,name:u.mount||Rt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,Rt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=Rt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),zt=up(X,f,rt);if(Ct(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const bt=h[X];bt&&bt(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Y(X,Ee,rt),xt=!yn(Le)||zt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!Rt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),xt&&E.state.next({name:X,...zt?{}:Le});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&zt&&E.state.next({...n}),t.resolver){const{errors:bt}=await le([X]);if(A([X]),xe(Ee),!fe){!yn(Le)&&E.state.next(Le);return}const Vt=w1(n.errors,r,X),Cn=w1(bt,r,Vt.name||X);Se=Cn.error,X=Cn.name,_e=yn(bt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,Le))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Ot(z)?z:me);X=yn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&bn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!bn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Ot(z)?X:bn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},ft=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;Ct(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},st=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Un=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Vn=z=>(u.mount=!0,S={...S,...z.formState},Un({...z,formState:{...x,...z.formState}})),ze=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},mt=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},pt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return Ct(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?mt({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),pt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Ot(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;Ct(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},ht=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),hn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Et=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),yn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),ht(),setTimeout(ht);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:yn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},On=(z,Q={})=>{Re(r,z)&&(Ot(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),Ct(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},ut=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=yn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),Rt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Ot(Rt)?Ct(xe,Ee,Rt):!rt&&!Ot(Zt)&&I(Ee,Zt)}}else{if(vf&&Ot(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const Rt=rt.closest("form");if(Rt){Rt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)Ct(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!yn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>ut(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},jn={control:{register:pt,unregister:ze,getFieldState:Te,handleSubmit:Et,setError:ft,_subscribe:Un,_runSchema:le,_updateIsValidating:A,_focusError:ht,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:mt,_setErrors:U,_getFieldArray:O,_reset:ut,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:hn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Vn,trigger:je,register:pt,handleSubmit:Et,watch:st,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:On,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!yn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:ze,setError:ft,setFocus:hs,getFieldState:Te};return{...jn,formControl:jn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));Ct(u,"root",l),Ct(n,r,u)}else Ct(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function _t(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` + color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ct=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return Ct(i,DE,t[n]),Ct(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Pt(i)&&l){const u=IE(i,l);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&Ct(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?Ct(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&Ct(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&Ct(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&Ct(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ct(l,z,Q)},H=(z,Q)=>{Ct(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(l,z)),Se=Re(l,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?Ct(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):Ct(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(Ct(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?Ct(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):Ct(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&mt(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?mt(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):Ct(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&&it(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&Ct(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&Ct(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||Ct(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(Ct(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const bt=h[X];bt&&bt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),xt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),xt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:bt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(bt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(bt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},mt=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;Ct(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),it=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},nn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},yt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return Ct(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?nn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),yt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;Ct(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},ht=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),sn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),ht(),setTimeout(ht);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),Ct(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?Ct(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)Ct(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:yt,unregister:it,getFieldState:Te,handleSubmit:Ut,setError:mt,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:ht,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:nn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:sn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:yt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:it,setError:mt,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));Ct(u,"root",l),Ct(n,r,u)}else Ct(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function _t(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` `).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>` ${l}`)];return new t(...n,i.join(` -`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}_t(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Dt=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Dt.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Dt.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Dt.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Dt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Dt.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Dt.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Dt.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Dt.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Dt.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Dt.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Dt.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Dt.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Dt.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Dt.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Dt.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Dt.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Dt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Dt.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Dt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Dt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Dt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Dt.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Dt.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));_t(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` +`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}_t(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));_t(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(` if (${T}.issues.length) { if (${A} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ @@ -111,21 +111,21 @@ Error generating stack: `+d.message+` } } - `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Sn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),Sn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Dn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ + `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Dn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Dn(r.element,n);if(r.type==="set")return Dn(r.valueType,n);if(r.type==="lazy")return Dn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Dn(r.innerType,n);if(r.type==="intersection")return Dn(r.left,n)||Dn(r.right,n);if(r.type==="record"||r.type==="map")return Dn(r.keyType,n)||Dn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Dn(r.in,n)||Dn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Dn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Dn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Dn(i,n))return!0;return!!(r.rest&&Dn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return Sn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return Sn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=Sn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=Sn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=Sn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>Sn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=Sn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=Sn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=Sn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;Sn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),Lt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),Lt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),Lt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),Lt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const Lt=pe("ZodStringFormat",(e,t)=>{Dt.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),Lt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),Lt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),Lt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),Lt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),Lt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),Lt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),Lt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),Lt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),Lt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),Lt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),Lt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),Lt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),Lt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),Lt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),Lt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),Lt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),Lt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),Lt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),Lt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),_t(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:nt("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:nt("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:nt("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:nt("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:nt("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:nt("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Fn(zn(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Tn(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=fn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=tt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=tt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await wn(`/api/orgs/${e.id}/invites`),j=await Tn(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Tn(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=fn(),n=`/api/orgs/${e.id}/apps`,{data:r}=tt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Tn(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>wn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Tn(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await wn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=fn(),{data:t,error:n}=tt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await wn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await wn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:nt("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:nt("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:nt("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:nt("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:nt("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=fn(),n=tt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:nt("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:nt("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=tt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return tt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return tt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return tt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=tt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=tt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?Fn(w.manage_url):null,j=r?.billing?Fn(r.billing.url):null,S=Fn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&&yt("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:nt("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=tt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:nt("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:nt("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:nt("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function $n(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=$n(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!$n(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Fn(cn("install",e.id)),children:"Connect a device"})})})]}),$n(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=fn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:$n(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=fn(),{data:r,error:i}=Nv(e.id),l=$n(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await wn(`/api/orgs/${t.id}/invites`),j=await Tn(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),_t(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?" (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=mn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+" · ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=mn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&&vt("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...In(dn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=mn(),{data:r,error:i}=Nv(e.id),l=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV} to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive -bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Tn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>yt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&&yt("/setup/connect"),e!=="welcome"&&!t&&yt("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>yt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),yt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return tt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=tt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=fn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await wn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{wn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` +bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>vt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&&vt("/setup/connect"),e!=="welcome"&&!t&&vt("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>vt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),vt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=mn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(` `).filter(f=>f.trim()).join(` `),t.push(i),i=null)};for(const u of e.split(` `)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(` `).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=cy(e),n=[];let r=0;return e.split(` `).forEach((i,l)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:l+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(` `)}function BB(e){return e.split(` -`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:nt("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:nt("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:nt("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` +`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Tn(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=fn(),[l,u]=b.useState(""),{data:f}=tt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await wn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CUIsP4dU.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-Dl8vJRj-.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let ze=!0;return w({cancelRefetch:!0}).then(mt=>{ze&&mt.status==="success"&&!mt.isRefetchError&&g(l)}),()=>{ze=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const ze=setInterval(()=>V(mt=>mt+1),5e3);return()=>clearInterval(ze)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const ze=()=>{const mt=[];B.awareness.getStates().forEach(hn=>{const Et=hn.user?.name;Et&&mt.push(Et)}),K([...new Set(mt)]);const pt=cy(P.current),ht=new Set;for(const hn of B.remoteCursors()){const Et=H2(pt,hn.pos);Et&&ht.add(Et.name)}D(ht)};return ze(),B.awareness.on("change",ze),()=>B.awareness.off("change",ze)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=fn(),je=b.useRef(null),ve=async ze=>{try{const mt=await Rf(l),pt=je.current;if(mt.kind==="text"&&pt){const ht=pt.merge(mt.text,mt.sha,{held:ze});re(ht==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e,Ze=x?.kind==="text"&&x.text===""&&!!x.sha;b.useEffect(()=>{if(!Te)return;const ze=async()=>{const mt=je.current;if(!mt)return!0;let pt;const ht=new Promise(hn=>{pt=setTimeout(hn,Ze?5e3:1500)});try{await Promise.race([mt.saveNow(),ht])}catch{}finally{clearTimeout(pt)}return mt.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Te.current=ze,()=>{Te.current===ze&&(Te.current=null)}},[Te,we,t,n,l,Ze]);const ft=b.useRef(0),st=ze=>{ke("Someone else saved this file first. Your version is beside it as "+(ze.split("/").pop()??ze))};b.useEffect(()=>{const ze=mt=>{if(mt.detail?.includes(n)&&i){if(he.current>0){he.current--;return}ft.current>0||re(!0)}};return window.addEventListener("bdrive:changed",ze),()=>window.removeEventListener("bdrive:changed",ze)},[n,i]);const Un=M==="offline",Vn=Un&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Un?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Vn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(ze=>o.jsx(G2,{name:ze,title:ze+" is editing"},ze)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Vn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Un&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(ze=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+ze,"aria-selected":Z===ze,className:Z===ze?"on":"",onClick:()=>W(ze),children:[o.jsx(ge,{name:ze==="write"?"pencil":ze==="markdown"?"code":"eye"}),ze==="write"?"Write":ze==="markdown"?"Markdown":"Preview"]},ze))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:st,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:ze=>{ft.current=ze},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(ze=>ze.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:st,onExternal:ze=>{re(ze==="blocked"),ze==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:ze=>{ft.current=ze},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=tt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=tt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",zn(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=tt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=tt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` -`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=fn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=$n(e.perm,"admin"),x=$n(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await Tn(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Tn(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Tn(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return tt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=fn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await wn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await wn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` -`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(it.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(it.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(it.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(it.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(it.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(it.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(it.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(it.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:nt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:nt("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:nt("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:nt("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:nt("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=tt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=tt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>zn(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Fn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Fn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Fn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Fn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Fn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Fn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Fn(t(e.path)),children:l})]})}function Rq(e,t){return tt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=tt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Fn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=fn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const ft=V===null?-1:q.indexOf(V),st=Te.key==="j"?Math.min(q.length-1,ft+1):Math.max(0,ft===-1?0:ft-1);ee(q[st])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),ft=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const st=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ft?[ft,st]:st}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=tt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await Tn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=tt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=fn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=tt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),yt(zn(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const $e of _H(H))Ne.add($e);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const $e=new Set(Ne);return $e.has(ie)?$e.delete(ie):$e.add(ie),$e})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{yt(zn(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>yt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[ft,st]=b.useState(!1),[Un,Vn]=b.useState("");b.useEffect(()=>n3(ie=>{Vn(ie??""),st(!0)}),[]);const ze=b.useRef(null),mt=b.useRef(null),pt=b.useRef(null),ht=e.panel??null,hn=!ht&&i&&!!l&&(Z||U)&&$n(l.perm,"write"),Et=ie=>K2(_,ie)?.me,On=!ht&&Z&&!L&&(!i||!!l&&$n(Et(M)??l.perm,"write")),ut=!!r.editing&&On;b.useEffect(()=>{if(!On||!Z||ut)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[On,Z,ut]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let $e=0;$emr||[],[mr]),z=jn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!ht,[rt,Rt]=b.useState(null),Zt=b.useRef(null),zt=b.useRef(null),Le=b.useRef(!1);b.useEffect(()=>{Le.current=!1},[M]);const xt=b.useCallback(()=>{Le.current=!0,yt(zn(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),bt=b.useCallback(()=>{Le.current?(Le.current=!1,history.back()):yt(zn(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!ft&&bt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,ft,bt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?zt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:Cn}=mE(l?.id,i&&!!l),Nt=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),_n=Z?(Cn||[]).filter(ie=>ie.path===M):[],{data:pr}=tt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),nn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,En=b.useCallback(async()=>{if(!nn)return;const ie=nn+window.location.pathname,Ne=await Tn(ie);ke(Ne?"Web link copied":ie,!Ne)},[nn]),gr=!ht&&i&&!!l,Jn=!ht&&Z&&!r.view,Kr=!ht&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!ut,sn=!ht&&(Z||i&&!!l&&U),Nn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():mt.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await Tn(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&$n(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,$e)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+($e?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await wn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(ot){ke("Restore failed: "+ot.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),$t=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await wn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,$e=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const ot=await wn(n+"undo-run",{...$e,preview:!0}),Ft=new Set(ot.changed_after);if(!ot.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",ot.undone.length," file",ot.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:ot.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),Ft.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),Ft.size>0&&o.jsxs("div",{className:"undo-warn",children:[Ft.size," file",Ft.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Ft.size===1?"that change":"those changes"," too."]}),ot.skipped.length>0&&o.jsxs("div",{children:[ot.skipped.length," already hold",ot.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),ot.refused.length>0&&o.jsxs("div",{children:[ot.refused.length," path",ot.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",ot.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await wn(n+"undo-run",$e);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(ot){ke("Undo failed: "+ot.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Vn(""),st($e=>!$e))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=$e=>ie.push($e);if(i&&l){const $e=l.id,ot=Zs=>()=>{e.onClosePanel?.(),yt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:ot("/"+$e)});const Ft=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:ot(Ys)});Ft("activity","Activity",cn("history",$e)),Ft("insights","Insights",cn("dashboard",$e)),Ft("gear","Settings",cn("settings",$e)),Ft("laptop","Connect a device",cn("install",$e))}if(i&&l&&M){const $e=M.slice(M.lastIndexOf("/")+1),ot=(Ft,Zs,ps)=>Ne({icon:Ft,label:Zs,hint:$e,kind:"action",group:$e,run:ps});hn&&ot("share","Share",Ei),ot("hist","History",Ts),Z&&ot("download","Download",()=>ze.current?.click()),es&&ot("printer","Print",Do),_i&&ot("copy","Copy",zo)}if(i)for(const $e of e.projects||[])(!l||$e.id!==l.id)&&Ne({icon:"folder",label:$e.name,kind:"project",group:"Projects",run:()=>yt("/"+$e.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const $e of y.keys())Ne({icon:"folder",label:$e,kind:"folder",run:()=>I($e)});for(const $e of m)qr($e.path)||Ne({icon:"doc",label:$e.path,kind:"file",run:()=>I($e.path)});return ie},[i,l,M,Z,hn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),rn=i?l?.id:void 0;b.useEffect(()=>{if(!rn)return;const ie=()=>mU(rn);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[rn]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{rn&&La&&pU(rn)},[rn,La]);const $a=sy(rn),ts=b.useMemo(()=>hH(h,$a),[h,$a]),kn=vU(rn),Fo=AU(n,!!rn&&!!t.comments&&kn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),an=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&$n(l.perm,"write"),Io=b.useCallback(ie=>!!l&&$n(Et(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const $e=(ie?ie+"/":"")+Ne;if(Yr.has($e)||y.has($e)){ke($e+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent($e),""),await f.invalidateQueries({queryKey:["tree",n]}),yt(zn($e,l?.id,void 0,!1,!0)),ds()}catch(ot){ke("Could not create "+$e+": "+ot.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:rn?ie=>ry(rn).includes(ie):void 0,togglePin:rn?ie=>W1(rn,ie):void 0,copyPath:async ie=>{const Ne=await Tn(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&$n(l.perm,"write")?async ie=>{const Ne=(Cn||[]).find($e=>$e.path===ie);if(Ne){const $e=await Tn(Ne.url);ke($e?"Share link copied":Ne.url,!$e);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>yt(cn("dashboard",l.id,ie)):void 0,remove:ms?$t:void 0}),[Fa,Ia,Io,rn,i,l,Cn,I,re,ms,$t,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,qn;if(ht)qn=ht.body;else if(r.view==="dashboard")Ks="wide",qn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",qn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:$t,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>zn(ie,l?.id,Ne),onFilters:ie=>yt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)qn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)qn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)qn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);qn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:ut,editSource:Bs,me:Gr,commentable:Hn,flushRef:pt});return Hn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:jn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),qn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):qn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(qn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),qn]}));const jc=ht?ht.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!ut&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Hn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),On&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{ut||(jp(),gS(f,n,M))},onFocus:()=>{ut||(jp(),gS(f,n,M))},title:ut?"Stop editing":"Edit this file",onClick:async()=>{if(!ut){yt(zn(M,l?.id,L,r.full,!0));return}const ie=zn(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let $e=!0;try{$e=await(pt.current?.()??Promise.resolve(!0))}catch{}$e&&window.location.pathname+window.location.search===Ne&&yt(ie)},children:[!ut&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:ut?"Done":"Edit"})]}),ut&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),hn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:xt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Nn,ref:ze,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:mt,children:"Print"}),sn&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>ze.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),nn&&o.jsx("button",{className:"more-item",onClick:En,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),yt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:kn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[rn&&o.jsx(EH,{pins:kn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(rn,ie)}),rn&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(an==="recent"?" on":""),id:"tree-sort-btn","aria-label":an==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":an==="recent",title:an==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(an==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:an,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:zt,onClick:bt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!ht&&Z&&o.jsx(b7,{shares:_n,canRevoke:!!l&&$n(l.perm,"write"),onChanged:Nt}),qn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:Rt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:Cn||[],onChanged:Nt,onOpenFolder:ie=>yt(zn(ie,l.id)),onClose:()=>{ve(!1),Nt()}}),Hn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:jn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:$n(l?.perm,"admin")}),o.jsx(cq,{open:ft,onClose:()=>st(!1),candidates:zf,recent:xc,initialQuery:Un})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?yt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await wn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),yt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);yt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>yt("/"),beta:U==="BearDrive"}),Y=fn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Fn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):zn(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Fn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),yt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:zn(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),yt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),yt(cn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return wn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:zn(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DzIcnMyR.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CQ41m5Hk.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(it=>{Fe&&it.status==="success"&&!it.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(it=>it+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const it=[];B.awareness.getStates().forEach(ht=>{const sn=ht.user?.name;sn&&it.push(sn)}),K([...new Set(it)]);const nn=cy(P.current),yt=new Set;for(const ht of B.remoteCursors()){const sn=H2(nn,ht.pos);sn&&yt.add(sn.name)}D(yt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),je=b.useRef(null),ve=async Fe=>{try{const it=await Rf(l),nn=je.current;if(it.kind==="text"&&nn){const yt=nn.merge(it.text,it.sha,{held:Fe});re(yt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const it=je.current;if(!it)return!0;const nn=it.mayServerRefuseShrink(),yt=it.saveNow();let ht;try{nn?await yt:await Promise.race([yt,new Promise(sn=>{ht=setTimeout(sn,1500)})])}catch{}finally{clearTimeout(ht)}return it.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),mt=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=it=>{if(it.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:mt,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:mt,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?dn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` +`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=dn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(dn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(dn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` +`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const mt=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,mt+1):Math.max(0,mt===-1?0:mt-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),mt=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return mt?[mt,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),vt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{vt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>vt(dn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[mt,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const it=b.useRef(null),nn=b.useRef(null),yt=b.useRef(null),ht=e.panel??null,sn=!ht&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!ht&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!ht,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const xt=b.useCallback(()=>{ze.current=!0,vt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),bt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):vt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!mt&&bt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,mt,bt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),Et=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),rn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!rn)return;const ie=rn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[rn]),gr=!ht&&i&&!!l,Jn=!ht&&Z&&!r.view,Kr=!ht&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,an=!ht&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():nn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(lt){ke("Restore failed: "+lt.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const lt=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(lt.changed_after);if(!lt.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",lt.undone.length," file",lt.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:lt.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),lt.skipped.length>0&&o.jsxs("div",{children:[lt.skipped.length," already hold",lt.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),lt.refused.length>0&&o.jsxs("div",{children:[lt.refused.length," path",lt.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",lt.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(lt){ke("Undo failed: "+lt.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,lt=Zs=>()=>{e.onClosePanel?.(),vt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:lt("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:lt(Ys)});$t("activity","Activity",dn("history",Le)),$t("insights","Insights",dn("dashboard",Le)),$t("gear","Settings",dn("settings",Le)),$t("laptop","Connect a device",dn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),lt=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});sn&<("share","Share",Ei),lt("hist","History",Ts),Z&<("download","Download",()=>it.current?.click()),es&<("printer","Print",Do),_i&<("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>vt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,sn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),on=i?l?.id:void 0;b.useEffect(()=>{if(!on)return;const ie=()=>mU(on);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[on]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{on&&La&&pU(on)},[on,La]);const $a=sy(on),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(on),Fo=AU(n,!!on&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),ln=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),vt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(lt){ke("Could not create "+Le+": "+lt.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:on?ie=>ry(on).includes(ie):void 0,togglePin:on?ie=>W1(on,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>vt(dn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,on,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(ht)Hn=ht.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?dn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>vt(dn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:yt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=ht?ht.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){vt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await(yt.current?.()??Promise.resolve(!0))}catch{}Le&&window.location.pathname+window.location.search===Ne&&vt(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),sn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:xt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:it,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:nn,children:"Print"}),an&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>it.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),rn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),vt(dn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[on&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(on,ie)}),on&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(ln==="recent"?" on":""),id:"tree-sort-btn","aria-label":ln==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":ln==="recent",title:ln==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(ln==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:ln,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:bt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!ht&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:Et}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:Et,onOpenFolder:ie=>vt(Ln(ie,l.id)),onClose:()=>{ve(!1),Et()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:mt,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?vt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),vt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);vt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>vt("/"),beta:U==="BearDrive"}),Y=mn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?dn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),vt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:dn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:dn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),vt(I==="home"?"/"+M.id:dn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),vt(dn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-CSb7vEsh.js b/internal/webapp/static/assets/sharedfile-UW7NkjEZ.js similarity index 77% rename from internal/webapp/static/assets/sharedfile-CSb7vEsh.js rename to internal/webapp/static/assets/sharedfile-UW7NkjEZ.js index 111fbb4f..5c88924c 100644 --- a/internal/webapp/static/assets/sharedfile-CSb7vEsh.js +++ b/internal/webapp/static/assets/sharedfile-UW7NkjEZ.js @@ -1,17 +1,17 @@ -import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-YIhaBYDQ.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const yt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&yt(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=yt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=yt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=yt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),kl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Et=e=>new Error(e),mt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},ui=Et("Unexpected end of array"),fi=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=yt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ki=typeof window<"u"&&typeof document<"u"&&!Gt;let St;const Yl=()=>{if(St===void 0)if(Gt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Mr(t,"-")}`,n),St.set(`-${Mr(t,"-")}`,n)}})):St=rt();return St},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),Si=e=>Ls("--"+e)||Rn(e)!==null,ql=Si("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!Si("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=ki?Ql:Zl,sc=ki?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,ks=(e,t,n)=>yt(e.next()*(n+1-t)+t),_i=(e,t,n)=>yt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` -`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){mt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),kc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const Se=G(e=>typeof e=="number"),Mi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}. -${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>ks(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(ks(t,Ur,On))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,Ni,nr,Kn,Oi(Se),Ii(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;r$i(tn(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=yt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==gt){const p=At(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof Tt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=yt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==dt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Ct(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Ct(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Ct(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&en(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===gt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===gt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==gt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===gt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw mt()}clone(){throw mt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Et("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},ko=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},So=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=` -`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==dt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof dt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return So(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):So(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw mt()}mergeWith(t){return!1}write(t,n,s){throw mt()}integrate(t,n){throw mt()}}const sh=0;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===dt||this.right&&this.right.constructor===dt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===dt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new dt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},yt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. -${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ce),H(S,ze(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&S[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` +import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-CiZlXtW0.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){It(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const St=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&St(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=St(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=St(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=St(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),Sl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):Sl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class kl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},at=()=>{throw Ct("Unexpected case")},ui=Ct("Unexpected end of array"),fi=Ct("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=St(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,Se=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Gt;let bt;const Yl=()=>{if(bt===void 0)if(Gt){bt=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${Mr(t,"-")}`,n),bt.set(`-${Mr(t,"-")}`,n)}})):bt=rt();return bt},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),ki=e=>Ls("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!ki("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=Si?Ql:Zl,sc=Si?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,Ss=(e,t,n)=>St(e.next()*(n+1-t)+t),_i=(e,t,n)=>St(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&Se(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),Sc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const kc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=kc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const ke=G(e=>typeof e=="number"),Mi=G(e=>e===ke),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(ke,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(ke,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. +${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>Ss(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(Ss(t,Ur,On))).if(Un,(e,t)=>ge(t,ks(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rks(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,ks(t,[ke,Ie,Qn,Ni,nr,Kn,Oi(ke),Ii(Me("a","b","c"),ke)]))).if(Sc,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;r$i(tn(t),e),Tt=typeof document<"u"?document:{},Nc=e=>Tt.createElement(e),$c=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),iu=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const ou=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=Tt.ELEMENT_NODE,Jc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const Wc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Yc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=St((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==pt){const p=It(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const lu=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},Sa=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ka{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new ka(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},cu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},au=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=It(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=St(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==gt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class hu extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const k=c.beforeState.get(w)||0,A=b-k;A>0&&en(f,w,k,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===pt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===pt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==pt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===pt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Ct("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=` +`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==gt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof gt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case At:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case xt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case Y:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Ct("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(Sh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(kh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw yt()}mergeWith(t){return!1}write(t,n,s){throw yt()}integrate(t,n){throw yt()}}const sh=0;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class Y{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Y(this.key,this.value)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new Y(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new At(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,Sh=5,kh=6;class xt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new xt(this.type._copy())}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new xt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===gt||this.right&&this.right.constructor===gt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===gt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new gt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class pt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>It(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},St(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),Se(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}. +${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),k=Q();_(k,Ce),H(k,ze(i,w)),Ds(this,B(k))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(Sa(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&k[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const k=h[w-1],A=f-d,O=A===-w||A!==w&&k[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const k=u[w],A=u[w+1];(k>y||A>b)&&p.push({aS:n+y,aE:n+k,bS:n+b,bE:n+A}),y=k+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(` `)||i[o.length]===` -`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),h=_t(o,i),a=[...Ue(h,_t(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,_t(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",R=S;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),R=f(b,1,w,S);if(O===R){d+=O;continue}if(w===S){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,S),O,R,As):Jn(u(o,w,S),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(` +`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=_t(e,s),l=_t(t,s),c=_t(n,s),h=Et(o,i),a=[...Ue(h,Et(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,Et(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,k)=>b.slice(w,k).join(""),f=(b,w,k,A)=>{let O="",R=k;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,k);continue}const O=f(b,0,w,k),R=f(b,1,w,k);if(O===R){d+=O;continue}if(w===k){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,k),O,R,As):Jn(u(o,w,k),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(` `)?e:e+` `;function Vo(e,t,n,s){let r=t.endsWith(` `);return r===e.endsWith(` `)&&(r=n.endsWith(` `)),s===""||r===s.endsWith(` `)?s:r?s+` -`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` -`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,Yt),i=bt(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,Yt),s),i=Ue(_t(bt(e,Yt),s),r),o=Ue(r,_t(bt(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",R=0;const N=(g=Date.now())=>{const k=Math.max(g,R+1e3);return R=k,Go(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,xt=!1,ht=null,Fe=0,rs=!1,tt=null,Ot=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let kt=!1,Be=null,Qt=0;const Ve=()=>{kt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,pt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},kr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const k=L();if(k===g)return!0;const m=oi(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=L();if(k===n&&!Ot){$("clean");return}if($("saving"),e.onWriting?.(),xt){if(S!==null&&A===k){if(await yn(k,O)==="stop")return;continue}xt=!1}const m=c||h?await Ho(k):await Jo(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!Ot?"clean":"dirty");return}}};let wt=!1;const Ho=async g=>{Lt=g,je=!1;let k;try{k=await bn(gn(e.path),g,s,wt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(wt=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,wt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){Ot=!0;const m=t(k.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...wt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return wt=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,wt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,Ot=!1,a)return"stop";const I=t(g,k.text,L());return I.ok&&Rt(I.text)&&(je||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ee=g=>{Y||f||!e.onShrinkRefused||($("error"),Y={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!kt&&pt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&pt{if(!f)try{const k=await xr(Or(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;$(pt>=it&&!kt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let ft=null;const Wo=()=>{ft&&clearTimeout(ft),ft=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},Sr=async(g,k,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=N(),A=g);const m=S;O=k,xt=!0;const I=await Sr(g,k,m);return f?"stop":I?(wn(I.err),"stop"):(xt=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(f||u)&&(d=it-pt,e.onPending?.(d))},Yo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const k=(async()=>{try{for(;!u&&!f&&!Y&&pt{y=!1,S=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,Ot=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||Ot)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(oi(k,m.text)));y=!0,(S===null||A!==g)&&(S=N(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if($("dirty"),a){kt=!0,Be=m,Qt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=L();if(g===I)return r(g,k),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,k),kt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,k),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let kn=null;const zo=()=>{if(!f){if(Y)return Promise.resolve();if((a?u?kt:d>0:L()!==n)&&!wt&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(ft??void 0),ft=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!kt)return Promise.resolve();if(kn)return kn;const g=Qt;$("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(kt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(ft??void 0),ft=null,ee(L()),Y))return;$(kt?"dirty":"clean")}finally{kn=null}})();return kn=k,k};let Ut=null;const Sn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&kt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),Sn(V));return}if(y||xt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!Ot)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){Sn(m)(),f||(clearTimeout(ft??void 0),ft=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return Sn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;xt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),S=Mt,A=g,br(Mt,g,m,lt=>{xt=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(wt=!1,tt===j&&(tt=null),Ot=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,wt,!0,!0).then(T=>{if(wt=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(ft??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,au as U,lu as a,ka as b,Ea as c,oi as d,cu as e,Ps as f,ae as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t}; +`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function uu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` +`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,Yt),i=_t(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=k>0?p.charCodeAt(p.length-k):0;O>=56320&&O<=57343&&k--,b+=w,p=p.slice(w,p.length-k),y=y.slice(w,y.length-k),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=Et(_t(t,Yt),s),i=Ue(Et(_t(e,Yt),s),r),o=Ue(r,Et(_t(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(` +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",nu=32e3,su=32;function fu(e){const t=(g,S,m)=>Xh(e.path,g,S,m);let n=e.seed,s=e.baseSha;const r=(g,S)=>{n=g,i=S,ot(S);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const S=[];for(let m=g;m!==null&&S.length<4;m=m.prev)m.sent!==m.from&&!S.includes(m.sent)&&S.push(m.sent);return S.length?S:void 0},l=(g,S=tt)=>{const m=o(S);return i&&i===s&&n.length>nu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,k=null,A=null,O="",R=0;const N=(g=Date.now())=>{const S=Math.max(g,R+1e3);return R=S,Go(e.path,e.who||"browser",new Date(S))},F=new Map;let Kt=0,Ot=!1,ht=null,Fe=0,rs=!1,tt=null,kt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>su&&Bt.shift())};let wt=!1,Be=null,Qt=0;const Ve=()=>{wt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,mt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},Sr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const S=L();if(S===g)return!0;const m=oi(S,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,W||a||w)return;const S=L();if(S===n&&!kt){$("clean");return}if($("saving"),e.onWriting?.(),Ot){if(k!==null&&A===S){if(await yn(S,O)==="stop")return;continue}Ot=!1}const m=c||h?await Ho(S):await Jo(S);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!kt?"clean":"dirty");return}}};let ft=!1;const Ho=async g=>{Lt=g,je=!1;let S;try{S=await bn(gn(e.path),g,s,ft)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(ft=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,ft=!1,Sr(),S.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,S.sha),e.onSaved?.(g),"done")},cs=async(g,S)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(S&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),S&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let S=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){S=m;break}if(tt=null,S){kt=!0;const m=t(S.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=S.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let S;const m=tt;try{tt={sent:g,from:n,prev:m},S=await Ht(jt,{...l(g,m),...ft?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return ft=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,ft=!1,Sr(),S.update&&x.applyRemoteUpdate(S.update),tt=null,kt=!1,a)return"stop";const I=t(g,S.text,L());return I.ok&&Rt(I.text)&&(je||r(S.text,S.sha)),e.onSaved?.(S.text),"done"};let W=null;const ee=g=>{W||f||!e.onShrinkRefused||($("error"),W={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const S=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(S,m);const C=!wt&&mt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&mt{if(!f)try{const S=await xr(Or(e.apiBase,e.path));if(f||S.kind!=="text")return;if(r(S.text,S.sha),Rt(S.text),W=null,a&&!u){if(await fe(!1),f)return;$(mt>=it&&!wt?"clean":"dirty");return}mt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{W=null}}},e.onShrinkRefused(W))};let dt=null;const Wo=()=>{dt&&clearTimeout(dt),dt=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},kr=async(g,S,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,S&&(s=S),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),S,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(k===null||A!==g)&&(k=N(),A=g);const m=k;O=S,Ot=!0;const I=await kr(g,S,m);return f?"stop":I?(wn(I.err),"stop"):(Ot=!1,A===g&&(k=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,S)=>{mt=Math.max(mt,g),is(S),!(f||u)&&(d=it-mt,e.onPending?.(d))},Yo=()=>{f||u||W||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(mt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const S=(async()=>{try{for(;!u&&!f&&!W&&mt{y=!1,k=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,kt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||kt)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const S=x.text.toString(),m=t(n,S,g);if(m.ok)return hs(()=>x.applySplices(oi(S,m.text)));y=!0,(k===null||A!==g)&&(k=N(),A=g),b=!0;let I;try{I=await kr(g,s??"",k)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(k=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),mt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,S)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(S?.origin)){if($("dirty"),a){wt=!0,Be=m,Qt+=1,u||(it+=1,d=it-mt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,S,m)=>{if(m?.held)return r(g,S),"same";if(g===n||g===Lt)return ot(S),"same";const I=L();if(g===I)return r(g,S),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,S),wt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,S),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,S),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let Sn=null;const zo=()=>{if(!f){if(W)return Promise.resolve();if((a?u?wt:d>0:L()!==n)&&!ft&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(dt??void 0),dt=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!wt)return Promise.resolve();if(Sn)return Sn;const g=Qt;$("saving");const S=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(wt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(dt??void 0),dt=null,ee(L()),W))return;$(wt?"dirty":"clean")}finally{Sn=null}})();return Sn=S,S};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,S)=>{if(W)return;if(a){const T=!u&&d>0;if(!T&&!(u&&wt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(y||Ot){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=k!==null&&A===g?k:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!kt)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!S){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){kn(m)(),f||(clearTimeout(dt??void 0),dt=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return kn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;Ot=!0;let Mt=k!==null&&A===g?k:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),k=Mt,A=g,br(Mt,g,m,lt=>{Ot=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(ft=!1,tt===j&&(tt=null),kt=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,ft,!0,!0).then(T=>{if(ft=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>W!==null,mayServerRefuseShrink:()=>W||f||ft||!e.onShrinkRefused||!s||s===eu?!1:a?n===""&&(wt||d>0):n===""&&(L()!==""||kt)||(c||h)&&L()!==n,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(dt??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,W?e.onShrinkWithdrawn?.(W):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,hu as U,cu as a,Sa as b,Ea as c,oi as d,au as e,Ps as f,ae as g,iu as h,vt as i,uu as m,fu as o,lu as r,ou as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index e5bf76cb..40ad82b2 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + From 9fe7bba7a300fd2515df25d2ba37154268c78025 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Wed, 11 Nov 2026 22:51:51 +0900 Subject: [PATCH 09/34] fix(webapp): await saveNow settlement on Done without fixed timeout --- CHANGELOG.md | 2 +- architecture/webapp-frontend.md | 4 +- internal/webapp/frontend/src/apps/Browser.tsx | 35 +++++--- .../frontend/src/components/FileView.tsx | 25 ++---- .../webapp/frontend/src/lib/sharedfile.ts | 16 ---- .../src/lib/sharedfile_restore.test.ts | 87 +++++++------------ ...{Editor-DzIcnMyR.js => Editor-DYK0viPg.js} | 2 +- ...dit-CQ41m5Hk.js => VisualEdit-x7yoZJb9.js} | 2 +- .../{index-CiZlXtW0.js => index-CCNmuVia.js} | 54 ++++++------ ...ile-UW7NkjEZ.js => sharedfile-Bq16w-Wl.js} | 20 ++--- internal/webapp/static/index.html | 2 +- 11 files changed, 99 insertions(+), 150 deletions(-) rename internal/webapp/static/assets/{Editor-DzIcnMyR.js => Editor-DYK0viPg.js} (99%) rename internal/webapp/static/assets/{VisualEdit-CQ41m5Hk.js => VisualEdit-x7yoZJb9.js} (97%) rename internal/webapp/static/assets/{index-CiZlXtW0.js => index-CCNmuVia.js} (65%) rename internal/webapp/static/assets/{sharedfile-UW7NkjEZ.js => sharedfile-Bq16w-Wl.js} (77%) diff --git a/CHANGELOG.md b/CHANGELOG.md index e64259ba..611c4706 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **`POST /api/p//ycollab/sync` merges browser edits into a room over HTTP.** A browser without a connected socket sends its Yjs state, or its text with the base it started from; `peek` reads the room without writing. The hub answers `ok` only after storage holds the edit, waiting up to 8 seconds (`ycollabSyncDurableWait`), including for the lease holder in another process; otherwise it returns `503` and the browser keeps its edits. - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict. - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. -- **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves before leaving (waiting up to 1.5 seconds, and staying only for an open shrink question). `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. +- **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done waits for the save to settle before leaving, staying on the editor if a shrink confirmation opens. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. ## v0.18.9 — 2026-11-11 diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index 96b0d1f6..481fd1c7 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -59,7 +59,7 @@ classDiagram +scroll restoration: contentRef, memo, goal from lib/scroll +fullscreen: body.full-view from route.full, Exit / Esc / Back +readWidth: dragged reading width, tab memory only - +Done: awaits editFlushRef (saveNow, 1.5s cap) before leaving the editor + +Done: awaits editFlushRef (saveNow) until it settles, then leaves the editor } note for Browser "readWidth is the reading column's width as the reader drags it (components/WidthHandle.tsx), held in Browser's state and nowhere else: it follows the reader across files and in and out of fullscreen because Browser outlives both, and a reload or a new tab is the reset — no storage, by design. It reaches the DOM as ONE variable, --page-read on the .page element, so the file rail's placement arithmetic follows without its own rule. During a drag the handle writes that variable straight onto the element and commits to state only on release, so the file page is not re-rendered on every pointer move" note for Browser "Fullscreen is a QUERY PARAM on the file route (?full=1), for the reason ?v= is one: the first segment after the project id is reserved for view names, and a fullscreen file is the same page with different chrome. Two things the code forced: routeKey is withoutFull(useLocationPath()), because a ?full=1 push otherwise looks like a fresh route and arms a scroll goal of 0 — the reader is thrown to the top of the document the moment they ask for more of it; and the chrome is HIDDEN by a body class, never unmounted, so <article id=content> survives the toggle and keeps its scrollTop in both directions. display:none also takes the hidden controls out of the tab order and the accessibility tree together, which is what syncSidebarInert already encodes for the off-canvas sidebar. The Exit control is rendered by AppShell OUTSIDE the topbar it hides and painted over the content: the HTML sandbox is an opaque origin and the PDF viewer is the browser's own, so Esc can never reach the app from inside either one (BEA-195)" @@ -232,7 +232,7 @@ classDiagram Browser --> components components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand) note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
-    note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow + askingShrink, and Done waits for it (at most 1.5s, never a veto) before leaving; an open shrink question keeps the user in the editor"
+    note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow + askingShrink, and Done awaits it until the save settles before leaving; an open shrink question keeps the user in the editor"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx
index bf9f17a4..8b2e70e0 100644
--- a/internal/webapp/frontend/src/apps/Browser.tsx
+++ b/internal/webapp/frontend/src/apps/Browser.tsx
@@ -252,6 +252,9 @@ export default function Browser(props: {
   // it (briefly) so leaving never strands the last words in a pending save.
   // It answers false when the save is waiting on the user (ShrinkDialog).
   const editFlushRef = useRef<(() => Promise) | null>(null);
+  // A Done already saving: a second click waits on the first, never leaves
+  // past it (that would skip the shrink question its answer may open).
+  const leavingFlushRef = useRef<(() => Promise) | null>(null);
 
   const panel = props.panel ?? null;
   // Sharing is a write — a read-only member sees no Share button rather than
@@ -1157,21 +1160,27 @@ export default function Browser(props: {
                   navigate(urlForPath(path, project?.id, version, route.full, true));
                   return;
                 }
-                // Save and leave: FileView's flush bounds its own wait, so a
-                // hub that does not answer never traps the user in the editor.
-                // Only a question the user must answer keeps them here.
-                const target = urlForPath(path, project?.id, version, route.full, false);
-                const here = window.location.pathname + window.location.search;
-                let okToLeave = true;
+                // Save and leave, once the save has settled: an answer that
+                // opens a question (ShrinkDialog) keeps the user here.
+                const flush = editFlushRef.current;
+                if (flush && leavingFlushRef.current === flush) return;
+                leavingFlushRef.current = flush;
                 try {
-                  okToLeave = await (editFlushRef.current?.() ?? Promise.resolve(true));
-                } catch {
-                  // The editor's own teardown still sends what it holds.
+                  const target = urlForPath(path, project?.id, version, route.full, false);
+                  const here = window.location.pathname + window.location.search;
+                  let okToLeave = true;
+                  try {
+                    okToLeave = await (flush?.() ?? Promise.resolve(true));
+                  } catch {
+                    // The editor's own teardown still sends what it holds.
+                  }
+                  if (!okToLeave) return; // the shrink dialog is open: answer it here
+                  // Somewhere else already (a click elsewhere while saving): stay there.
+                  if (window.location.pathname + window.location.search !== here) return;
+                  navigate(target);
+                } finally {
+                  if (leavingFlushRef.current === flush) leavingFlushRef.current = null;
                 }
-                if (!okToLeave) return; // the shrink dialog is open: answer it here
-                // Somewhere else already (a click elsewhere while saving): stay there.
-                if (window.location.pathname + window.location.search !== here) return;
-                navigate(target);
               }}
             >
               {!editing && } {editing ? "Done" : "Edit"}
diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx
index 89d08b51..0d260ce8 100644
--- a/internal/webapp/frontend/src/components/FileView.tsx
+++ b/internal/webapp/frontend/src/components/FileView.tsx
@@ -513,32 +513,17 @@ function EditView(props: Parameters[0]) {
   const { flushRef } = props;
   useEffect(() => {
     if (!flushRef) return;
-    /* Save and leave: the save gets a moment, never a veto — a hub that does
-       not answer must not trap the user in the editor. A question the user
-       must answer does keep them here, however it opened. The one exception
-       to the moment: a save only the hub can refuse as a shrink is waited out
-       in full, since leaving before its answer would close the editor under
-       the question it opens. */
+    /* Save and leave, once the save has settled — however long the hub
+       takes, since its answer may be a question (a shrink only it can see)
+       the user must answer here. Clean or a bystander settles at once, and a
+       failed request fails fast. */
     const flush = async () => {
       const f = fileHandle.current;
       if (!f) return true;
-      const mustSettle = f.mayServerRefuseShrink();
-      const saving = f.saveNow();
-      // Promise constructor, not withResolvers: the app targets ES2022.
-      let timer: ReturnType | undefined;
       try {
-        if (mustSettle) await saving;
-        else
-          await Promise.race([
-            saving,
-            new Promise((r) => {
-              timer = setTimeout(r, 1_500);
-            }),
-          ]);
+        await f.saveNow();
       } catch {
         // The editor's own teardown still sends what it holds.
-      } finally {
-        clearTimeout(timer);
       }
       if (f.askingShrink()) return false;
       void qc.invalidateQueries({ queryKey: ["render", apiBase, path] });
diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts
index 0970763d..fb28928e 100644
--- a/internal/webapp/frontend/src/lib/sharedfile.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile.ts
@@ -72,10 +72,6 @@ const MAX_REBASES = 4;
 const MAX_CONFLICT_TRIES = 64;
 const MAX_EXIT_COPY_TRIES = 8;
 
-// The sha of no bytes: a base naming it is a known-empty file, which nothing
-// can shrink.
-const EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
-
 // Above this, a staging checkpoint names its ancestor by sha alone when it can
 // (the hub reads the blob) instead of carrying it as text.
 const INLINE_BASE_MAX = 32_000;
@@ -95,12 +91,6 @@ export type SharedFile = {
   /** A shrink question is waiting on the user: leaving now would leave it
       unanswered (Done stays on the editor). */
   askingShrink(): boolean;
-  /** A save now could still be refused by the hub as a sharp shrink that
-      nothing here can see: `saved` is empty while the base names a non-empty
-      version, or a solo write lands on a file a peer may have grown. Done
-      then waits for the save's outcome, however long, rather than leave on a
-      timer before the question could open. */
-  mayServerRefuseShrink(): boolean;
   /** Fold an outside write — an agent, a CLI, another device — into the open
       document. "blocked" means the caller should SAY so instead, because this
       refused to resolve it. `held` says the hub has already put this text
@@ -1510,12 +1500,6 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile {
     rebase,
     saveNow,
     askingShrink: () => asking !== null,
-    mayServerRefuseShrink: () => {
-      if (asking || gone || confirmShrinkOnce || !opts.onShrinkRefused) return false;
-      if (!base || base === EMPTY_SHA256) return false;
-      if (hubHoldsIt) return saved === "" && (localDirtyInRoom || pending > 0);
-      return (saved === "" && (current() !== "" || roomNeedsFlush)) || ((solo || noRoomHttp) && current() !== saved);
-    },
     destroy() {
       if (typeof window !== "undefined") {
         window.removeEventListener("pagehide", onPageHide);
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index d0b8843a..716b5221 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -2242,9 +2242,8 @@ for (const mode of ["live", "offline", "staging", "solo"] as const) {
 
 /* A shrink only the hub can see: the read seeded an empty buffer (`saved`
    is "", so nothing local is a shrink) and the hub refuses the save 422,
-   ten seconds later. The file says so (mayServerRefuseShrink), so Done waits
-   the save out instead of leaving on a timer; the question opens when the
-   answer comes, and Done finds it open and stays. */
+   ten seconds later. Done waits the save out — there is no timer to leave
+   on — so the question opens when the answer comes, and Done stays. */
 test("a shrink the hub refuses 422 after a slow answer still asks before Done leaves", async () => {
   fakeTimers();
   try {
@@ -2279,7 +2278,6 @@ test("a shrink the hub refuses 422 after a slow answer still asks before Done le
     await waitFor(() => assert.equal(solo, true));
 
     buffer = "x\n";
-    assert.equal(file.mayServerRefuseShrink(), true);
     let settled = false;
     void file.saveNow().then(() => {
       settled = true;
@@ -2292,71 +2290,44 @@ test("a shrink the hub refuses 422 after a slow answer still asks before Done le
     assert.equal(settled, true);
     assert.equal(file.askingShrink(), true);
     assert.equal(asks.length, 1);
-    assert.equal(file.mayServerRefuseShrink(), false); // the question is open
     file.destroy();
   } finally {
     realTimers();
   }
 });
 
-/* When a save could meet a shrink refusal nothing here can see — and when
-   it cannot, so Done keeps its short wait. */
-test("mayServerRefuseShrink is true only where the hub alone can see a shrink", async () => {
+/* A live room over a non-empty `saved`: nothing local is a shrink, but a
+   peer grew the file and the hub snapshotted it before this tab heard. The
+   hub refuses the room's state 422, ten seconds later; saveNow waits for that
+   answer and leaves the question open, so Done stays on the editor. */
+test("a live save the hub refuses 422 for a shrink only it can see asks, however late", async () => {
   fakeTimers();
-  const solos: SharedFile[] = [];
+  const h = await heldRoom();
   try {
-    globalThis.fetch = (async () => new Response("{}", { status: 200 })) as typeof fetch;
-    const openSolo = async (seed: string, baseSha: string | undefined, buffer: string) => {
-      let solo = false;
-      const file = openSharedFile({
-        apiBase: "/api/",
-        path: "notes.md",
-        seed,
-        baseSha,
-        me: { name: "t", colour: "oklch(0.7 0.1 200)" },
-        onReady: () => {},
-        onSolo: () => {
-          solo = true;
-        },
-        onShrinkRefused: () => {},
-        soloText: () => buffer,
-        soloApply: () => {},
-      });
-      solos.push(file);
-      await waitFor(() => assert.equal(solo, true));
-      return file;
-    };
-    // Empty `saved`, a version that is not the empty file: only the hub knows.
-    assert.equal((await openSolo("", "sha-big", "x\n")).mayServerRefuseShrink(), true);
-    // Solo over a file a peer may have grown since it was read.
-    assert.equal((await openSolo("a\nb\nc\n", "sha-a", "a\nb\n")).mayServerRefuseShrink(), true);
-    // No version to be conditional on, or the version of no bytes.
-    assert.equal((await openSolo("", undefined, "x\n")).mayServerRefuseShrink(), false);
-    const empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
-    assert.equal((await openSolo("", empty, "x\n")).mayServerRefuseShrink(), false);
-    // Nothing to save.
-    assert.equal((await openSolo("a\nb\nc\n", "sha-a", "a\nb\nc\n")).mayServerRefuseShrink(), false);
+    await h.goLive();
+    h.localEdit((t) => t.insert(t.length, "d\n")); // grows `saved`: no local shrink
+    h.net.status = 422;
+    h.net.error = JSON.stringify({ error: "would cut most of the file", shrink: true });
+    const late = Promise.withResolvers();
+    setTimeout(late.resolve, 10_000); // fake clock: advance() moves it
+    h.net.hold = late.promise;
+
+    let settled = false;
+    void h.file.saveNow().then(() => {
+      settled = true;
+    });
+    await advance(9_999);
+    assert.equal(h.reqs.length, 1);
+    assert.equal(settled, false);
+    assert.equal(h.file.askingShrink(), false);
+    await advance(1);
+    assert.equal(settled, true);
+    assert.equal(h.file.askingShrink(), true);
+    assert.equal(h.asks.length, 1);
   } finally {
-    for (const f of solos) f.destroy();
-    await settle(); // their unmount saves land on this test's fetch
+    h.done();
     realTimers();
   }
-
-  // A room, live or staging, over a non-empty `saved`: every shrink is local.
-  for (const mode of ["live", "staging"] as const) {
-    fakeTimers();
-    const h = await heldRoom();
-    try {
-      if (mode === "live") {
-        await h.goLive();
-        h.localEdit((t) => t.insert(t.length, "d\n"));
-      } else h.state.buffer = "a\nb\nc\nd\n";
-      assert.equal(h.file.mayServerRefuseShrink(), false);
-    } finally {
-      h.done();
-      realTimers();
-    }
-  }
 });
 
 /* Keep, with the socket down, after Done asked about a sharp shrink: the
diff --git a/internal/webapp/static/assets/Editor-DzIcnMyR.js b/internal/webapp/static/assets/Editor-DYK0viPg.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-DzIcnMyR.js
rename to internal/webapp/static/assets/Editor-DYK0viPg.js
index b8b1a50c..3234f450 100644
--- a/internal/webapp/static/assets/Editor-DzIcnMyR.js
+++ b/internal/webapp/static/assets/Editor-DYK0viPg.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-CiZlXtW0.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-UW7NkjEZ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-CCNmuVia.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-Bq16w-Wl.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js b/internal/webapp/static/assets/VisualEdit-x7yoZJb9.js
similarity index 97%
rename from internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js
rename to internal/webapp/static/assets/VisualEdit-x7yoZJb9.js
index 635a1eff..65f88dea 100644
--- a/internal/webapp/static/assets/VisualEdit-CQ41m5Hk.js
+++ b/internal/webapp/static/assets/VisualEdit-x7yoZJb9.js
@@ -1 +1 @@
-import{r as i,j as y,w as ge,a as me}from"./index-CiZlXtW0.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-UW7NkjEZ.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit};
+import{r as i,j as y,w as ge,a as me}from"./index-CCNmuVia.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-Bq16w-Wl.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit};
diff --git a/internal/webapp/static/assets/index-CiZlXtW0.js b/internal/webapp/static/assets/index-CCNmuVia.js
similarity index 65%
rename from internal/webapp/static/assets/index-CiZlXtW0.js
rename to internal/webapp/static/assets/index-CCNmuVia.js
index 08bcf5a6..f5e699fb 100644
--- a/internal/webapp/static/assets/index-CiZlXtW0.js
+++ b/internal/webapp/static/assets/index-CCNmuVia.js
@@ -1,18 +1,18 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DzIcnMyR.js","assets/sharedfile-UW7NkjEZ.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CQ41m5Hk.js"])))=>i.map(i=>d[i]);
-import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var $m={exports:{}},Nl={};var Xb;function BR(){if(Xb)return Nl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Nl.Fragment=t,Nl.jsx=n,Nl.jsxs=n,Nl}var Wb;function GR(){return Wb||(Wb=1,$m.exports=BR()),$m.exports}var o=GR(),Fm={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Y(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Y(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(W(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var je=0;je>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Y());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Y():M=!1}}}var Y;if(typeof R=="function")Y=function(){R(W)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=W,Y=function(){le.postMessage(null)}}else Y=function(){_(W,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Y()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Um)),Um}var nw;function YR(){return nw||(nw=1,Pm.exports=ZR()),Pm.exports}var Vm={exports:{}},Mn={};var sw;function QR(){if(sw)return Mn;sw=1;var e=Lg();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vm.exports=QR(),Vm.exports}var aw;function XR(){if(aw)return kl;aw=1;var e=YR(),t=Lg(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function je(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Te(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),jl._currentValue=V)}var Ze,mt;function Je(s){if(Ze===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ze=a&&a[1]||"",mt=-1i.map(i=>d[i]);
+import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1p||F[d]!==ne[p]){var ce=`
-`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{Wn=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Je(c):""}function it(s,a){switch(s.tag){case 26:case 27:case 5:return Je(s.type);case 16:return Je("Lazy");case 13:return s.child!==a&&a!==null?Je("Suspense Fallback"):Je("Suspense");case 19:return Je("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return Je("Activity");default:return""}}function nn(s){try{var a="",c=null;do a+=it(s,c),c=s,s=s.return;while(s);return a}catch(d){return`
+`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{es=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?tt(c):""}function ot(s,a){switch(s.tag){case 26:case 27:case 5:return tt(s.type);case 16:return tt("Lazy");case 13:return s.child!==a&&a!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return tt("Activity");default:return""}}function mn(s){try{var a="",c=null;do a+=ot(s,c),c=s,s=s.return;while(s);return a}catch(d){return`
 Error generating stack: `+d.message+`
-`+d.stack}}var yt=Object.prototype.hasOwnProperty,ht=e.unstable_scheduleCallback,sn=e.unstable_cancelCallback,Ut=e.unstable_shouldYield,An=e.unstable_requestPaint,dt=e.unstable_now,Bs=e.unstable_getCurrentPriorityLevel,hs=e.unstable_ImmediatePriority,Gr=e.unstable_UserBlockingPriority,Vn=e.unstable_NormalPriority,mr=e.unstable_LowPriority,Cn=e.unstable_IdlePriority,z=e.log,Q=e.unstable_setDisableYieldValue,X=null,fe=null;function me(s){if(typeof z=="function"&&Q(s),fe&&typeof fe.setStrictMode=="function")try{fe.setStrictMode(X,s)}catch{}}var xe=Math.clz32?Math.clz32:Ee,Se=Math.log,_e=Math.LN2;function Ee(s){return s>>>=0,s===0?32:31-(Se(s)/_e|0)|0}var rt=256,kt=262144,Zt=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function ze(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function xt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function bt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var s=Zt;return Zt<<=1,(Zt&62914560)===0&&(Zt=4194304),s}function _n(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Et(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function En(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Sc=/[\n"\\]/g;function ln(s){return s.replace(Sc,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fa(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+Rn(a)):s.value!==""+Rn(a)&&(s.value=""+Rn(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ia(s,C,Rn(a)):c!=null?Ia(s,C,Rn(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+Rn(k):s.removeAttribute("name")}function Io(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){Yr(s);return}c=c!=null?""+Rn(c):"",a=a!=null?""+Rn(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),Yr(s)}function Ia(s,a,c){a==="number"&&ki(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Os(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$f=!1;if(xr)try{var Uo={};Object.defineProperty(Uo,"passive",{get:function(){$f=!0}}),window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{$f=!1}var Qr=null,Ff=null,_c=null;function wy(){if(_c)return _c;var s,a=Ff,c=a.length,d,p="value"in Qr?Qr.value:Qr.textContent,v=p.length;for(s=0;s=qo),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Mi=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Mi)return s==="compositionend"||!Hf&&Ry(s,a)?(s=wy(),_c=Ff=Qr=null,Mi=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ki(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ki(s.document)}return a}function Gf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=xr&&"documentMode"in document&&11>=document.documentMode,Ti=null,Kf=null,Zo=null,Zf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Zf||Ti==null||Ti!==ki(d)||(d=Ti,"selectionStart"in d&&Gf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Zo&&Ko(Zo,d)||(Zo=d,d=yu(Kf,"onSelect"),0>=C,p-=C,Qs=1<<32-xe(a)+p|c<Ke?(tt=De,De=null):tt=De.sibling;var ut=se(J,De,te[Ke],ue);if(ut===null){De===null&&(De=tt);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=tt}if(Ke===te.length)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;KeKe?(tt=De,De=null):tt=De.sibling;var ya=se(J,De,ut.value,ue);if(ya===null){De===null&&(De=tt);break}s&&De&&ya.alternate===null&&a(J,De),G=v(ya,G,Ke),ct===null?$e=ya:ct.sibling=ya,ct=ya,De=tt}if(ut.done)return c(J,De),at&&wr(J,Ke),$e;if(De===null){for(;!ut.done;Ke++,ut=te.next())ut=de(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return at&&wr(J,Ke),$e}for(De=d(De);!ut.done;Ke++,ut=te.next())ut=oe(De,J,Ke,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ke:ut.key),G=v(ut,G,Ke),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),at&&wr(J,Ke),$e}function jt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Ya($e)===G.type){c(J,G.sibling),ue=p(G,te.props),el(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=qa(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=zc(te.type,te.key,te.props,null,J.mode,ue),el(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=th(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Ya(te),jt(J,G,te,ue)}if(be(te))return Ae(J,G,te,ue);if(Y(te)){if($e=Y(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return jt(J,G,Vc(te),ue);if(te.$$typeof===R)return jt(J,G,Fc(J,te),ue);Hc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=eh(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{Jo=0;var $e=jt(J,G,te,ue);return Vi=null,$e}catch(De){if(De===Ui||De===Pc)throw De;var ct=ss(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Xa=d0(!0),f0=d0(!1),ta=!1;function hh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function na(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function sa(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Dc(s),Yy(s,null,c),a}return Ac(s,d,a,c),Dc(s)}function tl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,rn(s,c)}}function ph(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var gh=!1;function nl(){if(gh){var s=Pi;if(s!==null)throw s}}function sl(s,a,c,d){gh=!1;var p=s.updateQueue;ta=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var de=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(et&se)===se:(d&se)===se){se!==0&&se===Ii&&(gh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Ae=s,Pe=k;se=a;var jt=c;switch(Pe.tag){case 1:if(Ae=Pe.payload,typeof Ae=="function"){de=Ae.call(jt,de,se);break e}de=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Pe.payload,se=typeof Ae=="function"?Ae.call(jt,de,se):Ae,se==null)break e;de=g({},de,se);break e;case 2:ta=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=de):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=de),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),la|=C,s.lanes=C,s.memoizedState=de}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,zh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);il(s,a,ce,ls(s))}else il(s,a,d,ls(s))}catch(de){il(s,a,{then:function(){},status:"rejected",reason:de},ls())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Ah(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_r,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),il(s,a.next.queue,{},ls())}function Dh(){return gn(jl)}function Z0(){return qt().memoizedState}function Y0(){return qt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ls();s=na(c);var d=sa(a,s,c);d!==null&&(Yn(d,a,c),tl(d,a,c)),a={cache:ch()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=ls();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Jc(s)?X0(a,c):(c=Wf(s,a,c,d),c!==null&&(Yn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=ls();il(s,a,c,d)}function il(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Jc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ns(k,C))return Ac(s,a,p,0),Nt===null&&Oc(),!1}catch{}if(c=Wf(s,a,p,d),c!==null)return Yn(c,s,d),W0(c,a,d),!0}return!1}function zh(s,a,c,d){if(d={lane:2,revertLane:hm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Jc(s)){if(a)throw Error(r(479))}else a=Wf(s,c,d,2),a!==null&&Yn(a,s,2)}function Jc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){qi=Gc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,rn(s,c)}}var ol={readContext:gn,use:Yc,useCallback:Ft,useContext:Ft,useEffect:Ft,useImperativeHandle:Ft,useLayoutEffect:Ft,useInsertionEffect:Ft,useMemo:Ft,useReducer:Ft,useRef:Ft,useState:Ft,useDebugValue:Ft,useDeferredValue:Ft,useTransition:Ft,useSyncExternalStore:Ft,useId:Ft,useHostTransitionStatus:Ft,useFormState:Ft,useActionState:Ft,useOptimistic:Ft,useMemoCache:Ft,useCacheRefresh:Ft};ol.useEffectEvent=Ft;var J0={readContext:gn,use:Yc,useCallback:function(s,a){return Dn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Xc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Xc(4194308,4,s,a)},useInsertionEffect:function(s,a){Xc(4,2,s,a)},useMemo:function(s,a){var c=Dn();a=a===void 0?null:a;var d=s();if(Wa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=Dn();if(c!==void 0){var p=c(a);if(Wa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=Dn();return s={current:s},a.memoizedState=s},useState:function(s){s=kh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Th,useDeferredValue:function(s,a){var c=Dn();return Oh(c,s,a)},useTransition:function(){var s=kh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),Dn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=Dn();if(at){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Nt===null)throw Error(r(349));(et&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Gi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=Dn(),a=Nt.identifierPrefix;if(at){var c=Xs,d=Qs;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Kc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[an]=a,v[kn]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&Nr(a)}}return Mt(a),Yh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&Nr(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,$i(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[an]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Jr(a,!0)}else s=xu(s).createTextNode(d),s[an]=a,a.stateNode=s}return Mt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=$i(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[an]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),s=!1}else c=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(as(a),a):(as(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Mt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=$i(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[an]=a}else Ba(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mt(a),p=!1}else p=ah(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(as(a),a):(as(a),null)}return as(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),ru(a,a.updateQueue),Mt(a),null);case 4:return je(),s===null&&vm(a.stateNode.containerInfo),Mt(a),null;case 10:return jr(a.type),Mt(a),null;case 19:if(D(Ht),d=a.memoizedState,d===null)return Mt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)cl(d,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=Bc(s),v!==null){for(a.flags|=128,cl(d,!1),s=v.updateQueue,a.updateQueue=s,ru(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(Ht,Ht.current&1|2),at&&wr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&dt()>cu&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304)}else{if(!p)if(s=Bc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,ru(a,s),cl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!at)return Mt(a),null}else 2*dt()-d.renderingStartTime>cu&&c!==536870912&&(a.flags|=128,p=!0,cl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=dt(),s.sibling=null,c=Ht.current,B(Ht,p?c&1|2:c&1),at&&wr(a,d.treeForkCount),s):(Mt(a),null);case 22:case 23:return as(a),yh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Mt(a),a.subtreeFlags&6&&(a.flags|=8192)):Mt(a),c=a.updateQueue,c!==null&&ru(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Za),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),jr(Yt),Mt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(sh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return jr(Yt),je(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Te(a),null;case 31:if(a.memoizedState!==null){if(as(a),a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(as(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ba()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(Ht),null;case 4:return je(),null;case 10:return jr(a.type),null;case 22:case 23:return as(a),yh(),s!==null&&D(Za),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return jr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(sh(a),a.tag){case 3:jr(Yt),je();break;case 26:case 27:case 5:Te(a);break;case 4:je();break;case 31:a.memoizedState!==null&&as(a);break;case 13:as(a);break;case 19:D(Ht);break;case 10:jr(a.type);break;case 22:case 23:as(a),yh(),s!==null&&D(Za);break;case 24:jr(Yt)}}function ul(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){gt(a,a.return,k)}}function ia(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){gt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){gt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){gt(s,s.return,d)}}}function _x(s,a,c){c.props=Ja(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){gt(s,a,d)}}function dl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){gt(s,a,p)}}function Ws(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){gt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){gt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){gt(s,s.return,p)}}function Qh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[kn]=a}catch(p){gt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ha(s.type)||s.tag===4}function Xh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ha(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Wh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=$t));else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Wh(s,a,c),s=s.sibling;s!==null;)Wh(s,a,c),s=s.sibling}function au(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&ha(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(au(s,a,c),s=s.sibling;s!==null;)au(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[an]=s,a[kn]=c}catch(v){gt(s,s.return,v)}}var kr=!1,Wt=!1,Jh=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Vk(s,a){if(s=s.containerInfo,bm=Eu,s=Uy(s),Gf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,de=s,se=null;t:for(;;){for(var oe;de!==c||p!==0&&de.nodeType!==3||(k=C+p),de!==v||d!==0&&de.nodeType!==3||(F=C+d),de.nodeType===3&&(C+=de.nodeValue.length),(oe=de.firstChild)!==null;)se=de,de=oe;for(;;){if(de===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=de.nextSibling)!==null)break;de=se,se=de.parentNode}de=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(wm={focusedElem:s,selectionRange:c},Eu=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[an]=s,Lt(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kjt&&(C=jt,jt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,jt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=de.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>jt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(de=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&de.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=im,im=null;var v=ua,C=Ar;if(cn=0,Xi=ua=null,Ar=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,vl(0,!1),fe&&typeof fe.onPostCommitFiberRoot=="function")try{fe.onPostCommitFiberRoot(X,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=vs(c,a),a=Ih(s.stateNode,a,2),s=sa(s,a,2),s!==null&&(Et(s,2),Js(s))}function gt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(ca===null||!ca.has(d))){s=vs(c,s),c=ox(2),d=sa(a,c,2),d!==null&&(lx(c,d,a,s),Et(d,2),Js(d));break}}a=a.return}}function um(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(nm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Nt===s&&(et&c)===c&&(It===4||It===3&&(et&62914560)===et&&300>dt()-lu?(ft&2)===0&&Wi(s,0):sm|=c,Qi===et&&(Qi=0)),Js(s)}function ob(s,a){a===0&&(a=Vt()),s=Ha(s,a),s!==null&&(Et(s,a),Js(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return ht(s,a)}var pu=null,eo=null,dm=!1,gu=!1,fm=!1,fa=0;function Js(s){s!==eo&&s.next===null&&(eo===null?pu=eo=s:eo=eo.next=s),gu=!0,dm||(dm=!0,tR())}function vl(s,a){if(!fm&&gu){fm=!0;do for(var c=!1,d=pu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=et,v=ze(d,d===Nt?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||xt(d,v)||(c=!0,db(d,v));d=d.next}while(c);fm=!1}}function eR(){lb()}function lb(){gu=dm=!1;var s=0;fa!==0&&dR()&&(s=fa);for(var a=dt(),c=null,d=pu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?pu=p:c.next=p,p===null&&(eo=c)):(c=d,(s!==0||(v&3)!==0)&&(gu=!0)),d=p}cn!==0&&cn!==5||vl(s),fa!==0&&(fa=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,de=F.initiatorType;ce&&xb(de)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=to;if(d&&typeof a=="string"&&a){var p=ln(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function bR(s){Dr.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Dr.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Dr.L(s,a,c);var d=to;if(d&&s&&a){var p='link[rel="preload"][as="'+ln(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+ln(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+ln(c.imageSizes)+'"]')):p+='[href="'+ln(s)+'"]';var v=p;switch(a){case"style":v=no(s);break;case"script":v=so(s)}js.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),js.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(wl(v))||a==="script"&&d.querySelector(Sl(v))||(a=d.createElement("link"),yn(a,"link",s),Lt(a),d.head.appendChild(a)))}}function jR(s,a){Dr.m(s,a);var c=to;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+ln(d)+'"][href="'+ln(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=so(s)}if(!js.has(v)&&(s=g({rel:"modulepreload",href:s},a),js.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Sl(v)))return}d=c.createElement("link"),yn(d,"link",s),Lt(d),c.head.appendChild(d)}}}function CR(s,a,c){Dr.S(s,a,c);var d=to;if(d&&s){var p=vr(d).hoistableStyles,v=no(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(wl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=js.get(v))&&km(s,c);var F=C=d.createElement("link");Lt(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,wu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Dr.X(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Dr.M(s,a);var c=to;if(c&&s){var d=vr(c).hoistableScripts,p=so(s),v=d.get(p);v||(v=c.querySelector(Sl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=js.get(p))&&Rm(s,a),v=c.createElement("script"),Lt(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?bu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=no(c.href),c=vr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=no(c.href);var v=vr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(wl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),js.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},js.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=so(c),c=vr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function no(s){return'href="'+ln(s)+'"'}function wl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Lt(a),s.head.appendChild(a))}function so(s){return'[src="'+ln(s)+'"]'}function Sl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+ln(c.href)+'"]');if(d)return a.instance=d,Lt(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Lt(d),yn(d,"style",p),wu(d,c.precedence,s),a.instance=d;case"stylesheet":p=no(c.href);var v=s.querySelector(wl(p));if(v)return a.state.loading|=4,a.instance=v,Lt(v),v;d=Ab(c),(p=js.get(p))&&km(d,p),v=(s.ownerDocument||s).createElement("link"),Lt(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,wu(v,c.precedence,s),a.instance=v;case"script":return v=so(c.src),(p=s.querySelector(Sl(v)))?(a.instance=p,Lt(p),p):(d=c,(p=js.get(v))&&(d=g({},c),Rm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Lt(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,wu(d,c.precedence,s));return a.instance}function wu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=no(d.href),v=a.querySelector(wl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=ju.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Lt(v);return}v=a.ownerDocument||a,d=Ab(d),(p=js.get(p))&&km(d,p),v=v.createElement("link"),Lt(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=ju.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Mm=0;function MR(s,a){return s.stylesheets&&s.count===0&&_u(s,s.stylesheets),0Mm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_u(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var Cu=null;function _u(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,Cu=new Map,a.forEach(TR,s),Cu=null,ju.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=Cu.get(s);if(c)var d=c.get(null);else{c=new Map,Cu.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Im.exports=XR(),Im.exports}var JR=WR(),No=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends No{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},$g=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ii=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function $n(){}function aM(e,t){return typeof e=="function"?e(t):e}function kp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ca(e,t){return typeof e=="function"?e(t):e}function cs(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Fg(u,t.options))return!1}else if(!Vl(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(fi(t.options.mutationKey)!==fi(l))return!1}else if(!Vl(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Fg(e,t){return(t?.queryKeyHashFn||fi)(e)}function fi(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Vl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Vl(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Rp(e)&&Rp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ii.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ig=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ig?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Pg(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Hl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Tp(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var fn=fM(),hM=class extends No{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},vd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?vd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Tp(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Op(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>$g.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Hl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kp(this.gcTime)&&(this.#e=ii.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Hl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ii.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Ap,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Ap(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Ap(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Ap(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Mp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then($n).catch($n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>cs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ig||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ca(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Op&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Op){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),fn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends No{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Tp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof cs(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!gd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||Ca(this.options.staleTime,this.#t)!==Ca(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||cs(this.options.enabled,this.#t)!==cs(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch($n)),t}#g(){this.#b();const e=Ca(this.options.staleTime,this.#t);if(Hl.isServer()||this.#s.isStale||!kp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ii.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Hl.isServer()||cs(this.options.enabled,this.#t)===!1||!kp(this.#c)||this.#c===0)&&(this.#f=ii.setInterval(()=>{(this.options.refetchIntervalInBackground||$g.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ii.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ii.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Mp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Mp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Ug(e,t),refetch:this.refetch,promise:this.#o,isEnabled:cs(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},W=()=>{const ae=this.#o=L.promise=Tp();Z(ae)},Y=this.#o;switch(Y.status){case"pending":e.queryHash===n.queryHash&&Z(Y);break;case"fulfilled":(U||L.data!==Y.value)&&W();break;case"rejected":(!U||L.error!==Y.reason)&&W();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),gd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){fn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return cs(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&cs(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&Dp(e,t,t.refetchOnMount)}function Dp(e,t,n){if(cs(t.enabled,e)!==!1&&Ca(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ug(e,t)}return!1}function mw(e,t,n,r){return(e!==t||cs(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ug(e,n)}function Ug(e,t){return cs(t.enabled,e)!==!1&&e.isStaleByTime(Ca(t.staleTime,e))}function bM(e,t){return!gd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),fn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Au(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Au(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Au(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){fn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return fn.batch(()=>Promise.all(e.map(t=>t.continue().catch($n))))}};function Au(e){return e.options.scope?.id}var CM=class extends No{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),gd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&fi(n.mutationKey)!==fi(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){fn.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends No{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Fg(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){fn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){fn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){fn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=$g.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ca(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return fn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;fn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return fn.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=fn.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then($n).catch($n)}invalidateQueries(e,t={}){return fn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=fn.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch($n)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then($n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ca(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then($n).catch($n)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then($n).catch($n)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(fi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{Vl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(fi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{Vl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ig&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),mn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Pg(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Pg(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(fn.batchCalls(x)):$n;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Hl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch($n).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function nt(e,t){return tj(e,XS)}function FM(e,t){const n=mn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(fn.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch($n)},[r]);if(i.error&&Pg(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function qd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function Bd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Vg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function ko(e){const t=await e.text();throw new Vg(e.status,HM(e.status,t),t)}async function Qe(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&Bd(),t.ok||await ko(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&Bd(),t.ok||await ko(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await ko(i),qd(e,t),i.status===204?{}:i.json()}async function yd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&qd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&Bd(),n.ok||await ko(n),qd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&Bd(),f.ok||await ko(f),qd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await ko(l),await l.json()}let zp=null;function GM(){zp??=Qe("/api/config")}function KM(){return nt({queryKey:["config"],queryFn:async()=>{const e=zp;zp=null;const t=await(e??Qe("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var nc=VS();const ZM=PS(nc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function So(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Du=="function"&&(i=Du(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Du=="function"&&(j=Du(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Kt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=jo("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Du=Hd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ot=aT.reduce((e,t)=>{const n=jo(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&nc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(ot.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Ra(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Ra(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=jo(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Kt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=jo(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Kt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ir=globalThis?.document?b.useLayoutEffect:()=>{},uT=Hd[" useInsertionEffect ".trim().toString()]||ir;function sc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var fr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};fr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Rl(r.current),u.current=void 0):l.current="none"},[h]),ir(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Rl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ir(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Rl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Rl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Rl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function us(e){const[t,n]=b.useState(vT());return ir(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Vr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",Lp="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,Hg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Gd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(Hg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Kt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(W=>{l?.(W),f?.(W),W.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(W=>{if(!(W instanceof Node))return!1;const Y=[...y.branches].some(ae=>ae.contains(W));return A&&!Y},[y.branches,A])}),H=kT(W=>{if(r&&M.current)return;const Y=W.target;[...y.branches].some(le=>le.contains(Y))||(u?.(W),f?.(W),W.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Vr(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&h&&(W.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const W=()=>j({});return document.addEventListener(Lp,W),()=>document.removeEventListener(Lp,W)},[]),o.jsx(ot.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Gd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(Hg),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ot.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(Hg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Vr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Vr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent(Lp);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var Hm="focusScope.autoFocusOnMount",qm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",qg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Vr(i),y=Vr(l),g=b.useRef(null),w=Kt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:wa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||wa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&wa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(Hm,jw);f.addEventListener(Hm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&wa(f))}return()=>{f.removeEventListener(Hm,m),setTimeout(()=>{const _=new CustomEvent(qm,jw);f.addEventListener(qm,y),f.dispatchEvent(_),_.defaultPrevented||wa(S??document.body,{select:!0}),f.removeEventListener(qm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&wa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&wa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(ot.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});qg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(wa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function wa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Kd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ir(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?nc.createPortal(o.jsx(ot.div,{...r,ref:t}),u):null});Kd.displayName=LT;var zu=0,ao=null;function dj(){b.useEffect(()=>{ao||(ao={start:Nw(),end:Nw()});const{start:e,end:t}=ao;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),zu++,()=>{zu===1&&(ao?.start.remove(),ao?.end.remove(),ao=null),zu=Math.max(0,zu-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var rr=function(){return rr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),yo="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
+`+d.stack}}var Nt=Object.prototype.hasOwnProperty,un=e.unstable_scheduleCallback,jt=e.unstable_cancelCallback,Lt=e.unstable_shouldYield,ts=e.unstable_requestPaint,At=e.unstable_now,nn=e.unstable_getCurrentPriorityLevel,ns=e.unstable_ImmediatePriority,hr=e.unstable_UserBlockingPriority,Hs=e.unstable_NormalPriority,ms=e.unstable_LowPriority,Tn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Ae,je=Math.log,_e=Math.LN2;function Ae(s){return s>>>=0,s===0?32:31-(je(s)/_e|0)|0}var Ke=256,Ct=262144,sn=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function dt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function Et(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $t(){var s=sn;return sn<<=1,(sn&62914560)===0&&(sn=4194304),s}function Hn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function vt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function dn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Lf=/[\n"\\]/g;function On(s){return s.replace(Lf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Bs(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+En(a)):s.value!==""+En(a)&&(s.value=""+En(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ti(s,C,En(a)):c!=null?Ti(s,C,En(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+En(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){ki(s);return}c=c!=null?""+En(c):"",a=a!=null?""+En(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),ki(s)}function Ti(s,a,c){a==="number"&&Ri(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Gs(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ff=!1;if(vr)try{var Ho={};Object.defineProperty(Ho,"passive",{get:function(){Ff=!0}}),window.addEventListener("test",Ho,Ho),window.removeEventListener("test",Ho,Ho)}catch{Ff=!1}var Zr=null,If=null,Cc=null;function wy(){if(Cc)return Cc;var s,a=If,c=a.length,d,p="value"in Zr?Zr.value:Zr.textContent,v=p.length;for(s=0;s=Go),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Di=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Di)return s==="compositionend"||!qf&&Ry(s,a)?(s=wy(),Cc=If=Zr=null,Di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Ri(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Ri(s.document)}return a}function Kf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=vr&&"documentMode"in document&&11>=document.documentMode,zi=null,Zf=null,Qo=null,Yf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Yf||zi==null||zi!==Ri(d)||(d=zi,"selectionStart"in d&&Kf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Qo&&Yo(Qo,d)||(Qo=d,d=vu(Zf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ze?(st=De,De=null):st=De.sibling;var ut=se(J,De,te[Ze],ue);if(ut===null){De===null&&(De=st);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=st}if(Ze===te.length)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;ZeZe?(st=De,De=null):st=De.sibling;var ga=se(J,De,ut.value,ue);if(ga===null){De===null&&(De=st);break}s&&De&&ga.alternate===null&&a(J,De),G=v(ga,G,Ze),ct===null?$e=ga:ct.sibling=ga,ct=ga,De=st}if(ut.done)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;!ut.done;Ze++,ut=te.next())ut=fe(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return it&&xr(J,Ze),$e}for(De=d(De);!ut.done;Ze++,ut=te.next())ut=oe(De,J,Ze,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ze:ut.key),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),it&&xr(J,Ze),$e}function bt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Za($e)===G.type){c(J,G.sibling),ue=p(G,te.props),nl(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ha(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=Dc(te.type,te.key,te.props,null,J.mode,ue),nl(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=nh(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Za(te),bt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if($e=Q(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return bt(J,G,Uc(te),ue);if(te.$$typeof===R)return bt(J,G,$c(J,te),ue);Vc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=th(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{tl=0;var $e=bt(J,G,te,ue);return Gi=null,$e}catch(De){if(De===Bi||De===Ic)throw De;var ct=rs(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Qa=d0(!0),f0=d0(!1),Jr=!1;function mh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ph(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ea(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function ta(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Ac(s),Yy(s,null,c),a}return Oc(s,d,a,c),Ac(s)}function sl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}function gh(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var vh=!1;function rl(){if(vh){var s=qi;if(s!==null)throw s}}function al(s,a,c,d){vh=!1;var p=s.updateQueue;Jr=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(nt&se)===se:(d&se)===se){se!==0&&se===Hi&&(vh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Pe=k;se=a;var bt=c;switch(Pe.tag){case 1:if(Oe=Pe.payload,typeof Oe=="function"){fe=Oe.call(bt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Pe.payload,se=typeof Oe=="function"?Oe.call(bt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:Jr=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ia|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,Lh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);ll(s,a,ce,cs(s))}else ll(s,a,d,cs(s))}catch(fe){ll(s,a,{then:function(){},status:"rejected",reason:fe},cs())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Dh(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),ll(s,a.next.queue,{},cs())}function zh(){return gn(_l)}function Z0(){return Bt().memoizedState}function Y0(){return Bt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=cs();s=ea(c);var d=ta(a,s,c);d!==null&&(Xn(d,a,c),sl(d,a,c)),a={cache:uh()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=cs();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Wc(s)?X0(a,c):(c=Jf(s,a,c,d),c!==null&&(Xn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=cs();ll(s,a,c,d)}function ll(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Wc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ss(k,C))return Oc(s,a,p,0),_t===null&&Tc(),!1}catch{}if(c=Jf(s,a,p,d),c!==null)return Xn(c,s,d),W0(c,a,d),!0}return!1}function Lh(s,a,c,d){if(d={lane:2,revertLane:mm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Wc(s)){if(a)throw Error(r(479))}else a=Jf(s,c,d,2),a!==null&&Xn(a,s,2)}function Wc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Zi=Bc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}var cl={readContext:gn,use:Zc,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};cl.useEffectEvent=Pt;var J0={readContext:gn,use:Zc,useCallback:function(s,a){return zn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Qc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Qc(4194308,4,s,a)},useInsertionEffect:function(s,a){Qc(4,2,s,a)},useMemo:function(s,a){var c=zn();a=a===void 0?null:a;var d=s();if(Xa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=zn();if(c!==void 0){var p=c(a);if(Xa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=zn();return s={current:s},a.memoizedState=s},useState:function(s){s=Rh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Oh,useDeferredValue:function(s,a){var c=zn();return Ah(c,s,a)},useTransition:function(){var s=Rh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),zn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=zn();if(it){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),_t===null)throw Error(r(349));(nt&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Qi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=zn(),a=_t.identifierPrefix;if(it){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Gc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[Ft]=a,v[_n]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&_r(a)}}return Rt(a),Qh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&_r(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ui(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[Ft]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Xr(a,!0)}else s=yu(s).createTextNode(d),s[Ft]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ui(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(is(a),a):(is(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ui(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(is(a),a):(is(a),null)}return is(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),su(a,a.updateQueue),Rt(a),null);case 4:return Se(),s===null&&ym(a.stateNode.containerInfo),Rt(a),null;case 10:return wr(a.type),Rt(a),null;case 19:if(D(qt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)dl(d,!1);else{if(Ut!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=qc(s),v!==null){for(a.flags|=128,dl(d,!1),s=v.updateQueue,a.updateQueue=s,su(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(qt,qt.current&1|2),it&&xr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&At()>lu&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304)}else{if(!p)if(s=qc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,su(a,s),dl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!it)return Rt(a),null}else 2*At()-d.renderingStartTime>lu&&c!==536870912&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=At(),s.sibling=null,c=qt.current,B(qt,p?c&1|2:c&1),it&&xr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return is(a),xh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&su(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Ka),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),wr(Yt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(rh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return wr(Yt),Se(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Me(a),null;case 31:if(a.memoizedState!==null){if(is(a),a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(is(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(qt),null;case 4:return Se(),null;case 10:return wr(a.type),null;case 22:case 23:return is(a),xh(),s!==null&&D(Ka),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return wr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(rh(a),a.tag){case 3:wr(Yt),Se();break;case 26:case 27:case 5:Me(a);break;case 4:Se();break;case 31:a.memoizedState!==null&&is(a);break;case 13:is(a);break;case 19:D(qt);break;case 10:wr(a.type);break;case 22:case 23:is(a),xh(),s!==null&&D(Ka);break;case 24:wr(Yt)}}function fl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ra(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Wa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function hl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Xh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[_n]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&da(s.type)||s.tag===4}function Wh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&da(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Jh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Qe));else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Jh(s,a,c),s=s.sibling;s!==null;)Jh(s,a,c),s=s.sibling}function ru(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(ru(s,a,c),s=s.sibling;s!==null;)ru(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[Ft]=s,a[_n]=c}catch(v){pt(s,s.return,v)}}var Er=!1,Wt=!1,em=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,fn=null;function Vk(s,a){if(s=s.containerInfo,wm=_u,s=Uy(s),Kf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(Sm={focusedElem:s,selectionRange:c},_u=!1,fn=a;fn!==null;)if(a=fn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,fn=s;else for(;fn!==null;){switch(a=fn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[Ft]=s,Ht(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kbt&&(C=bt,bt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,bt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>bt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=om,om=null;var v=la,C=Tr;if(an=0,to=la=null,Tr=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,xl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=xs(c,a),a=Ph(s.stateNode,a,2),s=ta(s,a,2),s!==null&&(vt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(oa===null||!oa.has(d))){s=xs(c,s),c=ox(2),d=ta(a,c,2),d!==null&&(lx(c,d,a,s),vt(d,2),Ws(d));break}}a=a.return}}function dm(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(sm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,_t===s&&(nt&c)===c&&(Ut===4||Ut===3&&(nt&62914560)===nt&&300>At()-ou?(ft&2)===0&&no(s,0):rm|=c,eo===nt&&(eo=0)),Ws(s)}function ob(s,a){a===0&&(a=$t()),s=Va(s,a),s!==null&&(vt(s,a),Ws(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return un(s,a)}var mu=null,ro=null,fm=!1,pu=!1,hm=!1,ua=0;function Ws(s){s!==ro&&s.next===null&&(ro===null?mu=ro=s:ro=ro.next=s),pu=!0,fm||(fm=!0,tR())}function xl(s,a){if(!hm&&pu){hm=!0;do for(var c=!1,d=mu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=nt,v=Le(d,d===_t?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||dt(d,v)||(c=!0,db(d,v));d=d.next}while(c);hm=!1}}function eR(){lb()}function lb(){pu=fm=!1;var s=0;ua!==0&&dR()&&(s=ua);for(var a=At(),c=null,d=mu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?mu=p:c.next=p,p===null&&(ro=c)):(c=d,(s!==0||(v&3)!==0)&&(pu=!0)),d=p}an!==0&&an!==5||xl(s),ua!==0&&(ua=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=ao;if(d&&typeof a=="string"&&a){var p=On(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function bR(s){Or.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Or.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Or.L(s,a,c);var d=ao;if(d&&s&&a){var p='link[rel="preload"][as="'+On(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+On(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+On(c.imageSizes)+'"]')):p+='[href="'+On(s)+'"]';var v=p;switch(a){case"style":v=io(s);break;case"script":v=oo(s)}_s.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),_s.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(jl(v))||a==="script"&&d.querySelector(Cl(v))||(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function jR(s,a){Or.m(s,a);var c=ao;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+On(d)+'"][href="'+On(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=oo(s)}if(!_s.has(v)&&(s=g({rel:"modulepreload",href:s},a),_s.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Cl(v)))return}d=c.createElement("link"),yn(d,"link",s),Ht(d),c.head.appendChild(d)}}}function CR(s,a,c){Or.S(s,a,c);var d=ao;if(d&&s){var p=Gr(d).hoistableStyles,v=io(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(jl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=_s.get(v))&&Rm(s,c);var F=C=d.createElement("link");Ht(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,bu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Or.X(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Or.M(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?xu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=io(c.href),c=Gr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=io(c.href);var v=Gr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(jl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),_s.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},_s.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=oo(c),c=Gr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function io(s){return'href="'+On(s)+'"'}function jl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Ht(a),s.head.appendChild(a))}function oo(s){return'[src="'+On(s)+'"]'}function Cl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+On(c.href)+'"]');if(d)return a.instance=d,Ht(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Ht(d),yn(d,"style",p),bu(d,c.precedence,s),a.instance=d;case"stylesheet":p=io(c.href);var v=s.querySelector(jl(p));if(v)return a.state.loading|=4,a.instance=v,Ht(v),v;d=Ab(c),(p=_s.get(p))&&Rm(d,p),v=(s.ownerDocument||s).createElement("link"),Ht(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,bu(v,c.precedence,s),a.instance=v;case"script":return v=oo(c.src),(p=s.querySelector(Cl(v)))?(a.instance=p,Ht(p),p):(d=c,(p=_s.get(v))&&(d=g({},c),Mm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Ht(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,bu(d,c.precedence,s));return a.instance}function bu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=io(d.href),v=a.querySelector(jl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=Su.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Ht(v);return}v=a.ownerDocument||a,d=Ab(d),(p=_s.get(p))&&Rm(d,p),v=v.createElement("link"),Ht(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=Su.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Tm=0;function MR(s,a){return s.stylesheets&&s.count===0&&Cu(s,s.stylesheets),0Tm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ju=null;function Cu(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ju=new Map,a.forEach(TR,s),ju=null,Su.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=ju.get(s);if(c)var d=c.get(null);else{c=new Map,ju.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Pm.exports=XR(),Pm.exports}var JR=WR(),To=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends To{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fg=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ai=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Fn(){}function aM(e,t){return typeof e=="function"?e(t):e}function Rp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Sa(e,t){return typeof e=="function"?e(t):e}function us(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Ig(u,t.options))return!1}else if(!ql(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(di(t.options.mutationKey)!==di(l))return!1}else if(!ql(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ig(e,t){return(t?.queryKeyHashFn||di)(e)}function di(e){return JSON.stringify(e,(t,n)=>Mp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function ql(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ql(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Mp(e)&&Mp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ai.setTimeout(t,e)})}function Tp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pg=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ug(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Bl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Op(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var cn=fM(),hM=class extends To{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},gd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?gd.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Op(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Ap(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>Fg.isFocused()&&(e.networkMode==="always"||gd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Bl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rp(this.gcTime)&&(this.#e=ai.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Bl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ai.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Dp,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Dp(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Dp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Dp(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Tp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Fn).catch(Fn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>us(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Sa(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Ap&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Ap){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),cn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends To{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Op(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof us(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!pd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||Sa(this.options.staleTime,this.#t)!==Sa(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Fn)),t}#g(){this.#b();const e=Sa(this.options.staleTime,this.#t);if(Bl.isServer()||this.#s.isStale||!Rp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ai.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Bl.isServer()||us(this.options.enabled,this.#t)===!1||!Rp(this.#c)||this.#c===0)&&(this.#f=ai.setInterval(()=>{(this.options.refetchIntervalInBackground||Fg.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ai.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ai.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Tp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Tp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Vg(e,t),refetch:this.refetch,promise:this.#o,isEnabled:us(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Op();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),pd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){cn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return us(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&us(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&zp(e,t,t.refetchOnMount)}function zp(e,t,n){if(us(t.enabled,e)!==!1&&Sa(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vg(e,t)}return!1}function mw(e,t,n,r){return(e!==t||us(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vg(e,n)}function Vg(e,t){return us(t.enabled,e)!==!1&&e.isStaleByTime(Sa(t.staleTime,e))}function bM(e,t){return!pd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),cn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ou(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ou(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){cn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){cn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return cn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Fn))))}};function Ou(e){return e.options.scope?.id}var CM=class extends To{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),pd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&di(n.mutationKey)!==di(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){cn.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Ig(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){cn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){cn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){cn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){cn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Fg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Sa(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return cn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;cn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return cn.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=cn.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Fn).catch(Fn)}invalidateQueries(e,t={}){return cn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=cn.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Fn)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Fn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Sa(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Fn).catch(Fn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Fn).catch(Fn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(di(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ql(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(di(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{ql(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ig(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),hn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Ug(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Ug(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=hn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(cn.batchCalls(x)):Fn;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Bl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Fn).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function rt(e,t){return tj(e,XS)}function FM(e,t){const n=hn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(cn.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Fn)},[r]);if(i.error&&Ug(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function Hd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function qd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Hg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function Oo(e){const t=await e.text();throw new Hg(e.status,HM(e.status,t),t)}async function We(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&qd(),t.ok||await Oo(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&qd(),t.ok||await Oo(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await Oo(i),Hd(e,t),i.status===204?{}:i.json()}async function vd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&Hd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&qd(),n.ok||await Oo(n),Hd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&qd(),f.ok||await Oo(f),Hd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await Oo(l),await l.json()}let Lp=null;function GM(){Lp??=We("/api/config")}function KM(){return rt({queryKey:["config"],queryFn:async()=>{const e=Lp;Lp=null;const t=await(e??We("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var rc=VS();const ZM=PS(rc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Eo(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Au=="function"&&(i=Au(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Au=="function"&&(j=Au(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Zt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=No("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Au=Vd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=aT.reduce((e,t)=>{const n=No(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&rc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(lt.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Na(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Na(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=No(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Zt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=No(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Zt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?b.useLayoutEffect:()=>{},uT=Vd[" useInsertionEffect ".trim().toString()]||ar;function ac({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Tl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Tl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Tl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Tl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Tl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function ds(e){const[t,n]=b.useState(vT());return ar(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Pr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",$p="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,qg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Bd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(qg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Zt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=kT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Pr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const X=()=>j({});return document.addEventListener($p,X),()=>document.removeEventListener($p,X)},[]),o.jsx(lt.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Bd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(qg),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(lt.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(qg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Pr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Pr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent($p);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var qm="focusScope.autoFocusOnMount",Bm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",Bg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Pr(i),y=Pr(l),g=b.useRef(null),w=Zt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:xa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||xa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&xa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(qm,jw);f.addEventListener(qm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&xa(f))}return()=>{f.removeEventListener(qm,m),setTimeout(()=>{const _=new CustomEvent(Bm,jw);f.addEventListener(Bm,y),f.dispatchEvent(_),_.defaultPrevented||xa(S??document.body,{select:!0}),f.removeEventListener(Bm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&xa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&xa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(lt.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});Bg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function xa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Gd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?rc.createPortal(o.jsx(lt.div,{...r,ref:t}),u):null});Gd.displayName=LT;var Du=0,co=null;function dj(){b.useEffect(()=>{co||(co={start:Nw(),end:Nw()});const{start:e,end:t}=co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Du++,()=>{Du===1&&(co?.start.remove(),co?.end.remove(),co=null),Du=Math.max(0,Du-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),So="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
   .`.concat(FT,` {
    overflow: hidden `).concat(r,`;
    padding-right: `).concat(f,"px ").concat(r,`;
   }
-  body[`).concat(yo,`] {
+  body[`).concat(So,`] {
     overflow: hidden `).concat(r,`;
     overscroll-behavior: contain;
     `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
@@ -25,34 +25,34 @@ Error generating stack: `+d.message+`
     `),n==="padding"&&"padding-right: ".concat(f,"px ").concat(r,";")].filter(Boolean).join(""),`
   }
   
-  .`).concat(sd,` {
+  .`).concat(nd,` {
     right: `).concat(f,"px ").concat(r,`;
   }
   
-  .`).concat(rd,` {
+  .`).concat(sd,` {
     margin-right: `).concat(f,"px ").concat(r,`;
   }
   
-  .`).concat(sd," .").concat(sd,` {
+  .`).concat(nd," .").concat(nd,` {
     right: 0 `).concat(r,`;
   }
   
-  .`).concat(rd," .").concat(rd,` {
+  .`).concat(sd," .").concat(sd,` {
     margin-right: 0 `).concat(r,`;
   }
   
-  body[`).concat(yo,`] {
+  body[`).concat(So,`] {
     `).concat(IT,": ").concat(f,`px;
   }
-`)},Rw=function(){var e=parseInt(document.body.getAttribute(yo)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(yo,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(yo):document.body.setAttribute(yo,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},$p=!1;if(typeof window<"u")try{var Lu=Object.defineProperty({},"passive",{get:function(){return $p=!0,!0}});window.addEventListener("test",Lu,Lu),window.removeEventListener("test",Lu,Lu)}catch{$p=!1}var io=$p?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},$u=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return`
+`)},Rw=function(){var e=parseInt(document.body.getAttribute(So)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(So,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(So):document.body.setAttribute(So,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},Fp=!1;if(typeof window<"u")try{var zu=Object.defineProperty({},"passive",{get:function(){return Fp=!0,!0}});window.addEventListener("test",zu,zu),window.removeEventListener("test",zu,zu)}catch{Fp=!1}var uo=Fp?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},Lu=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return`
   .block-interactivity-`.concat(e,` {pointer-events: none;}
   .allow-interactivity-`).concat(e,` {pointer-events: all;}
-`)},pO=0,oo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],l=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=$u(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var W=Mw(L,M);if(!W)return!0;if(W?A=L:(A=L==="v"?"h":"v",W=Mw(L,M)),!W)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Y=r.current||A;return fO(Y,E,S,Y==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!oo.length||oo[oo.length-1]!==l)){var _="deltaY"in E?Tw(E):$u(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=$u(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,$u(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return oo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,io),document.addEventListener("touchmove",h,io),document.addEventListener("touchstart",y,io),function(){oo=oo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,io),document.removeEventListener("touchmove",h,io),document.removeEventListener("touchstart",y,io)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Bg=b.forwardRef(function(e,t){return b.createElement(Zd,rr({},e,{ref:t,sideCar:yO}))});Bg.classNames=Zd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},lo=new WeakMap,Fu=new WeakMap,Iu={},Zm=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Iu[n]||(Iu[n]=new WeakMap);var l=Iu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(lo.get(w)||0)+1,E=(l.get(w)||0)+1;lo.set(w,S),l.set(w,E),u.push(w),S===1&&j&&Fu.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Zm++,function(){u.forEach(function(g){var w=lo.get(g)-1,x=l.get(g)-1;lo.set(g,w),l.set(g,x),w||(Fu.has(g)||g.removeAttribute(r),Fu.delete(g)),x||g.removeAttribute(n)}),Zm--,Zm||(lo=new WeakMap,lo=new WeakMap,Fu=new WeakMap,Iu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Yd="Dialog",[wj]=Ra(Yd),[SO,qs]=wj(Yd),Gg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=sc({prop:r,defaultProp:i??!1,onChange:l,caller:Yd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:us(),titleId:us(),descriptionId:us(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Gg.displayName=Yd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Sj,n),l=Kt(t,i.triggerRef);return o.jsx(ot.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Xg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Kg="DialogPortal",[CO,jj]=wj(Kg,{forceMount:void 0}),Zg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=qs(Kg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:u})}))})};Zg.displayName=Kg;var xd="DialogOverlay",Yg=b.forwardRef((e,t)=>{const n=jj(xd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(xd,e.__scopeDialog);return l.modal?o.jsx(fr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Yg.displayName=xd;var _O=jo("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(xd,n),l=_T(),u=Kt(t,l);return o.jsx(Bg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(ot.div,{"data-state":Xg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),Co="DialogContent",Qg=b.forwardRef((e,t)=>{const n=jj(Co,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=qs(Co,e.__scopeDialog);return o.jsx(fr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Qg.displayName=Co;var NO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(null),i=Kt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=qs(Co,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=qs(Co,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(qg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Gd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Xg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(_j,n);return o.jsx(ot.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Nj,n);return o.jsx(ot.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=qs(Rj,n);return o.jsx(ot.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Xg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ir(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],_a=Math.min,Ir=Math.max,bd=Math.round,Pu=Math.floor,Pr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return Ir(e,_a(t,n))}function Hr(e,t){return typeof e=="function"?e(t):e}function Ea(e){return e.split("-")[0]}function Ro(e){return e.split("-")[1]}function Wg(e){return e==="x"?"y":"x"}function Jg(e){return e==="y"?"height":"width"}function ar(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ev(e){return Wg(ar(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ro(e),i=ev(e),l=Jg(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=wd(u)),[u,wd(u)]}function AO(e){const t=wd(e);return[Fp(e),t,Fp(t)]}function Fp(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ro(e);let l=LO(Ea(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Fp)))),l}function wd(e){const t=Ea(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function Sd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=ar(t),u=ev(t),f=Jg(u),h=Ea(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ro(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Hr(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=Sd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=Sd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Hr(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=ev(i),j=Jg(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=_a(g[_],U),W=_a(g[N],U),Y=L-S[j]-W,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Y),be=!h.arrow&&Ro(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var W,Y;const le=(((W=l.flip)==null?void 0:W.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==ar(be):!1)||Z.every(V=>ar(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Y=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Y.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=ar(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Hr(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ea(n),f=Ro(n),h=ar(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Hr(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Hr(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=ar(i),x=Wg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Hr(e,t),w={x:i,y:l},x=ar(u),j=Wg(x);let S=w[j],E=w[x];const _=Hr(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ea(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Hr(e,t),h=await i.detectOverflow(t,f),m=Ea(n),y=Ro(n),g=ar(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=_a(x-h[j],E),R=_a(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*Ir(h.left,h.right):M=x-2*Ir(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Qd(){return typeof window<"u"}function Mo(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Xn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Br(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Qd()?e instanceof Node||e instanceof Xn(e).Node:!1}function cr(e){return Qd()?e instanceof Element||e instanceof Xn(e).Element:!1}function Ma(e){return Qd()?e instanceof HTMLElement||e instanceof Xn(e).HTMLElement:!1}function Fw(e){return!Qd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xn(e).ShadowRoot}function Xd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ur(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Mo(e))}function Wd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ni=e=>!!e&&e!=="none";let Ym;function tv(e){const t=cr(e)?ur(e):e;return ni(t.transform)||ni(t.translate)||ni(t.scale)||ni(t.rotate)||ni(t.perspective)||!nv()&&(ni(t.backdropFilter)||ni(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=hi(e);for(;Ma(t)&&!ql(t);){if(tv(t))return t;if(Wd(t))return null;t=hi(t)}return null}function nv(){return Ym==null&&(Ym=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ym}function ql(e){return/^(html|body|#document)$/.test(Mo(e))}function ur(e){return Xn(e).getComputedStyle(e)}function Jd(e){return cr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function hi(e){if(Mo(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Br(e);return Fw(t)?t.host:t}function zj(e){const t=hi(e);return ql(t)?(e.ownerDocument||e).body:Ma(t)&&Xd(t)?t:zj(t)}function Bl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Xn(i);if(l){const f=Ip(u);return t.concat(u,u.visualViewport||[],Xd(i)?i:[],f&&n?Bl(f):[])}else return t.concat(i,Bl(i,[],n))}function Ip(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=ur(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Ma(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=bd(n)!==l||bd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function sv(e){return cr(e)?e:e.contextElement}function xo(e){const t=sv(e);if(!Ma(t))return Pr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?bd(n.width):n.width)/r,f=(l?bd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Pr(0);function $j(e){const t=Xn(e);return!nv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Xn(e)}function mi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=sv(e);let u=Pr(1);t&&(r?cr(r)&&(u=xo(r)):u=xo(e));const f=tA(l,n,r)?$j(l):Pr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Xn(l),x=cr(r)?Xn(r):r;let j=w,S=Ip(j);for(;S&&x!==j;){const E=xo(S),_=S.getBoundingClientRect(),N=ur(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Xn(S),S=Ip(j)}}return Sd({width:y,height:g,x:h,y:m})}function ef(e,t){const n=Jd(e).scrollLeft;return t?t.left+n:mi(Br(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ef(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Br(r),f=t?Wd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Pr(1);const y=Pr(0),g=Ma(r);if((g||!l)&&((Mo(r)!=="body"||Xd(u))&&(h=Jd(r)),g)){const x=mi(r);m=xo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Pr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Jd(e),n=e.ownerDocument.body,r=Ir(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Ir(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+ef(e);const u=-t.scrollTop;return ur(n).direction==="rtl"&&(l+=Ir(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Xn(e),l=Br(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!nv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(ef(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=mi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=xo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Br(e));else if(cr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Bl(e,[],!1).filter(f=>cr(f)&&Mo(f)!=="body"),i=null;const l=ur(e).position==="fixed";let u=l?hi(e):e;for(;cr(u)&&!ql(u);){const f=ur(u),h=tv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=hi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Wd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Xn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=sv(e),y=i||l?[...m?Bl(m):[],...t?Bl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?mi(e):null;h&&E();function E(){const _=mi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},ad=CA?b.useLayoutEffect:_A;function jd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!jd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!jd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Xm(e){const t=b.useRef(e);return ad(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);jd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Xm(h),W=Xm(i),Y=Xm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};W.current&&(V.platform=W.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Y.current!==!1};le.current&&!jd(H.current,K)&&(H.current=K,nc.flushSync(()=>{g(K)}))})},[w,t,n,W,Y]);ad(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);ad(()=>(le.current=!0,()=>{le.current=!1}),[]),ad(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(ot.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,rv="Popper",[Hj,tf]=Ra(rv),[$A,qj]=Hj(rv),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=rv;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Kt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&iv(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(ot.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var av="PopperContent",[FA,IA]=Hj(av),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(av,n),[_,N]=b.useState(null),R=Kt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},W=Array.isArray(m)?m:[m],Y=W.length>0,ae={padding:Z,boundary:W.filter(UA),altBoundary:Y},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:je,availableWidth:ve,availableHeight:Te})=>{const{width:Ze,height:mt}=je.reference,Je=we.floating.style;Je.setProperty("--radix-popper-available-width",`${ve}px`),Je.setProperty("--radix-popper-available-height",`${Te}px`),Je.setProperty("--radix-popper-anchor-width",`${Ze}px`),Je.setProperty("--radix-popper-anchor-height",`${mt}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Y?ae.boundary:void 0})]}),ee=E.setPlacementState;ir(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=iv($),D=Vr(j);ir(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ir(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(ot.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=av;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=iv(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function iv(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Wm=!1;function HA(){const[e,t]=b.useState(Wm);return b.useEffect(()=>{Wm||(Wm=!0,t(!0))},[]),e}var tC=Hd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,Jm="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},rc="RovingFocusGroup",[Pp,nC,ZA]=oj(rc),[YA,sC]=Ra(rc,[ZA]),[QA,XA]=YA(rc),rC=b.forwardRef((e,t)=>o.jsx(Pp.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Pp.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=rc;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Kt(t,w),j=lj(l),[S,E]=sc({prop:u,defaultProp:f??null,onChange:h,caller:rc}),[_,N]=b.useState(!1),R=Vr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(Jm,R),()=>H.removeEventListener(Jm,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(ot.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(Jm,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const W=T().filter($=>$.focusable),Y=W.find($=>$.active),ae=W.find($=>$.id===S),be=[Y,ae,...W].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=us(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ir(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Pp.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(ot.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Up=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Up,"ArrowRight"],rtl:[...Up,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ac="Menu",[Gl,cD,uD]=oj(ac),[wi,nf]=Ra(ac,[uD,tf,sC]),sf=tf(),cC=sC(),[dD,Si]=wi(ac),[fD,ic]=wi(ac),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=sf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Vr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=ac;var hD="MenuAnchor",ov=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(Wj,{...i,...r,ref:t})});ov.displayName=hD;var lv="MenuPortal",[mD,dC]=wi(lv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=Si(lv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};fC.displayName=lv;var Rs="MenuContent",[pD,cv]=wi(Rs),hC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=Si(Rs,e.__scopeMenu),u=ic(Rs,e.__scopeMenu);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||l.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu),r=b.useRef(null),i=Kt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(uv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=Si(Rs,e.__scopeMenu);return o.jsx(uv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=jo("MenuContent.ScrollLock"),uv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=Si(Rs,n),_=ic(Rs,n),N=sf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Kt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),W=b.useRef(0),Y=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Bg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Y.current?.side&&OD(ee,Y.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:W,onPointerGraceIntentChange:b.useCallback(ee=>{Y.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(qg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Kl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Rs;var xD="MenuGroup",dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"group",...r,ref:t})});dv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{...r,ref:t})});mC.displayName=bD;var Cd="MenuItem",Hw="menu.itemSelect",rf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=ic(Cd,e.__scopeMenu),f=cv(Cd,e.__scopeMenu),h=Kt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Up.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});rf.displayName=Cd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=cv(Cd,n),f=cC(n),h=b.useRef(null),m=Kt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Gl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(ot.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Kl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Kl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(rf,{role:"menuitemcheckbox","aria-checked":_d(n)?"mixed":n,...i,ref:t,"data-state":hv(n),onSelect:Ue(i.onSelect,()=>r?.(_d(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=wi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Vr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(dv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(rf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":hv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var fv="MenuItemIndicator",[wC,CD]=wi(fv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(fv,n);return o.jsx(fr,{present:r||_d(l.checked)||l.checked===!0,children:o.jsx(ot.span,{...i,ref:t,"data-state":hv(l.checked)})})});SC.displayName=fv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(ot.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=sf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=wi(ND),zl="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=Si(zl,e.__scopeMenu),r=ic(zl,e.__scopeMenu),i=_C(zl,e.__scopeMenu),l=cv(zl,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Kt(t,i.onTriggerChange);return o.jsx(ov,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Kl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Kl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=zl;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Rs,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=Si(Rs,e.__scopeMenu),f=ic(Rs,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Kt(t,m);return o.jsx(Gl.Provider,{scope:e.__scopeMenu,children:o.jsx(fr,{present:r||u.open,children:o.jsx(Gl.Slot,{scope:e.__scopeMenu,children:o.jsx(uv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function _d(e){return e==="indeterminate"}function hv(e){return _d(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Kl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=ov,OC=fC,AC=hC,DC=dv,zC=mC,LC=rf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,af="ContextMenu",[AD]=Ra(af,[nf]),Pn=nf(),[DD,BC]=AD(af),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=sc({prop:i,defaultProp:!1,onChange:r,caller:af}),y=Pn(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=af;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Pn(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(ot.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Uu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Uu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Uu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Uu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Pn(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Pn(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Pn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Uu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,of="DropdownMenu",[lz]=Ra(of,[nf]),Un=nf(),[cz,e_]=lz(of),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Un(t),m=b.useRef(null),[y,g]=sc({prop:i,defaultProp:l??!1,onChange:u,caller:of});return o.jsx(cz,{scope:t,triggerId:us(),triggerRef:m,contentId:us(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=of;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Un(n),f=Kt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(ot.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(ot.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(ot.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[lf]=Ra("Tooltip",[tf]),cf=tf(),p_="TooltipProvider",Hz=700,Vp="tooltip.open",[qz,mv]=lf(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Zl="Tooltip",[Bz,oc]=lf(Zl),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=mv(Zl,e.__scopeTooltip),m=cf(t),[y,g]=b.useState(null),w=us(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=sc({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Vp))):h.onClose(),l?.(L)},caller:Zl}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Zl;var Hp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=oc(Hp,n),l=mv(Hp,n),u=cf(n),f=b.useRef(null),h=Kt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(ot.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=Hp;var pv="TooltipPortal",[Gz,Kz]=lf(pv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=oc(pv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(fr,{present:n||l.open,children:o.jsx(Kd,{asChild:!0,container:i,children:r})})})};x_.displayName=pv;var _o="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(_o,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=oc(_o,e.__scopeTooltip);return o.jsx(fr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=oc(_o,e.__scopeTooltip),r=mv(_o,e.__scopeTooltip),i=b.useRef(null),l=Kt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=lf(Zl,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=oc(_o,n),m=cf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Vp,y),()=>document.removeEventListener(Vp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Gd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=_o;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ed="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(Ed),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(Ed):e.slice(t).join(Ed),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];gv(i,n,r,t)}return n},gv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(Ed),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},qp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+qp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],un=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,xa=e=>A4.test(e),Ye=e=>!!e&&!Number.isNaN(Number(e)),er=e=>!!e&&Number.isInteger(Number(e)),ep=e=>e.endsWith("%")&&Ye(e.slice(0,-1)),zr=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),vv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Me(e)&&!Oe(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ta(e,z_,vv),Me=e=>M_.test(e),si=e=>Ta(e,L_,I4),Zw=e=>Ta(e,W4,Ye),B4=e=>Ta(e,F_,O_),G4=e=>Ta(e,$_,vv),Yw=e=>Ta(e,A_,vv),K4=e=>Ta(e,D_,U4),Vu=e=>Ta(e,I_,P4),Oe=e=>T_.test(e),Ml=e=>ji(e,L_),Z4=e=>ji(e,$_),Qw=e=>ji(e,A_),Y4=e=>ji(e,z_),Q4=e=>ji(e,D_),Hu=e=>ji(e,I_,!0),X4=e=>ji(e,F_,!0),Ta=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},ji=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=un("color"),t=un("font"),n=un("text"),r=un("font-weight"),i=un("tracking"),l=un("leading"),u=un("breakpoint"),f=un("container"),h=un("spacing"),m=un("radius"),y=un("shadow"),g=un("inset-shadow"),w=un("text-shadow"),x=un("drop-shadow"),j=un("blur"),S=un("perspective"),E=un("aspect"),_=un("ease"),N=un("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Oe,Me],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Oe,Me,h],U=()=>[xa,"full","auto",...H()],Z=()=>[er,"none","subgrid",Oe,Me],W=()=>["auto",{span:["full",er,Oe,Me]},er,Oe,Me],Y=()=>[er,"auto",Oe,Me],ae=()=>["auto","min","max","fr",Oe,Me],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[xa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[xa,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[xa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Oe,Me],O=()=>[...T(),Qw,Yw,{position:[Oe,Me]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Oe,Me]}],P=()=>[ep,Ml,si],I=()=>["","none","full",m,Oe,Me],re=()=>["",Ye,Ml,si],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],je=()=>[Ye,ep,Qw,Yw],ve=()=>["","none",j,Oe,Me],Te=()=>["none",Ye,Oe,Me],Ze=()=>["none",Ye,Oe,Me],mt=()=>[Ye,Oe,Me],Je=()=>[xa,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zr],breakpoint:[zr],color:[O_],container:[zr],"drop-shadow":[zr],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zr],shadow:[zr],spacing:["px",Ye],text:[zr],"text-shadow":[zr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",xa,Me,Oe,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Oe,Me]}],"container-named":[H4],columns:[{columns:[Ye,Me,Oe,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[er,"auto",Oe,Me]}],basis:[{basis:[xa,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,xa,"auto","initial","none",Me]}],grow:[{grow:["",Ye,Oe,Me]}],shrink:[{shrink:["",Ye,Oe,Me]}],order:[{order:[er,"first","last","none",Oe,Me]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:W()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:W()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ml,si]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ep,Me]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Me]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Oe,Me]}],"line-clamp":[{"line-clamp":[Ye,"none",Oe,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Oe,Me]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Oe,Me]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Oe,si]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Ye,"auto",Oe,Me]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[er,Oe,Me]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Oe,Me]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Oe,Me]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},er,Oe,Me],radial:["",Oe,Me],conic:[er,Oe,Me]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Oe,Me]}],"outline-w":[{outline:["",Ye,Ml,si]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Hu,Vu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Hu,Vu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Ye,si]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Hu,Vu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Ye,Oe,Me]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":je()}],"mask-image-linear-to-pos":[{"mask-linear-to":je()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":je()}],"mask-image-t-to-pos":[{"mask-t-to":je()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":je()}],"mask-image-r-to-pos":[{"mask-r-to":je()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":je()}],"mask-image-b-to-pos":[{"mask-b-to":je()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":je()}],"mask-image-l-to-pos":[{"mask-l-to":je()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":je()}],"mask-image-x-to-pos":[{"mask-x-to":je()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":je()}],"mask-image-y-to-pos":[{"mask-y-to":je()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Oe,Me]}],"mask-image-radial-from-pos":[{"mask-radial-from":je()}],"mask-image-radial-to-pos":[{"mask-radial-to":je()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":je()}],"mask-image-conic-to-pos":[{"mask-conic-to":je()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Oe,Me]}],filter:[{filter:["","none",Oe,Me]}],blur:[{blur:ve()}],brightness:[{brightness:[Ye,Oe,Me]}],contrast:[{contrast:[Ye,Oe,Me]}],"drop-shadow":[{"drop-shadow":["","none",x,Hu,Vu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Ye,Oe,Me]}],"hue-rotate":[{"hue-rotate":[Ye,Oe,Me]}],invert:[{invert:["",Ye,Oe,Me]}],saturate:[{saturate:[Ye,Oe,Me]}],sepia:[{sepia:["",Ye,Oe,Me]}],"backdrop-filter":[{"backdrop-filter":["","none",Oe,Me]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Oe,Me]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Oe,Me]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Oe,Me]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Oe,Me]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Oe,Me]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Oe,Me]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Oe,Me]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Oe,Me]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Oe,Me]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Oe,Me]}],ease:[{ease:["linear","initial",_,Oe,Me]}],delay:[{delay:[Ye,Oe,Me]}],animate:[{animate:["none",N,Oe,Me]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Oe,Me]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Te()}],"rotate-x":[{"rotate-x":Te()}],"rotate-y":[{"rotate-y":Te()}],"rotate-z":[{"rotate-z":Te()}],scale:[{scale:Ze()}],"scale-x":[{"scale-x":Ze()}],"scale-y":[{"scale-y":Ze()}],"scale-z":[{"scale-z":Ze()}],"scale-3d":["scale-3d"],skew:[{skew:mt()}],"skew-x":[{"skew-x":mt()}],"skew-y":[{"skew-y":mt()}],transform:[{transform:[Oe,Me,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],zoom:[{zoom:[er,Oe,Me]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Oe,Me]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Oe,Me]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Ye,Ml,si,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function st(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function uf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function df({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function ff({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:st("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Bp=new Set;function n3(e){return Bp.add(e),()=>Bp.delete(e)}function bo(e){for(const t of Bp)t(e)}const oi=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Lr=/\.html?$/i,id=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Yl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function pi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function On(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Gp="(min-width: 1400px)";function hf(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function yv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var tp={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...tp,width:t??m??tp.width,height:t??m??tp.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],xv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],bv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=wv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),gi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}gi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function ds(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),gi(),e&&window.innerWidth<=wv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const wv=900;function gi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=wv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Kp="bdrive.sidebarWidth",aE=210,iE=480;function od(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function np(e){try{e===null?localStorage.removeItem(Kp):localStorage.setItem(Kp,String(e))}catch{}}const Zp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Zp(m.clientX-l),od(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&np(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{od(null),np(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Zp(u+l);od(f),np(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Kp));e&&od(Zp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",gi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){ds();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:xv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:bv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Yp={folder:xv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:bv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ui({name:e,className:t}){const n=e??"",r=Object.hasOwn(Yp,n)?Yp[n]:xv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function Sv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function go(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&gi()}function li(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:ds}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(jv,{id:"rail-search",icon:"search",label:"Search",hint:Yl?"⌘K":"Ctrl+K",onClick:()=>bo()}),t]})}function jv(e){return o.jsxs(uf,{delayDuration:100,children:[o.jsx(df,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(ff,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function mf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(Sv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function ci(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Yl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Qp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Qp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Qp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Qn=new xL,bL=(e,t)=>{const n=t?.id||Qp++;return Qn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Qn.toasts,CL=()=>Qn.getActiveToasts(),Ww=Object.assign(SL,{success:Qn.success,info:Qn.info,warning:Qn.warning,error:Qn.error,custom:Qn.custom,message:Qn.message,promise:Qn.promise,dismiss:Qn.dismiss,loading:Qn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function qu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function tr(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:W="",duration:Y,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[je,ve]=ye.useState(!1),[Te,Ze]=ye.useState(!1),[mt,Je]=ye.useState(0),[Wn,Fe]=ye.useState(0),it=ye.useRef(g.duration||Y||Jw),nn=ye.useRef(null),yt=ye.useRef(null),ht=_===0,sn=_+1<=S,Ut=g.type,An=g.dismissible!==!1,dt=g.className||"",Bs=g.descriptionClassName||"",hs=ye.useMemo(()=>E.findIndex(ze=>ze.toastId===g.id)||0,[E,g.id]),Gr=ye.useMemo(()=>{var ze;return(ze=g.closeButton)!=null?ze:M},[g.closeButton,M]),Vn=ye.useMemo(()=>g.duration||Y||Jw,[g.duration,Y]),mr=ye.useRef(0),Cn=ye.useRef(0),z=ye.useRef(0),Q=ye.useRef(null),[X,fe]=ae.split("-"),me=ye.useMemo(()=>E.reduce((ze,xt,bt)=>bt>=hs?ze:ze+xt.height,0),[E,hs]),xe=yL(),Se=g.invert||y,_e=Ut==="loading";Cn.current=ye.useMemo(()=>hs*le+me,[hs,me]),ye.useEffect(()=>{it.current=Vn},[Vn]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const ze=yt.current;if(ze){const xt=ze.getBoundingClientRect().height;return Fe(xt),j(bt=>[{toastId:g.id,height:xt,position:g.position},...bt]),()=>j(bt=>bt.filter(Vt=>Vt.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const ze=yt.current,xt=ze.style.height;ze.style.height="auto";const bt=ze.getBoundingClientRect().height;ze.style.height=xt,Fe(bt),j(Vt=>Vt.find(Et=>Et.toastId===g.id)?Vt.map(Et=>Et.toastId===g.id?{...Et,height:bt}:Et):[{toastId:g.id,height:bt,position:g.position},...Vt])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ee=ye.useCallback(()=>{re(!0),Je(Cn.current),j(ze=>ze.filter(xt=>xt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Cn]);ye.useEffect(()=>{if(g.promise&&Ut==="loading"||g.duration===1/0||g.type==="loading")return;let ze;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ee()},it.current)),()=>clearTimeout(ze)},[R,x,g,Ut,xe,Ee]),ye.useEffect(()=>{g.delete&&(Ee(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ee,g.delete]);function rt(){var ze;if(q?.loading){var xt;return ye.createElement("div",{className:tr($?.loader,g==null||(xt=g.classNames)==null?void 0:xt.loader,"sonner-loader"),"data-visible":Ut==="loading"},q.loading)}return ye.createElement(fL,{className:tr($?.loader,g==null||(ze=g.classNames)==null?void 0:ze.loader),visible:Ut==="loading"})}const kt=g.icon||q?.[Ut]||uL(Ut);var Zt,Dt;return ye.createElement("li",{tabIndex:0,ref:yt,className:tr(Z,dt,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Ut],g==null||(n=g.classNames)==null?void 0:n[Ut]),"data-sonner-toast":"","data-rich-colors":(Zt=g.richColors)!=null?Zt:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Te,"data-removed":I,"data-visible":sn,"data-y-position":X,"data-x-position":fe,"data-index":_,"data-front":ht,"data-swiping":he,"data-dismissible":An,"data-type":Ut,"data-invert":Se,"data-swipe-out":je,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?mt:Cn.current}px`,"--initial-height":be?"auto":`${Wn}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Q.current=null},onPointerDown:ze=>{ze.button!==2&&(_e||!An||(nn.current=new Date,Je(Cn.current),ze.target.setPointerCapture(ze.pointerId),ze.target.tagName!=="BUTTON"&&(we(!0),Q.current={x:ze.clientX,y:ze.clientY})))},onPointerUp:()=>{var ze,xt,bt;if(je||!An)return;Q.current=null;const Vt=Number(((ze=yt.current)==null?void 0:ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),_n=Number(((xt=yt.current)==null?void 0:xt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Et=new Date().getTime()-((bt=nn.current)==null?void 0:bt.getTime()),En=ee==="x"?Vt:_n,pr=Math.abs(En)/Et;if(Math.abs(En)>=ML||pr>.11){Je(Cn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?Vt>0?"right":"left":_n>0?"down":"up"),Ee(),ve(!0);return}else{var rn,Nn;(rn=yt.current)==null||rn.style.setProperty("--swipe-amount-x","0px"),(Nn=yt.current)==null||Nn.style.setProperty("--swipe-amount-y","0px")}Ze(!1),we(!1),K(null)},onPointerMove:ze=>{var xt,bt,Vt;if(!Q.current||!An||((xt=window.getSelection())==null?void 0:xt.toString().length)>0)return;const Et=ze.clientY-Q.current.y,En=ze.clientX-Q.current.x;var pr;const rn=(pr=e.swipeDirections)!=null?pr:OL(ae);!ee&&(Math.abs(En)>1||Math.abs(Et)>1)&&K(Math.abs(En)>Math.abs(Et)?"x":"y");let Nn={x:0,y:0};const gr=Jn=>1/(1.5+Math.abs(Jn)/20);if(ee==="y"){if(rn.includes("top")||rn.includes("bottom"))if(rn.includes("top")&&Et<0||rn.includes("bottom")&&Et>0)Nn.y=Et;else{const Jn=Et*gr(Et);Nn.y=Math.abs(Jn)0)Nn.x=En;else{const Jn=En*gr(En);Nn.x=Math.abs(Jn)0||Math.abs(Nn.y)>0)&&Ze(!0),(bt=yt.current)==null||bt.style.setProperty("--swipe-amount-x",`${Nn.x}px`),(Vt=yt.current)==null||Vt.style.setProperty("--swipe-amount-y",`${Nn.y}px`)}},Gr&&!g.jsx&&Ut!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!An?()=>{}:()=>{Ee(),g.onDismiss==null||g.onDismiss.call(g,g)},className:tr($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Ut||g.icon||g.promise)&&g.icon!==null&&(q?.[Ut]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:tr($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||rt():null,g.type!=="loading"?kt:null):null,ye.createElement("div",{"data-content":"",className:tr($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:tr($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:tr(W,Bs,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&qu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:ze=>{qu(g.cancel)&&An&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,ze),Ee())},className:tr($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&qu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:ze=>{qu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,ze),!ze.defaultPrevented&&Ee())},className:tr($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,W]=ye.useState([]),[Y,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Qn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Qn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,je)=>{var ve,Te;return ye.createElement(AL,{key:we.id,icons:T,index:je,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Te=_?.closeButton)!=null?Te:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ze=>Ze.position==we.position),heights:Z.filter(Ze=>Ze.position==we.position),setHeights:W,expandByDefault:f,gap:R,expanded:Y,swipeDirections:t.swipeDirections})})):null}))}),Nd="bdrive-theme",Xp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function Cv(){try{const e=localStorage.getItem(Nd);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function ld(){const e=LL(Cv()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Xp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Nd):localStorage.setItem(Nd,e)}catch{}ld()}let t1=!1;function IL(){if(!t1){t1=!0,ld();try{window.matchMedia(lE).addEventListener("change",()=>{Cv()==="system"&&ld()})}catch{}window.addEventListener("storage",e=>{(e.key===Nd||e.key===null)&&ld()})}}function PL(e){return window.addEventListener(Xp,e),()=>window.removeEventListener(Xp,e)}function n1(){return`${Cv()}:${$L()}`}function _v(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=_v();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function ke(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:st(qL({variant:t,size:n,className:e})),...i})}function lc({...e}){return o.jsx(Gg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Zg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Yg,{"data-slot":"dialog-overlay",className:st("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function cc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Qg,{"data-slot":"dialog-content",className:st("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function To({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:st("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:st("text-sm text-muted-foreground",e),...t})}let uE=null,cd=[];function uc(e){uE=e,cd.forEach(t=>t())}function Ql(e,t,n="",r="OK",i={}){return new Promise(l=>uc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function or(e,t,n="Confirm",r=!1){return new Promise(i=>uc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(cd.push(n),()=>{cd=cd.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{uc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(lc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(cc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{uc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{uc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let kd=null,ud=[];const Ev=e=>{kd=e,ud.forEach(t=>t())};function VB(e,t){Ev({...t,path:e,from:t})}function HB(e){kd?.from===e&&Ev(null)}function XL(){const e=b.useSyncExternalStore(f=>(ud.push(f),()=>{ud=ud.filter(h=>h!==f)}),()=>kd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),kd===e&&Ev(null)}},u=()=>{l(e.keep)};return o.jsx(lc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(cc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:pi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":pi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>Qe("/api/projects")};function WL(e){return nt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=mn();return()=>e.fetchQuery(dE)}function fE(e){return nt({queryKey:["orgs"],queryFn:()=>Qe("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function Nv(e){return nt({queryKey:["permissions",e],queryFn:()=>Qe(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return nt({queryKey:["folders",e],queryFn:()=>Qe(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return nt({queryKey:["shares",e],queryFn:()=>Qe(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return nt({queryKey:["admin","pending"],queryFn:()=>Qe("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function pf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Wp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Wp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Wp,e)?Wp[e]:void 0}const kv=["q","user","actor","device","range","since","until"];function Rv(e){return!!e&&kv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of kv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Mv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of kv){const y=r?.get(m);y&&(h[m]=y)}if(Rv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=pf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?pf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function Ln(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function dn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=pf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Tv="POP";const Jp=new Set;function xE(){for(const e of Jp)e()}window.addEventListener("popstate",()=>{Tv="POP",xE()});function vt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Tv=t?.replace?"REPLACE":"PUSH",xE())}function Ov(){return b.useSyncExternalStore(e=>(Jp.add(e),()=>{Jp.delete(e)}),()=>location.pathname+location.search)}function c$(){return Tv}function In(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),vt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ri({to:e}){return b.useEffect(()=>{vt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function Sa(e,t){return typeof e=="function"?e(t):e}function fs(e,t){return n=>{t.setState(r=>({...r,[e]:Sa(n,r[e])}))}}function gf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return fO(Q,E,S,Q==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!fo.length||fo[fo.length-1]!==l)){var _="deltaY"in E?Tw(E):Lu(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=Lu(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,Lu(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return fo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,uo),document.addEventListener("touchmove",h,uo),document.addEventListener("touchstart",y,uo),function(){fo=fo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,uo),document.removeEventListener("touchmove",h,uo),document.removeEventListener("touchstart",y,uo)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Gg=b.forwardRef(function(e,t){return b.createElement(Kd,sr({},e,{ref:t,sideCar:yO}))});Gg.classNames=Kd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ho=new WeakMap,$u=new WeakMap,Fu={},Ym=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Fu[n]||(Fu[n]=new WeakMap);var l=Fu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(ho.get(w)||0)+1,E=(l.get(w)||0)+1;ho.set(w,S),l.set(w,E),u.push(w),S===1&&j&&$u.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Ym++,function(){u.forEach(function(g){var w=ho.get(g)-1,x=l.get(g)-1;ho.set(g,w),l.set(g,x),w||($u.has(g)||g.removeAttribute(r),$u.delete(g)),x||g.removeAttribute(n)}),Ym--,Ym||(ho=new WeakMap,ho=new WeakMap,$u=new WeakMap,Fu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Zd="Dialog",[wj]=Na(Zd),[SO,Vs]=wj(Zd),Kg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=ac({prop:r,defaultProp:i??!1,onChange:l,caller:Zd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:ds(),titleId:ds(),descriptionId:ds(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Kg.displayName=Zd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Sj,n),l=Zt(t,i.triggerRef);return o.jsx(lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Wg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Zg="DialogPortal",[CO,jj]=wj(Zg,{forceMount:void 0}),Yg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Zg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:u})}))})};Yg.displayName=Zg;var yd="DialogOverlay",Qg=b.forwardRef((e,t)=>{const n=jj(yd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(yd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Qg.displayName=yd;var _O=No("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(yd,n),l=_T(),u=Zt(t,l);return o.jsx(Gg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(lt.div,{"data-state":Wg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),ko="DialogContent",Xg=b.forwardRef((e,t)=>{const n=jj(ko,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(ko,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Xg.displayName=ko;var NO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(null),i=Zt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(ko,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(Bg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Bd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Wg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(_j,n);return o.jsx(lt.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Nj,n);return o.jsx(lt.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Rj,n);return o.jsx(lt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Wg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],ja=Math.min,$r=Math.max,xd=Math.round,Iu=Math.floor,Fr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return $r(e,ja(t,n))}function Ur(e,t){return typeof e=="function"?e(t):e}function Ca(e){return e.split("-")[0]}function Ao(e){return e.split("-")[1]}function Jg(e){return e==="x"?"y":"x"}function ev(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function tv(e){return Jg(rr(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ao(e),i=tv(e),l=ev(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=bd(u)),[u,bd(u)]}function AO(e){const t=bd(e);return[Ip(e),t,Ip(t)]}function Ip(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ao(e);let l=LO(Ca(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Ip)))),l}function bd(e){const t=Ca(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function wd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=tv(t),f=ev(u),h=Ca(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ao(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Ur(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=wd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=wd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ur(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=tv(i),j=ev(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=ja(g[_],U),X=ja(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Q),be=!h.arrow&&Ao(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ur(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ca(n),f=Ao(n),h=rr(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Ur(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ur(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=rr(i),x=Jg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ur(e,t),w={x:i,y:l},x=rr(u),j=Jg(x);let S=w[j],E=w[x];const _=Ur(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ca(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ur(e,t),h=await i.detectOverflow(t,f),m=Ca(n),y=Ao(n),g=rr(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=ja(x-h[j],E),R=ja(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*$r(h.left,h.right):M=x-2*$r(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Yd(){return typeof window<"u"}function Do(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Hr(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Yd()?e instanceof Node||e instanceof Jn(e).Node:!1}function lr(e){return Yd()?e instanceof Element||e instanceof Jn(e).Element:!1}function ka(e){return Yd()?e instanceof HTMLElement||e instanceof Jn(e).HTMLElement:!1}function Fw(e){return!Yd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Jn(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Do(e))}function Xd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ti=e=>!!e&&e!=="none";let Qm;function nv(e){const t=lr(e)?cr(e):e;return ti(t.transform)||ti(t.translate)||ti(t.scale)||ti(t.rotate)||ti(t.perspective)||!sv()&&(ti(t.backdropFilter)||ti(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=fi(e);for(;ka(t)&&!Gl(t);){if(nv(t))return t;if(Xd(t))return null;t=fi(t)}return null}function sv(){return Qm==null&&(Qm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Qm}function Gl(e){return/^(html|body|#document)$/.test(Do(e))}function cr(e){return Jn(e).getComputedStyle(e)}function Wd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fi(e){if(Do(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Hr(e);return Fw(t)?t.host:t}function zj(e){const t=fi(e);return Gl(t)?(e.ownerDocument||e).body:ka(t)&&Qd(t)?t:zj(t)}function Kl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Jn(i);if(l){const f=Pp(u);return t.concat(u,u.visualViewport||[],Qd(i)?i:[],f&&n?Kl(f):[])}else return t.concat(i,Kl(i,[],n))}function Pp(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=ka(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=xd(n)!==l||xd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function rv(e){return lr(e)?e:e.contextElement}function jo(e){const t=rv(e);if(!ka(t))return Fr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?xd(n.width):n.width)/r,f=(l?xd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Fr(0);function $j(e){const t=Jn(e);return!sv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Jn(e)}function hi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=rv(e);let u=Fr(1);t&&(r?lr(r)&&(u=jo(r)):u=jo(e));const f=tA(l,n,r)?$j(l):Fr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Jn(l),x=lr(r)?Jn(r):r;let j=w,S=Pp(j);for(;S&&x!==j;){const E=jo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Jn(S),S=Pp(j)}}return wd({width:y,height:g,x:h,y:m})}function Jd(e,t){const n=Wd(e).scrollLeft;return t?t.left+n:hi(Hr(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Jd(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Hr(r),f=t?Xd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Fr(1);const y=Fr(0),g=ka(r);if((g||!l)&&((Do(r)!=="body"||Qd(u))&&(h=Wd(r)),g)){const x=hi(r);m=jo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Fr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Wd(e),n=e.ownerDocument.body,r=$r(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=$r(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+Jd(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=$r(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Jn(e),l=Hr(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!sv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(Jd(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=hi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=jo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Hr(e));else if(lr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Kl(e,[],!1).filter(f=>lr(f)&&Do(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?fi(e):e;for(;lr(u)&&!Gl(u);){const f=cr(u),h=nv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=fi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Xd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Jn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=rv(e),y=i||l?[...m?Kl(m):[],...t?Kl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?hi(e):null;h&&E();function E(){const _=hi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},rd=CA?b.useLayoutEffect:_A;function Sd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Sd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!Sd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Wm(e){const t=b.useRef(e);return rd(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);Sd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Wm(h),X=Wm(i),Q=Wm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};X.current&&(V.platform=X.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!Sd(H.current,K)&&(H.current=K,rc.flushSync(()=>{g(K)}))})},[w,t,n,X,Q]);rd(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);rd(()=>(le.current=!0,()=>{le.current=!1}),[]),rd(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(lt.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,av="Popper",[Hj,ef]=Na(av),[$A,qj]=Hj(av),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=av;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Zt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&ov(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(lt.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var iv="PopperContent",[FA,IA]=Hj(iv),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(iv,n),[_,N]=b.useState(null),R=Zt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(UA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:Se,availableWidth:ve,availableHeight:Me})=>{const{width:Ye,height:ht}=Se.reference,tt=we.floating.style;tt.setProperty("--radix-popper-available-width",`${ve}px`),tt.setProperty("--radix-popper-available-height",`${Me}px`),tt.setProperty("--radix-popper-anchor-width",`${Ye}px`),tt.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=ov($),D=Pr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(lt.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=iv;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=ov(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function ov(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Jm=!1;function HA(){const[e,t]=b.useState(Jm);return b.useEffect(()=>{Jm||(Jm=!0,t(!0))},[]),e}var tC=Vd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,ep="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},ic="RovingFocusGroup",[Up,nC,ZA]=oj(ic),[YA,sC]=Na(ic,[ZA]),[QA,XA]=YA(ic),rC=b.forwardRef((e,t)=>o.jsx(Up.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Up.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=ic;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Zt(t,w),j=lj(l),[S,E]=ac({prop:u,defaultProp:f??null,onChange:h,caller:ic}),[_,N]=b.useState(!1),R=Pr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(ep,R),()=>H.removeEventListener(ep,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(lt.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(ep,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ds(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Up.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(lt.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Vp=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Vp,"ArrowRight"],rtl:[...Vp,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oc="Menu",[Zl,cD,uD]=oj(oc),[bi,tf]=Na(oc,[uD,ef,sC]),nf=ef(),cC=sC(),[dD,wi]=bi(oc),[fD,lc]=bi(oc),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=nf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Pr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=oc;var hD="MenuAnchor",lv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(Wj,{...i,...r,ref:t})});lv.displayName=hD;var cv="MenuPortal",[mD,dC]=bi(cv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=wi(cv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};fC.displayName=cv;var Ts="MenuContent",[pD,uv]=bi(Ts),hC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=wi(Ts,e.__scopeMenu),u=lc(Ts,e.__scopeMenu);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(dv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu);return o.jsx(dv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=No("MenuContent.ScrollLock"),dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=wi(Ts,n),_=lc(Ts,n),N=nf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Zt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),X=b.useRef(0),Q=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Gg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Q.current?.side&&OD(ee,Q.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:b.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(Bg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Yl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Ts;var xD="MenuGroup",fv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"group",...r,ref:t})});fv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{...r,ref:t})});mC.displayName=bD;var jd="MenuItem",Hw="menu.itemSelect",sf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=lc(jd,e.__scopeMenu),f=uv(jd,e.__scopeMenu),h=Zt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Vp.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});sf.displayName=jd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=uv(jd,n),f=cC(n),h=b.useRef(null),m=Zt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Zl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(lt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Yl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Yl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(sf,{role:"menuitemcheckbox","aria-checked":Cd(n)?"mixed":n,...i,ref:t,"data-state":mv(n),onSelect:Ue(i.onSelect,()=>r?.(Cd(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=bi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Pr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(fv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(sf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":mv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var hv="MenuItemIndicator",[wC,CD]=bi(hv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(hv,n);return o.jsx(dr,{present:r||Cd(l.checked)||l.checked===!0,children:o.jsx(lt.span,{...i,ref:t,"data-state":mv(l.checked)})})});SC.displayName=hv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=bi(ND),$l="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=wi($l,e.__scopeMenu),r=lc($l,e.__scopeMenu),i=_C($l,e.__scopeMenu),l=uv($l,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Zt(t,i.onTriggerChange);return o.jsx(lv,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Yl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Yl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=$l;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=wi(Ts,e.__scopeMenu),f=lc(Ts,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Zt(t,m);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:o.jsx(dv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function Cd(e){return e==="indeterminate"}function mv(e){return Cd(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Yl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=lv,OC=fC,AC=hC,DC=fv,zC=mC,LC=sf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,rf="ContextMenu",[AD]=Na(rf,[tf]),Un=tf(),[DD,BC]=AD(rf),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=ac({prop:i,defaultProp:!1,onChange:r,caller:rf}),y=Un(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=rf;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Un(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(lt.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Pu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Pu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Pu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Pu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Pu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,af="DropdownMenu",[lz]=Na(af,[tf]),Vn=tf(),[cz,e_]=lz(af),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Vn(t),m=b.useRef(null),[y,g]=ac({prop:i,defaultProp:l??!1,onChange:u,caller:af});return o.jsx(cz,{scope:t,triggerId:ds(),triggerRef:m,contentId:ds(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=af;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Vn(n),f=Zt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(lt.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Vn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Vn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(lt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(lt.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[of]=Na("Tooltip",[ef]),lf=ef(),p_="TooltipProvider",Hz=700,Hp="tooltip.open",[qz,pv]=of(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Ql="Tooltip",[Bz,cc]=of(Ql),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=pv(Ql,e.__scopeTooltip),m=lf(t),[y,g]=b.useState(null),w=ds(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=ac({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Hp))):h.onClose(),l?.(L)},caller:Ql}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Ql;var qp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cc(qp,n),l=pv(qp,n),u=lf(n),f=b.useRef(null),h=Zt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(lt.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=qp;var gv="TooltipPortal",[Gz,Kz]=of(gv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=cc(gv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};x_.displayName=gv;var Ro="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(Ro,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=cc(Ro,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=cc(Ro,e.__scopeTooltip),r=pv(Ro,e.__scopeTooltip),i=b.useRef(null),l=Zt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=of(Ql,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=cc(Ro,n),m=lf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Hp,y),()=>document.removeEventListener(Hp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=Ro;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=lf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),_d="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(_d),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(_d):e.slice(t).join(_d),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];vv(i,n,r,t)}return n},vv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){vv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(_d),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},Bp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+Bp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],on=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,va=e=>A4.test(e),Xe=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),tp=e=>e.endsWith("%")&&Xe(e.slice(0,-1)),Ar=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),yv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Re(e)&&!Te(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ra(e,z_,yv),Re=e=>M_.test(e),ni=e=>Ra(e,L_,I4),Zw=e=>Ra(e,W4,Xe),B4=e=>Ra(e,F_,O_),G4=e=>Ra(e,$_,yv),Yw=e=>Ra(e,A_,yv),K4=e=>Ra(e,D_,U4),Uu=e=>Ra(e,I_,P4),Te=e=>T_.test(e),Ol=e=>Si(e,L_),Z4=e=>Si(e,$_),Qw=e=>Si(e,A_),Y4=e=>Si(e,z_),Q4=e=>Si(e,D_),Vu=e=>Si(e,I_,!0),X4=e=>Si(e,F_,!0),Ra=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Si=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=on("color"),t=on("font"),n=on("text"),r=on("font-weight"),i=on("tracking"),l=on("leading"),u=on("breakpoint"),f=on("container"),h=on("spacing"),m=on("radius"),y=on("shadow"),g=on("inset-shadow"),w=on("text-shadow"),x=on("drop-shadow"),j=on("blur"),S=on("perspective"),E=on("aspect"),_=on("ease"),N=on("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Te,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Te,Re,h],U=()=>[va,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Te,Re],X=()=>["auto",{span:["full",Js,Te,Re]},Js,Te,Re],Q=()=>[Js,"auto",Te,Re],ae=()=>["auto","min","max","fr",Te,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[va,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[va,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[va,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Te,Re],O=()=>[...T(),Qw,Yw,{position:[Te,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Te,Re]}],P=()=>[tp,Ol,ni],I=()=>["","none","full",m,Te,Re],re=()=>["",Xe,Ol,ni],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>[Xe,tp,Qw,Yw],ve=()=>["","none",j,Te,Re],Me=()=>["none",Xe,Te,Re],Ye=()=>["none",Xe,Te,Re],ht=()=>[Xe,Te,Re],tt=()=>[va,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ar],breakpoint:[Ar],color:[O_],container:[Ar],"drop-shadow":[Ar],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ar],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ar],shadow:[Ar],spacing:["px",Xe],text:[Ar],"text-shadow":[Ar],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",va,Re,Te,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Te,Re]}],"container-named":[H4],columns:[{columns:[Xe,Re,Te,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Te,Re]}],basis:[{basis:[va,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,va,"auto","initial","none",Re]}],grow:[{grow:["",Xe,Te,Re]}],shrink:[{shrink:["",Xe,Te,Re]}],order:[{order:[Js,"first","last","none",Te,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ol,ni]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tp,Re]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Te,Re]}],"line-clamp":[{"line-clamp":[Xe,"none",Te,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Te,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Te,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Te,ni]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Xe,"auto",Te,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Te,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Te,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Te,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Te,Re],radial:["",Te,Re],conic:[Js,Te,Re]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Te,Re]}],"outline-w":[{outline:["",Xe,Ol,ni]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Vu,Uu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Vu,Uu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Xe,ni]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Vu,Uu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Xe,Te,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Se()}],"mask-image-linear-to-pos":[{"mask-linear-to":Se()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":Se()}],"mask-image-t-to-pos":[{"mask-t-to":Se()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":Se()}],"mask-image-r-to-pos":[{"mask-r-to":Se()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":Se()}],"mask-image-b-to-pos":[{"mask-b-to":Se()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":Se()}],"mask-image-l-to-pos":[{"mask-l-to":Se()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":Se()}],"mask-image-x-to-pos":[{"mask-x-to":Se()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":Se()}],"mask-image-y-to-pos":[{"mask-y-to":Se()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Te,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":Se()}],"mask-image-radial-to-pos":[{"mask-radial-to":Se()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Se()}],"mask-image-conic-to-pos":[{"mask-conic-to":Se()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Te,Re]}],filter:[{filter:["","none",Te,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Xe,Te,Re]}],contrast:[{contrast:[Xe,Te,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Vu,Uu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Xe,Te,Re]}],"hue-rotate":[{"hue-rotate":[Xe,Te,Re]}],invert:[{invert:["",Xe,Te,Re]}],saturate:[{saturate:[Xe,Te,Re]}],sepia:[{sepia:["",Xe,Te,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Te,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Te,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Te,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Te,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Te,Re]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Te,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Te,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Te,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Te,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Te,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Te,Re]}],ease:[{ease:["linear","initial",_,Te,Re]}],delay:[{delay:[Xe,Te,Re]}],animate:[{animate:["none",N,Te,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Te,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Ye()}],"scale-x":[{"scale-x":Ye()}],"scale-y":[{"scale-y":Ye()}],"scale-z":[{"scale-z":Ye()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Te,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:tt()}],"translate-x":[{"translate-x":tt()}],"translate-y":[{"translate-y":tt()}],"translate-z":[{"translate-z":tt()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Te,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Te,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Te,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Xe,Ol,ni,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function at(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function cf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function uf({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function df({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:at("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Gp=new Set;function n3(e){return Gp.add(e),()=>Gp.delete(e)}function Co(e){for(const t of Gp)t(e)}const ii=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Dr=/\.html?$/i,ad=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Xl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function mi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Mn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Kp="(min-width: 1400px)";function ff(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function xv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var np={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...np,width:t??m??np.width,height:t??m??np.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],bv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],wv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=Sv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),pi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}pi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function fs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),pi(),e&&window.innerWidth<=Sv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const Sv=900;function pi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=Sv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Zp="bdrive.sidebarWidth",aE=210,iE=480;function id(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function sp(e){try{e===null?localStorage.removeItem(Zp):localStorage.setItem(Zp,String(e))}catch{}}const Yp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Yp(m.clientX-l),id(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&sp(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{id(null),sp(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Yp(u+l);id(f),sp(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Zp));e&&id(Yp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",pi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){fs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:bv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:wv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Qp={folder:bv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:wv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ci({name:e,className:t}){const n=e??"",r=Object.hasOwn(Qp,n)?Qp[n]:bv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function jv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function bo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&pi()}function oi(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:fs}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(Cv,{id:"rail-search",icon:"search",label:"Search",hint:Xl?"⌘K":"Ctrl+K",onClick:()=>Co()}),t]})}function Cv(e){return o.jsxs(cf,{delayDuration:100,children:[o.jsx(uf,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(df,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function hf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(jv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function li(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Xl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Xp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Xp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Xp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Wn=new xL,bL=(e,t)=>{const n=t?.id||Xp++;return Wn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Wn.toasts,CL=()=>Wn.getActiveToasts(),Ww=Object.assign(SL,{success:Wn.success,info:Wn.info,warning:Wn.warning,error:Wn.error,custom:Wn.custom,message:Wn.message,promise:Wn.promise,dismiss:Wn.dismiss,loading:Wn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Hu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function er(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[Se,ve]=ye.useState(!1),[Me,Ye]=ye.useState(!1),[ht,tt]=ye.useState(0),[es,Fe]=ye.useState(0),ot=ye.useRef(g.duration||Q||Jw),mn=ye.useRef(null),Nt=ye.useRef(null),un=_===0,jt=_+1<=S,Lt=g.type,ts=g.dismissible!==!1,At=g.className||"",nn=g.descriptionClassName||"",ns=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),hr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hs=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),ms=ye.useRef(0),Tn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,dt,Et)=>Et>=ns?Le:Le+dt.height,0),[E,ns]),xe=yL(),je=g.invert||y,_e=Lt==="loading";Tn.current=ye.useMemo(()=>ns*le+me,[ns,me]),ye.useEffect(()=>{ot.current=Hs},[Hs]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=Nt.current;if(Le){const dt=Le.getBoundingClientRect().height;return Fe(dt),j(Et=>[{toastId:g.id,height:dt,position:g.position},...Et]),()=>j(Et=>Et.filter($t=>$t.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=Nt.current,dt=Le.style.height;Le.style.height="auto";const Et=Le.getBoundingClientRect().height;Le.style.height=dt,Fe(Et),j($t=>$t.find(vt=>vt.toastId===g.id)?$t.map(vt=>vt.toastId===g.id?{...vt,height:Et}:vt):[{toastId:g.id,height:Et,position:g.position},...$t])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ae=ye.useCallback(()=>{re(!0),tt(Tn.current),j(Le=>Le.filter(dt=>dt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Tn]);ye.useEffect(()=>{if(g.promise&&Lt==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ae()},ot.current)),()=>clearTimeout(Le)},[R,x,g,Lt,xe,Ae]),ye.useEffect(()=>{g.delete&&(Ae(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ae,g.delete]);function Ke(){var Le;if(q?.loading){var dt;return ye.createElement("div",{className:er($?.loader,g==null||(dt=g.classNames)==null?void 0:dt.loader,"sonner-loader"),"data-visible":Lt==="loading"},q.loading)}return ye.createElement(fL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Lt==="loading"})}const Ct=g.icon||q?.[Lt]||uL(Lt);var sn,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:er(Z,At,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Lt],g==null||(n=g.classNames)==null?void 0:n[Lt]),"data-sonner-toast":"","data-rich-colors":(sn=g.richColors)!=null?sn:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Me,"data-removed":I,"data-visible":jt,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":un,"data-swiping":he,"data-dismissible":ts,"data-type":Lt,"data-invert":je,"data-swipe-out":Se,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Tn.current}px`,"--initial-height":be?"auto":`${es}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ts||(mn.current=new Date,tt(Tn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,dt,Et;if(Se||!ts)return;Y.current=null;const $t=Number(((Le=Nt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Hn=Number(((dt=Nt.current)==null?void 0:dt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vt=new Date().getTime()-((Et=mn.current)==null?void 0:Et.getTime()),dn=ee==="x"?$t:Hn,mr=Math.abs(dn)/vt;if(Math.abs(dn)>=ML||mr>.11){tt(Tn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?$t>0?"right":"left":Hn>0?"down":"up"),Ae(),ve(!0);return}else{var Cn,rn;(Cn=Nt.current)==null||Cn.style.setProperty("--swipe-amount-x","0px"),(rn=Nt.current)==null||rn.style.setProperty("--swipe-amount-y","0px")}Ye(!1),we(!1),K(null)},onPointerMove:Le=>{var dt,Et,$t;if(!Y.current||!ts||((dt=window.getSelection())==null?void 0:dt.toString().length)>0)return;const vt=Le.clientY-Y.current.y,dn=Le.clientX-Y.current.x;var mr;const Cn=(mr=e.swipeDirections)!=null?mr:OL(ae);!ee&&(Math.abs(dn)>1||Math.abs(vt)>1)&&K(Math.abs(dn)>Math.abs(vt)?"x":"y");let rn={x:0,y:0};const qr=qn=>1/(1.5+Math.abs(qn)/20);if(ee==="y"){if(Cn.includes("top")||Cn.includes("bottom"))if(Cn.includes("top")&&vt<0||Cn.includes("bottom")&&vt>0)rn.y=vt;else{const qn=vt*qr(vt);rn.y=Math.abs(qn)0)rn.x=dn;else{const qn=dn*qr(dn);rn.x=Math.abs(qn)0||Math.abs(rn.y)>0)&&Ye(!0),(Et=Nt.current)==null||Et.style.setProperty("--swipe-amount-x",`${rn.x}px`),($t=Nt.current)==null||$t.style.setProperty("--swipe-amount-y",`${rn.y}px`)}},hr&&!g.jsx&&Lt!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ts?()=>{}:()=>{Ae(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Lt||g.icon||g.promise)&&g.icon!==null&&(q?.[Lt]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||Ke():null,g.type!=="loading"?Ct:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,nn,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&Hu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{Hu(g.cancel)&&ts&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ae())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&Hu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{Hu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ae())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Wn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Wn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,Se)=>{var ve,Me;return ye.createElement(AL,{key:we.id,icons:T,index:Se,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Me=_?.closeButton)!=null?Me:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ye=>Ye.position==we.position),heights:Z.filter(Ye=>Ye.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Ed="bdrive-theme",Wp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function _v(){try{const e=localStorage.getItem(Ed);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function od(){const e=LL(_v()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Wp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Ed):localStorage.setItem(Ed,e)}catch{}od()}let t1=!1;function IL(){if(!t1){t1=!0,od();try{window.matchMedia(lE).addEventListener("change",()=>{_v()==="system"&&od()})}catch{}window.addEventListener("storage",e=>{(e.key===Ed||e.key===null)&&od()})}}function PL(e){return window.addEventListener(Wp,e),()=>window.removeEventListener(Wp,e)}function n1(){return`${_v()}:${$L()}`}function Ev(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=Ev();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:at(qL({variant:t,size:n,className:e})),...i})}function uc({...e}){return o.jsx(Kg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Yg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Qg,{"data-slot":"dialog-overlay",className:at("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function dc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Xg,{"data-slot":"dialog-content",className:at("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zo({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:at("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:at("text-sm text-muted-foreground",e),...t})}let uE=null,ld=[];function fc(e){uE=e,ld.forEach(t=>t())}function Wl(e,t,n="",r="OK",i={}){return new Promise(l=>fc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>fc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(ld.push(n),()=>{ld=ld.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{fc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(uc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(dc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{fc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{fc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let Nd=null,cd=[];const Nv=e=>{Nd=e,cd.forEach(t=>t())};function VB(e,t){Nv({...t,path:e,from:t})}function HB(e){Nd?.from===e&&Nv(null)}function XL(){const e=b.useSyncExternalStore(f=>(cd.push(f),()=>{cd=cd.filter(h=>h!==f)}),()=>Nd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),Nd===e&&Nv(null)}},u=()=>{l(e.keep)};return o.jsx(uc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(dc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:mi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":mi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>We("/api/projects")};function WL(e){return rt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=hn();return()=>e.fetchQuery(dE)}function fE(e){return rt({queryKey:["orgs"],queryFn:()=>We("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function kv(e){return rt({queryKey:["permissions",e],queryFn:()=>We(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return rt({queryKey:["folders",e],queryFn:()=>We(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return rt({queryKey:["shares",e],queryFn:()=>We(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return rt({queryKey:["admin","pending"],queryFn:()=>We("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=hn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function mf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Jp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Jp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Jp,e)?Jp[e]:void 0}const Rv=["q","user","actor","device","range","since","until"];function Mv(e){return!!e&&Rv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of Rv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Tv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of Rv){const y=r?.get(m);y&&(h[m]=y)}if(Mv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=mf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?mf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function $n(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function ln(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=mf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Ov="POP";const eg=new Set;function xE(){for(const e of eg)e()}window.addEventListener("popstate",()=>{Ov="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Ov=t?.replace?"REPLACE":"PUSH",xE())}function Av(){return b.useSyncExternalStore(e=>(eg.add(e),()=>{eg.delete(e)}),()=>location.pathname+location.search)}function c$(){return Ov}function Pn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function si({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function ba(e,t){return typeof e=="function"?e(t):e}function hs(e,t){return n=>{t.setState(r=>({...r,[e]:ba(n,r[e])}))}}function pf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Tn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return Bu(t,[...f,...m,...h],e)},He(e.options,Tn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),Bu(t,n,e,"center")),He(e.options,Tn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"left")},He(e.options,Tn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return Bu(t,l,e,"right")},He(e.options,Tn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Tn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Tn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Tn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Tn))}};function Bu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Us(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Us(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Us(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Us(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Us(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Us(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Us(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Us(e);const Av=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Av.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Av.autoRemove=e=>Us(e)||Us(e[0])&&Us(e[1]);const $r={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Av};function Us(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:fs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?$r.includesString:typeof r=="number"?$r.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?$r.equals:Array.isArray(r)?$r.arrIncludes:$r.weakEquals},e.getFilterFn=()=>{var n,r;return gf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:$r[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=Sa(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=Sa(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,sp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:fs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return sp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return sp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:sp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:fs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Fl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Fl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Fl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},rp=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:rp(),...e}),getDefaultOptions:e=>({onColumnPinningChange:fs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?rp():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:rp())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Gu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ap=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Gu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ap(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:fs("columnSizing",e),onColumnSizingInfoChange:fs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gu.minSize,(r=l??e.columnDef.size)!=null?r:Gu.size),(i=e.columnDef.maxSize)!=null?i:Gu.maxSize)},e.getStart=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Fl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),ip(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=ip(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,W]=U;m[Z]=Math.round(Math.max(W+W*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;ip(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ap():(n=e.initialState.columnSizingInfo)!=null?n:ap())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Ku=null;function A$(){if(typeof Ku=="boolean")return Ku;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ku=e,Ku}function ip(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:fs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Fl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:fs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>$r.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return gf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:$r[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:fs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},eg=0,tg=10,op=()=>({pageIndex:eg,pageSize:tg}),F$={getInitialState:e=>({...e,pagination:{...op(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:fs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>Sa(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?op():(i=e.initialState.pagination)!=null?i:op())},e.setPageIndex=r=>{e.setPagination(i=>{let l=Sa(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?eg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:eg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:tg)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,Sa(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=Sa(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},lp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:lp(),...e}),getDefaultOptions:e=>({onRowPinningChange:fs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?lp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:lp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:fs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{ng(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?cp(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return ng(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Dv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return sg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},ng=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>ng(e,f.id,n,r,i))};function cp(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=Dv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function Dv(e,t){var n;return(n=t[e.id])!=null?n:!1}function sg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(Dv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=sg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const rg=/([0-9]+)/gm,U$=(e,t,n)=>RE(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(Na(e.getValue(n)),Na(t.getValue(n))),H$=(e,t,n)=>zv(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>zv(Na(e.getValue(n)),Na(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rzv(e.getValue(n),t.getValue(n));function zv(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(rg).filter(Boolean),r=t.split(rg).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Tl={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:fs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Tl.datetime;if(typeof l=="string"&&(r=!0,l.split(rg).length>1))return Tl.alphanumeric}return r?Tl.text:Tl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return gf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Tl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=Sa(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ag(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var dc=e=>e.type==="checkbox",ja=e=>e instanceof Date,bn=e=>e==null;const Lv=e=>typeof e=="object";var Pt=e=>!bn(e)&&!Array.isArray(e)&&Lv(e)&&!ja(e),J$=e=>Pt(e)&&e.target?dc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Pt(t)&&t.hasOwnProperty("isPrototypeOf")},vf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(vf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Pt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Bt(e[i]));return r}const co={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Is={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Fs={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",$v=["__proto__","constructor","prototype"],t8=/^\w*$/;var fc=e=>t8.test(e),Tt=e=>e===void 0;const n8=/[.[\]'"]/;var yf=e=>e.split(n8).filter(Boolean),Re=(e,t,n)=>{if(!t||!Pt(e))return n;const r=fc(t)?[t]:yf(t);if(r.some(l=>$v.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Tt(i)||i===e?Tt(e[t])?n:e[t]:i},nr=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ct=(e,t,n)=>{let r=-1;const i=fc(t)?[t]:yf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==Is.all&&(t._proxyFormState[u]=!r||Is.all),e[u]}});return i};const a8=vf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),Re(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),Re(n,l))):(r&&(t.watchAll=!0),n),ig=e=>bn(e)||!Lv(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function sr(e,t,n=new WeakMap){if(e===t)return!0;if(ig(e)||ig(t))return Object.is(e,t);if(ja(e)&&ja(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(ja(f)&&ja(h)||(Pt(f)||Array.isArray(f))&&(Pt(h)||Array.isArray(h))?!sr(f,h,n):!Object.is(f,h))return!1}}return!0}var Zu=e=>({isOnSubmit:!e||e===Is.onSubmit,isOnBlur:e===Is.onBlur,isOnChange:e===Is.onChange,isOnAll:e===Is.all,isOnTouch:e===Is.onTouched}),up=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Il=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=Re(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Il(f,t))break}else if(Pt(f)&&Il(f,t))break}}};var f1=(e,t,n)=>{const r=Re(e,n),i=Array.isArray(r)?r:[];return Ct(i,DE,t[n]),Ct(e,n,i),e},xn=e=>Pt(e)&&!Object.keys(e).length,Fv=e=>e.type==="file",Rd=e=>{if(!vf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Iv=e=>e.type==="radio",Md=e=>e instanceof RegExp,Pv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Tt(e[0].attributes.value)?Tt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||nr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var uo=e=>Pt(e)&&!Md(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=Re(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Y=>{if(i&&R.reportValidity){const ae=nr(Y)?"":Y||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Iv(u),L=dc(u),H=M||L,U=(E||Fv(u))&&Tt(u.value)&&Tt(N)||Rd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Pv.bind(null,S,r,A),W=(Y,ae,le,be=Fs.maxLength,$=Fs.minLength)=>{const q=Y?ae:le;A[S]={type:Y?be:$,message:q,ref:u,...Z(Y?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||nr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Y,message:ae}=wn(h)?{value:!!h,message:h}:uo(h);if(Y&&(A[S]={type:Fs.required,message:ae,ref:R,...Z(Fs.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Y,ae;const le=uo(w),be=uo(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Y=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Y=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Y.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(W(le,Y.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Y,message:ae}=uo(x);if(Md(Y)&&!N.match(Y)&&(A[S]={type:Fs.pattern,message:ae,ref:u,...Z(Fs.pattern,ae)},!r))return T(ae),A}if(j){if(_s(j)){const Y=await j(N,n),ae=g1(Y,R);if(ae&&(A[S]={...ae,...Z(Fs.validate,ae.message)},!r))return T(ae.message),A}else if(Pt(j)){let Y={};for(const ae in j){if(!xn(Y)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Y={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Y))}if(!xn(Y)&&(A[S]={ref:R,...Y},!r))return A}}return T(!0),A},dd=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;r$v.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Pt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Gt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if(Lv(e[n])&&e[n]!==null&&!ja(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Pt(i)&&l){const u=IE(i,l);Pt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Iv(e)||dc(e),dp=e=>Rd(e)&&e.isConnected,d8=e=>{for(const t in e)if(_s(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Pt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Tt(t)):!Object.keys(e).length}function og(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function lg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},lg(i,t[r],l),HE(t[r])&&og(t,r)):Tt(i)||(t[r]=!0)}return t}function ai(e,t,n,r){n||(n=lg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Tt(t)||ig(n[i])?n[i]=lg(l,Array.isArray(l)?[]:{},u):ai(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&og(n,i)):sr(l,t[i])?og(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Tt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Fv(t)?t.files:Iv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):dc(t)?zE(e.refs).value:qE(Tt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=Re(t,l);u&&Ct(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Ol=e=>Tt(e)?e:Md(e)?e.source:Pt(e)?Md(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(_s(e.validate))return e.validate.constructor.name===b1;if(Pt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=Re(e,n);if(r||fc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=Re(t,l),f=Re(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||Is.all))},g8=(e,t,n)=>!e||!t||e===t||dd(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(Re(e,t)).length&&Gt(e,t);const x8={mode:Is.onSubmit,reValidateMode:Is.onChange,shouldFocusError:!0},fp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Bt(BE),isLoading:_s(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Pt(t.defaultValues)||Pt(t.values)?Bt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Bt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Zu(t.mode),w=Zu(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===Is.all,R=(z,Q)=>X=>{clearTimeout(m[z]),m[z]=setTimeout(Q,X)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Q=++_;let X;t.resolver?(X=xn((await le()).errors),Q===_&&A()):X=await q({fields:r,onlyCheckValid:!0,eventType:co.VALID}),Q===_&&X!==n.isValid&&E.state.next({isValid:X})}},A=(z,Q)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(X=>{X&&(Q?Ct(n.validatingFields,X,Q):Gt(n.validatingFields,X))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ai(i,l,void 0,r)},L=(z,Q=[],X,fe,me=!0,xe=!0)=>{if(fe&&X&&!t.disabled){if(u.action=!0,xe&&Array.isArray(Re(r,z))){const Se=X(Re(r,z),fe.argA,fe.argB);me&&Ct(r,z,Se)}if(xe&&Array.isArray(Re(n.errors,z))){const Se=X(Re(n.errors,z),fe.argA,fe.argB);me&&Ct(n.errors,z,Se),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(Re(n.touchedFields,z))){const Se=X(Re(n.touchedFields,z),fe.argA,fe.argB);me&&Ct(n.touchedFields,z,Se)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ct(l,z,Q)},H=(z,Q)=>{Ct(n.errors,z,Q),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Q=fc(z)?[z]:yf(z);let X=l,fe=i;for(let me=0;me{const me=Re(r,z);if(me){if(Z(z))return;const xe=Tt(Re(l,z)),Se=Re(l,z,Tt(X)?Re(i,z):X);Tt(Se)||fe&&fe.defaultChecked||Q?Ct(l,z,Q?Se:x1(me._f)):D(z,Se),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Tt(Re(l,z))&&up(z,f)&&(u.watch=!0))}},Y=(z,Q,X,fe,me)=>{let xe=!1,Se=!1;const _e={name:z};if(!t.disabled||fe===!0){if(!X||fe){const Ee=sr(Re(i,z),Q);(j.isDirty||S.isDirty)&&(Se=n.isDirty,n.isDirty=_e.isDirty=!Ee||ee(),xe=Se!==_e.isDirty),Se=!!Re(n.dirtyFields,z),Ee!==n.isDirty?n.dirtyFields=ai(i,l,void 0,r):Ee?Gt(n.dirtyFields,z):Ct(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&Se!==!Ee}if(X){const Ee=Re(n.touchedFields,z);Ee||(Ct(n.touchedFields,z,X),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ee!==X)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Q,X,fe)=>{const me=Re(n.errors,z),xe=(j.isValid||S.isValid)&&nr(Q)&&n.isValid!==Q;if(t.delayError&&X?(h[z]=R(z,()=>H(z,X)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],X?Ct(n.errors,z,X):Gt(n.errors,z),n.errors={...n.errors}),(X?!sr(me,X):me)||!xn(fe)||xe){const Se={...fe,...xe&&nr(Q)?{isValid:Q}:{},errors:n.errors,name:z};n={...n,...Se},E.state.next(Se)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Q}=await le(z);if(A(z),z){for(const X of z){const fe=Re(Q,X);fe?f.array.has(X)&&Pt(fe)&&!Object.keys(fe).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[X]:fe},X):Ct(n.errors,X,fe):Gt(n.errors,X)}n.errors={...n.errors}}else n.errors=Q;return Q},$=async({name:z,eventType:Q})=>{if(e.validate){const X=await e.validate({formValues:l,formState:n,name:z,eventType:Q});if(Pt(X))for(const fe in X){const me=X[fe];me&&mt(`${fp}.${fe}`,{message:wn(me.message)?me.message:"",type:me.type||Fs.validate})}else wn(X)||!X?mt(fp,{message:X||"",type:Fs.validate}):Ze(fp);return X}return!0},q=async({fields:z,onlyCheckValid:Q,name:X,eventType:fe,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:X,eventType:fe})&&(me.valid=!1,Q)))return me.valid;for(const xe in z){const Se=z[xe];if(Se){const{_f:_e,...Ee}=Se;if(_e){const rt=f.array.has(_e.name),kt=Se._f&&h8(Se._f),Zt=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;kt&&Zt&&A([_e.name],!0);const Dt=await v1(Se,f.disabled,l,N,t.shouldUseNativeValidation&&!Q,rt);if(kt&&Zt&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Q)||(!Q&&(Re(Dt,_e.name)?rt?f1(n.errors,Dt,_e.name):Ct(n.errors,_e.name,Dt[_e.name]):Gt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ee)&&await q({context:me,onlyCheckValid:Q,fields:Ee,name:xe,eventType:fe})}}return me.valid},V=()=>{for(const z of f.unMount){const Q=Re(r,z);Q&&(Q._f.refs?Q._f.refs.every(X=>!dp(X)):!dp(Q._f.ref))&&it(z)}f.unMount=new Set},ee=(z,Q)=>(z&&Q&&Ct(l,z,Q),!sr(u.mount?l:i,i)),K=(z,Q,X)=>i8(z,f,{...u.mount?l:Tt(Q)?i:wn(z)?{[z]:Q}:Q},X,Q),O=z=>$E(Re(u.mount?l:i,z,t.shouldUnregister?Re(i,z,[]):[])),D=(z,Q,X={},fe=!1,me=!1)=>{const xe=Re(r,z);let Se=Q;if(xe){const _e=xe._f;_e&&(!_e.disabled&&Ct(l,z,qE(Q,_e)),Se=Rd(_e.ref)&&bn(Q)?"":Q,PE(_e.ref)?[..._e.ref.options].forEach(Ee=>Ee.selected=Se.includes(Ee.value)):_e.refs?dc(_e.ref)?_e.refs.forEach(Ee=>{(!Ee.defaultChecked||!Ee.disabled)&&(Array.isArray(Se)?Ee.checked=!!Se.find(rt=>rt===Ee.value):Ee.checked=Se===Ee.value||!!Se)}):_e.refs.forEach(Ee=>Ee.checked=Ee.value===Se):Fv(_e.ref)?_e.ref.value="":(_e.ref.value=Se,!_e.ref.type&&!me&&E.state.next({name:z,values:fe?l:Bt(l)})))}(X.shouldDirty||X.shouldTouch)&&Y(z,Se,X.shouldTouch,X.shouldDirty,!me),X.shouldValidate&&je(z,{delayError:X.delayError})},B=(z,Q,X,fe=!1,me=!1)=>{for(const xe in Q){if(!Q.hasOwnProperty(xe))return;const Se=Q[xe],_e=z+"."+xe,Ee=Re(r,_e);(f.array.has(z)||Pt(Se)||Ee&&!Ee._f)&&!ja(Se)?B(_e,Se,X,fe,me):D(_e,Se,X,fe,me)}},P=(z,Q,X,fe,me=!1)=>{const xe=Re(r,z),Se=f.array.has(z),_e=fe?Q:Bt(Q),Ee=Re(l,z),rt=sr(Ee,_e);if(rt||Ct(l,z,_e),Se)E.array.next({name:z,values:fe?l:Bt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&X.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const kt=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||kt?D(z,_e,X,fe,me):B(z,_e,X,fe,me)}if(!rt&&!me){const kt=up(z,f),Zt=fe?l:Bt(l);E.state.next({...kt&&n,name:u.mount||kt?z:void 0,values:Zt})}},I=(z,Q,X={})=>P(z,Q,X,!1),re=(z,Q={})=>{const X=_s(z)?z(l):z;if(!sr(l,X)){l={...l,...X};const fe=FE(X);for(const me of f.mount)me in fe&&P(me,fe[me],Q,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Q.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Q=z.target;let X=Q.name,fe=!0;const me=Re(r,X),xe=Se=>{fe=Number.isNaN(Se)||ja(Se)&&isNaN(Se.getTime())||sr(Se,Re(l,X,Se))};if(me){let Se,_e;const Ee=Q.type?x1(me._f):J$(z),rt=z.type===co.BLUR||z.type===co.FOCUS_OUT,kt=!m8(me._f)&&!e.validate&&!t.resolver&&!Re(n.errors,X)&&!me._f.deps,Zt=kt||v8(rt,Re(n.touchedFields,X),n.isSubmitted,w,g),Dt=up(X,f,rt);if(Ct(l,X,Ee),rt){if(!Q||!Q.readOnly){me._f.onBlur&&me._f.onBlur(z);const bt=h[X];bt&&bt(0)}}else me._f.onChange&&me._f.onChange(z);const ze=Y(X,Ee,rt),xt=!xn(ze)||Dt;if(!rt&&E.state.next({name:X,type:z.type,...y?{values:Bt(l)}:{}}),Zt)return(!kt||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?rt&&T():rt||T()),xt&&E.state.next({name:X,...Dt?{}:ze});if(!t.resolver&&e.validate&&await $({name:X,eventType:z.type}),!rt&&Dt&&E.state.next({...n}),t.resolver){const{errors:bt}=await le([X]);if(A([X]),xe(Ee),!fe){!xn(ze)&&E.state.next(ze);return}const Vt=w1(n.errors,r,X),_n=w1(bt,r,Vt.name||X);Se=_n.error,X=_n.name,_e=xn(bt)}else A([X],!0),Se=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[X],A([X]),xe(Ee),fe&&(Se?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:X,eventType:z.type})));fe&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&je(me._f.deps),ae(X,_e,Se,ze))}},we=(z,Q)=>{if(Re(n.errors,Q)&&z.focus)return z.focus(),1},je=async(z,Q={})=>{let X,fe;const me=dd(z);if(t.resolver){const xe=await be(Tt(z)?z:me);X=xn(xe),fe=z?!me.some(Se=>Re(xe,Se)):X}else z?(fe=(await Promise.all(me.map(async xe=>{const Se=Re(r,xe);return await q({fields:Se&&Se._f?{[xe]:Se}:Se,eventType:co.TRIGGER})}))).every(Boolean),!(!fe&&!n.isValid)&&T()):fe=X=await q({fields:r,name:z,eventType:co.TRIGGER});if(Q.delayError&&t.delayError&&wn(z)){const xe=Re(n.errors,z);xe?(Gt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&X!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:X}:{},errors:n.errors}),Q.shouldFocus&&!fe&&Il(r,we,z?me:f.mount),fe},ve=(z,Q)=>{let X={...u.mount?l:i};return Q&&(X=IE(Q.dirtyFields?n.dirtyFields:n.touchedFields,X)),Tt(z)?X:wn(z)?Re(X,z):z.map(fe=>Re(X,fe))},Te=(z,Q)=>({invalid:!!Re((Q||n).errors,z),isDirty:!!Re((Q||n).dirtyFields,z),error:Re((Q||n).errors,z),isValidating:!!Re(n.validatingFields,z),isTouched:!!Re((Q||n).touchedFields,z)}),Ze=z=>{const Q=z?dd(z):void 0;Q?.forEach(X=>Gt(n.errors,X)),Q?Q.forEach(X=>{E.state.next({name:X,errors:n.errors})}):E.state.next({errors:{}})},mt=(z,Q,X)=>{const fe=(Re(r,z,{_f:{}})._f||{}).ref,me=Re(n.errors,z)||{},{ref:xe,message:Se,type:_e,...Ee}=me;Ct(n.errors,z,{...Ee,...Q,ref:fe}),E.state.next({name:z,errors:n.errors,isValid:!1}),X&&X.shouldFocus&&fe&&fe.focus&&fe.focus()},Je=(z,Q)=>{if(_s(z)){y++;const{unsubscribe:X}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Q),me)});let fe=!1;return{unsubscribe:()=>{fe||(fe=!0,y--,X())}}}return K(z,Q,!0)},Wn=z=>{var Q;const X=!!(!((Q=z.formState)===null||Q===void 0)&&Q.values);X&&y++;const{unsubscribe:fe}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,Gr,z.reRenderRoot)){const Se={...l};z.callback({values:Se,...n,...xe,defaultValues:i})}}});if(!X)return fe;let me=!1;return()=>{me||(me=!0,y--,fe())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},Wn({...z,formState:{...x,...z.formState}})),it=(z,Q={})=>{for(const X of z?dd(z):f.mount)f.mount.delete(X),f.array.delete(X),Q.keepValue||(Gt(r,X),Gt(l,X)),!Q.keepError&&Gt(n.errors,X),!Q.keepDirty&&Gt(n.dirtyFields,X),!Q.keepTouched&&Gt(n.touchedFields,X),!Q.keepIsValidating&&Gt(n.validatingFields,X),!t.shouldUnregister&&!Q.keepDefaultValue&&Gt(i,X);E.state.next({values:Bt(l)}),E.state.next({...n,...Q.keepDirty?{isDirty:ee()}:{}}),!Q.keepIsValid&&T()},nn=({disabled:z,name:Q})=>{if(nr(z)&&u.mount||z||f.disabled.has(Q)){const me=f.disabled.has(Q)!==!!z;z?f.disabled.add(Q):f.disabled.delete(Q),me&&u.mount&&!u.action&&T()}},yt=(z,Q={})=>{let X=Re(r,z);const fe=nr(Q.disabled)||nr(t.disabled),me=!f.registerName.has(z)&&X&&X._f&&!X._f.mount;return Ct(r,z,{...X||{},_f:{...X&&X._f?X._f:{ref:{name:z}},name:z,mount:!0,...Q}}),f.mount.add(z),X&&!me?nn({disabled:nr(Q.disabled)?Q.disabled:t.disabled,name:z}):W(z,!0,Q.value),{...fe?{disabled:Q.disabled||t.disabled}:{},...t.progressive?{required:!!Q.required,min:Ol(Q.min),max:Ol(Q.max),minLength:Ol(Q.minLength),maxLength:Ol(Q.maxLength),pattern:Ol(Q.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),yt(z,Q),f.registerName.delete(z),X=Re(r,z);const Se=Tt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(Se),Ee=X._f.refs||[];if(_e?Ee.find(rt=>rt===Se):Se===X._f.ref)return;Ct(r,z,{_f:{...X._f,..._e?{refs:[...Ee.filter(dp),Se,...Array.isArray(Re(i,z))?[{}]:[]],ref:{type:Se.type,name:z}}:{ref:Se}}}),W(z,!1,void 0,Se)}else X=Re(r,z,{}),X._f&&(X._f.mount=!1),(t.shouldUnregister||Q.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},ht=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Il(r,we,f.mount),sn=z=>{nr(z)&&(E.state.next({disabled:z}),Il(r,(Q,X)=>{const fe=Re(r,X);fe&&(Q.disabled=fe._f.disabled||z,Array.isArray(fe._f.refs)&&fe._f.refs.forEach(me=>{me.disabled=fe._f.disabled||z}))},0,!1))},Ut=(z,Q)=>async X=>{let fe;X&&(X.preventDefault&&X.preventDefault(),X.persist&&X.persist());let me=Bt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:Se}=await le();A(),n.errors=xe,me=Bt(Se)}else await q({fields:r,eventType:co.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Gt(me,xe);if(Gt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,X)}catch(xe){fe=xe}}else Q&&await Q({...n.errors},X),ht(),setTimeout(ht);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!fe,submitCount:n.submitCount+1,errors:n.errors}),fe)throw fe},An=(z,Q={})=>{Re(r,z)&&(Tt(Q.defaultValue)?I(z,Bt(Re(i,z))):(I(z,Q.defaultValue),Ct(i,z,Bt(Q.defaultValue))),Q.keepTouched||Gt(n.touchedFields,z),Q.keepDirty||(Gt(n.dirtyFields,z),n.isDirty=Q.defaultValue?ee(z,Bt(Re(i,z))):ee()),Q.keepError||(Gt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},dt=(z,Q={})=>{const X=z?Bt(z):i,fe=Bt(X),me=xn(z),xe=fe,Se=r;if(Q.keepDefaultValues||(i=X),!Q.keepValues){if(Q.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ai(i,l,void 0,Se))]);for(const Ee of Array.from(_e)){const rt=Re(n.dirtyFields,Ee),kt=Re(l,Ee),Zt=Re(xe,Ee);rt&&!Tt(kt)?Ct(xe,Ee,kt):!rt&&!Tt(Zt)&&I(Ee,Zt)}}else{if(vf&&Tt(z))for(const _e of f.mount){const Ee=Re(r,_e);if(Ee&&Ee._f){const rt=Array.isArray(Ee._f.refs)?Ee._f.refs[0]:Ee._f.ref;if(Rd(rt)){const kt=rt.closest("form");if(kt){kt.reset();break}}}}if(Q.keepFieldsRef)for(const _e of f.mount)I(_e,Re(xe,_e));else r={}}if(t.shouldUnregister){if(l=Q.keepDefaultValues?Bt(i):{},Q.keepFieldsRef)for(const _e of f.mount)Ct(l,_e,Re(xe,_e))}else l=Bt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Q.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Q.keepIsValid||!!Q.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Q.keepIsValid,u.action=!1,Q.keepErrors||(n.errors={}),E.state.next({submitCount:Q.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Q.keepDirty?n.isDirty:Q.keepValues?ee():!!(Q.keepDefaultValues&&!sr(z,i)),isSubmitted:Q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Q.keepDirtyValues?Q.keepDefaultValues&&l?ai(i,l,void 0,Se):n.dirtyFields:Q.keepDefaultValues&&z?ai(i,z,void 0,Se):Q.keepDirty?n.dirtyFields:{},touchedFields:Q.keepTouched?n.touchedFields:{},errors:Q.keepErrors?n.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},Bs=(z,Q)=>dt(_s(z)?z(l):z,{...t.resetOptions,...Q}),hs=(z,Q={})=>{const X=Re(r,z),fe=X&&X._f;if(fe){const me=fe.refs?fe.refs[0]:fe.ref;me.focus&&setTimeout(()=>{me.focus(),Q.shouldSelect&&_s(me.select)&&me.select()})}},Gr=z=>{const{name:Q,type:X,values:fe,...me}=z;n={...n,...me}},Cn={control:{register:yt,unregister:it,getFieldState:Te,handleSubmit:Ut,setError:mt,_subscribe:Wn,_runSchema:le,_updateIsValidating:A,_focusError:ht,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:nn,_setErrors:U,_getFieldArray:O,_reset:dt,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(z=>{Bs(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:sn,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Zu(t.mode),w=Zu(t.reValidateMode)}},subscribe:Fe,trigger:je,register:yt,handleSubmit:Ut,watch:Je,setValue:I,setValues:re,getValues:ve,reset:Bs,resetField:An,resetDefaultValues:(z,Q={})=>{if(i=Bt(z),!Q.keepDirty){const X=ai(i,l,void 0,r);n.dirtyFields=X,n.isDirty=!xn(X)}Q.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ze,unregister:it,setError:mt,setFocus:hs,getFieldState:Te};return{...Cn,formControl:Cn}}function Uv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Bt(BE),isLoading:_s(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!sr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=Re(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},cg=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&cg(e,t);const n={};for(const r in e){const i=Re(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},Re(n,r));Ct(u,"root",l),Ct(n,r,u)}else Ct(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class wo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Vv=globalThis.__zod_globalConfig;function vi(e){return Vv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function ug(e,t){return typeof t=="bigint"?t.toString():t}function Hv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qv(e){return e==null}function Bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function _t(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=Hv(()=>{if(Vv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xl(e){if(Td(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Td(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Xl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function xf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Aa(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Oa(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return Ci(this,"shape",u),u},checks:[]});return Aa(e,l)}function k8(e,t){if(!Xl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Oa(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return Ci(this,"shape",l),l}});return Aa(e,i)}function R8(e,t){if(!Xl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Ci(this,"shape",r),r}});return Aa(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Oa(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ci(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Aa(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Oa(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return Ci(this,"shape",h),h},checks:[]});return Aa(t,u)}function O8(e,t,n){const r=Oa(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return Ci(this,"shape",l),l}});return Aa(t,r)}function vo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Yu(e){return typeof e=="string"?e:e?.message}function yi(e,t,n){const r=e.message?e.message:Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Gv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wl(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ug,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kv=pe("$ZodError",XE),bf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new wo;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},L8=wf(bf),Sf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>yi(h,l,vi())));throw ZE(f,i?.callee),f}return u.value},$8=Sf(bf),jf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new wo;return l.issues.length?{success:!1,error:new(e??Kv)(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},F8=jf(bf),Cf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>yi(u,i,vi())))}:{success:!0,data:l.value}},I8=Cf(bf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},U8=e=>(t,n,r)=>wf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},H8=e=>async(t,n,r)=>Sf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},B8=e=>(t,n,r)=>jf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Cf(e)(t,n,i)},K8=e=>async(t,n,r)=>Cf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,hr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Gv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;hr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!qv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Gv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),_f=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;hr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{_f.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),_f.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),_f.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);const n=xf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`^${xf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);const n=new RegExp(`.*${xf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
+            color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Rn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return qu(t,[...f,...m,...h],e)},He(e.options,Rn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),qu(t,n,e,"center")),He(e.options,Rn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"left")},He(e.options,Rn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"right")},He(e.options,Rn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Rn))}};function qu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Is(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Is(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Is(e);const Dv=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Dv.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Dv.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const zr={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Dv};function Is(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:hs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?zr.includesString:typeof r=="number"?zr.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?zr.equals:Array.isArray(r)?zr.arrIncludes:zr.weakEquals},e.getFilterFn=()=>{var n,r;return pf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:zr[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=ba(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=ba(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,rp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:hs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return rp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return rp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:rp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:hs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Pl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Pl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Pl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},ap=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:ap(),...e}),getDefaultOptions:e=>({onColumnPinningChange:hs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?ap():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:ap())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Bu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ip=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Bu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ip(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:hs("columnSizing",e),onColumnSizingInfoChange:hs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bu.minSize,(r=l??e.columnDef.size)!=null?r:Bu.size),(i=e.columnDef.maxSize)!=null?i:Bu.maxSize)},e.getStart=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),op(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=op(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;op(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ip():(n=e.initialState.columnSizingInfo)!=null?n:ip())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Gu=null;function A$(){if(typeof Gu=="boolean")return Gu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gu=e,Gu}function op(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:hs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Pl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:hs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>zr.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return pf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:zr[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:hs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},tg=0,ng=10,lp=()=>({pageIndex:tg,pageSize:ng}),F$={getInitialState:e=>({...e,pagination:{...lp(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:hs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>ba(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?lp():(i=e.initialState.pagination)!=null?i:lp())},e.setPageIndex=r=>{e.setPagination(i=>{let l=ba(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:tg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?ng:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:ng)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,ba(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=ba(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},cp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:cp(),...e}),getDefaultOptions:e=>({onRowPinningChange:hs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?cp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:cp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:hs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{sg(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return sg(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},sg=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>sg(e,f.id,n,r,i))};function up(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=zv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function zv(e,t){var n;return(n=t[e.id])!=null?n:!1}function rg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(zv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=rg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const ag=/([0-9]+)/gm,U$=(e,t,n)=>RE(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(_a(e.getValue(n)),_a(t.getValue(n))),H$=(e,t,n)=>Lv(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>Lv(_a(e.getValue(n)),_a(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rLv(e.getValue(n),t.getValue(n));function Lv(e,t){return e===t?0:e>t?1:-1}function _a(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(ag).filter(Boolean),r=t.split(ag).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Al={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:hs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Al.datetime;if(typeof l=="string"&&(r=!0,l.split(ag).length>1))return Al.alphanumeric}return r?Al.text:Al.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Al[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=ba(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ig(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var hc=e=>e.type==="checkbox",wa=e=>e instanceof Date,bn=e=>e==null;const $v=e=>typeof e=="object";var Vt=e=>!bn(e)&&!Array.isArray(e)&&$v(e)&&!wa(e),J$=e=>Vt(e)&&e.target?hc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Vt(t)&&t.hasOwnProperty("isPrototypeOf")},gf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(gf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Vt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Gt(e[i]));return r}const mo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",Fv=["__proto__","constructor","prototype"],t8=/^\w*$/;var mc=e=>t8.test(e),Mt=e=>e===void 0;const n8=/[.[\]'"]/;var vf=e=>e.split(n8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Vt(e))return n;const r=mc(t)?[t]:vf(t);if(r.some(l=>Fv.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Ns=e=>typeof e=="function",wt=(e,t,n)=>{let r=-1;const i=mc(t)?[t]:vf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const a8=gf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),og=e=>bn(e)||!$v(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(og(e)||og(t))return Object.is(e,t);if(wa(e)&&wa(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(wa(f)&&wa(h)||(Vt(f)||Array.isArray(f))&&(Vt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Ku=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),dp=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Ul=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Ul(f,t))break}else if(Vt(f)&&Ul(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return wt(i,DE,t[n]),wt(e,n,i),e},xn=e=>Vt(e)&&!Object.keys(e).length,Iv=e=>e.type==="file",kd=e=>{if(!gf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pv=e=>e.type==="radio",Rd=e=>e instanceof RegExp,Uv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||tr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var po=e=>Vt(e)&&!Rd(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Pv(u),L=hc(u),H=M||L,U=(E||Iv(u))&&Mt(u.value)&&Mt(N)||kd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Uv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||tr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Q,message:ae}=wn(h)?{value:!!h,message:h}:po(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Q,ae;const le=po(w),be=po(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Q=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Q,message:ae}=po(x);if(Rd(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Ns(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Vt(j)){let Q={};for(const ae in j){if(!xn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!xn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},ud=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;rFv.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Vt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Kt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if($v(e[n])&&e[n]!==null&&!wa(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Vt(i)&&l){const u=IE(i,l);Vt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Pv(e)||hc(e),fp=e=>kd(e)&&e.isConnected,d8=e=>{for(const t in e)if(Ns(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Vt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function lg(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function cg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},cg(i,t[r],l),HE(t[r])&&lg(t,r)):Mt(i)||(t[r]=!0)}return t}function ri(e,t,n,r){n||(n=cg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Mt(t)||og(n[i])?n[i]=cg(l,Array.isArray(l)?[]:{},u):ri(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&lg(n,i)):nr(l,t[i])?lg(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Iv(t)?t.files:Pv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):hc(t)?zE(e.refs).value:qE(Mt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&wt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Dl=e=>Mt(e)?e:Rd(e)?e.source:Vt(e)?Rd(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(Ns(e.validate))return e.validate.constructor.name===b1;if(Vt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||mc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},g8=(e,t,n)=>!e||!t||e===t||ud(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(ke(e,t)).length&&Kt(e,t);const x8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},hp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Gt(BE),isLoading:Ns(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Vt(t.defaultValues)||Vt(t.values)?Gt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Gt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Ku(t.mode),w=Ku(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=xn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:mo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?wt(n.validatingFields,W,Y):Kt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ri(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const je=W(ke(r,z),de.argA,de.argB);me&&wt(r,z,je)}if(xe&&Array.isArray(ke(n.errors,z))){const je=W(ke(n.errors,z),de.argA,de.argB);me&&wt(n.errors,z,je),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const je=W(ke(n.touchedFields,z),de.argA,de.argB);me&&wt(n.touchedFields,z,je)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else wt(l,z,Y)},H=(z,Y)=>{wt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=mc(z)?[z]:vf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),je=ke(l,z,Mt(W)?ke(i,z):W);Mt(je)||de&&de.defaultChecked||Y?wt(l,z,Y?je:x1(me._f)):D(z,je),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&dp(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,je=!1;const _e={name:z};if(!t.disabled||de===!0){if(!W||de){const Ae=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(je=n.isDirty,n.isDirty=_e.isDirty=!Ae||ee(),xe=je!==_e.isDirty),je=!!ke(n.dirtyFields,z),Ae!==n.isDirty?n.dirtyFields=ri(i,l,void 0,r):Ae?Kt(n.dirtyFields,z):wt(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&je!==!Ae}if(W){const Ae=ke(n.touchedFields,z);Ae||(wt(n.touchedFields,z,W),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ae!==W)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?wt(n.errors,z,W):Kt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!xn(de)||xe){const je={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...je},E.state.next(je)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Vt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):wt(n.errors,W,de):Kt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Vt(W))for(const de in W){const me=W[de];me&&ht(`${hp}.${de}`,{message:wn(me.message)?me.message:"",type:me.type||Ls.validate})}else wn(W)||!W?ht(hp,{message:W||"",type:Ls.validate}):Ye(hp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const je=z[xe];if(je){const{_f:_e,...Ae}=je;if(_e){const Ke=f.array.has(_e.name),Ct=je._f&&h8(je._f),sn=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Ct&&sn&&A([_e.name],!0);const Dt=await v1(je,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,Ke);if(Ct&&sn&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Y)||(!Y&&(ke(Dt,_e.name)?Ke?f1(n.errors,Dt,_e.name):wt(n.errors,_e.name,Dt[_e.name]):Kt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ae)&&await q({context:me,onlyCheckValid:Y,fields:Ae,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!fp(W)):!fp(Y._f.ref))&&ot(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&wt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>i8(z,f,{...u.mount?l:Mt(Y)?i:wn(z)?{[z]:Y}:Y},W,Y),O=z=>$E(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let je=Y;if(xe){const _e=xe._f;_e&&(!_e.disabled&&wt(l,z,qE(Y,_e)),je=kd(_e.ref)&&bn(Y)?"":Y,PE(_e.ref)?[..._e.ref.options].forEach(Ae=>Ae.selected=je.includes(Ae.value)):_e.refs?hc(_e.ref)?_e.refs.forEach(Ae=>{(!Ae.defaultChecked||!Ae.disabled)&&(Array.isArray(je)?Ae.checked=!!je.find(Ke=>Ke===Ae.value):Ae.checked=je===Ae.value||!!je)}):_e.refs.forEach(Ae=>Ae.checked=Ae.value===je):Iv(_e.ref)?_e.ref.value="":(_e.ref.value=je,!_e.ref.type&&!me&&E.state.next({name:z,values:de?l:Gt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,je,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&Se(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const je=Y[xe],_e=z+"."+xe,Ae=ke(r,_e);(f.array.has(z)||Vt(je)||Ae&&!Ae._f)&&!wa(je)?B(_e,je,W,de,me):D(_e,je,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),je=f.array.has(z),_e=de?Y:Gt(Y),Ae=ke(l,z),Ke=nr(Ae,_e);if(Ke||wt(l,z,_e),je)E.array.next({name:z,values:de?l:Gt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Ct=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||Ct?D(z,_e,W,de,me):B(z,_e,W,de,me)}if(!Ke&&!me){const Ct=dp(z,f),sn=de?l:Gt(l);E.state.next({...Ct&&n,name:u.mount||Ct?z:void 0,values:sn})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Ns(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=FE(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=je=>{de=Number.isNaN(je)||wa(je)&&isNaN(je.getTime())||nr(je,ke(l,W,je))};if(me){let je,_e;const Ae=Y.type?x1(me._f):J$(z),Ke=z.type===mo.BLUR||z.type===mo.FOCUS_OUT,Ct=!m8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,sn=Ct||v8(Ke,ke(n.touchedFields,W),n.isSubmitted,w,g),Dt=dp(W,f,Ke);if(wt(l,W,Ae),Ke){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const Et=h[W];Et&&Et(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Ae,Ke),dt=!xn(Le)||Dt;if(!Ke&&E.state.next({name:W,type:z.type,...y?{values:Gt(l)}:{}}),sn)return(!Ct||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?Ke&&T():Ke||T()),dt&&E.state.next({name:W,...Dt?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!Ke&&Dt&&E.state.next({...n}),t.resolver){const{errors:Et}=await le([W]);if(A([W]),xe(Ae),!de){!xn(Le)&&E.state.next(Le);return}const $t=w1(n.errors,r,W),Hn=w1(Et,r,$t.name||W);je=Hn.error,W=Hn.name,_e=xn(Et)}else A([W],!0),je=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Ae),de&&(je?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&Se(me._f.deps),ae(W,_e,je,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},Se=async(z,Y={})=>{let W,de;const me=ud(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=xn(xe),de=z?!me.some(je=>ke(xe,je)):W}else z?(de=(await Promise.all(me.map(async xe=>{const je=ke(r,xe);return await q({fields:je&&je._f?{[xe]:je}:je,eventType:mo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:mo.TRIGGER});if(Y.delayError&&t.delayError&&wn(z)){const xe=ke(n.errors,z);xe?(Kt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Ul(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=IE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:wn(z)?ke(W,z):z.map(de=>ke(W,de))},Me=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ye=z=>{const Y=z?ud(z):void 0;Y?.forEach(W=>Kt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:je,type:_e,...Ae}=me;wt(n.errors,z,{...Ae,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},tt=(z,Y)=>{if(Ns(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},es=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,hr,z.reRenderRoot)){const je={...l};z.callback({values:je,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},es({...z,formState:{...x,...z.formState}})),ot=(z,Y={})=>{for(const W of z?ud(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Kt(r,W),Kt(l,W)),!Y.keepError&&Kt(n.errors,W),!Y.keepDirty&&Kt(n.dirtyFields,W),!Y.keepTouched&&Kt(n.touchedFields,W),!Y.keepIsValidating&&Kt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Kt(i,W);E.state.next({values:Gt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},mn=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},Nt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return wt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?mn({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Dl(Y.min),max:Dl(Y.max),minLength:Dl(Y.minLength),maxLength:Dl(Y.maxLength),pattern:Dl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Y),f.registerName.delete(z),W=ke(r,z);const je=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(je),Ae=W._f.refs||[];if(_e?Ae.find(Ke=>Ke===je):je===W._f.ref)return;wt(r,z,{_f:{...W._f,..._e?{refs:[...Ae.filter(fp),je,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:je.type,name:z}}:{ref:je}}}),X(z,!1,void 0,je)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},un=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Ul(r,we,f.mount),jt=z=>{tr(z)&&(E.state.next({disabled:z}),Ul(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},Lt=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=Gt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:je}=await le();A(),n.errors=xe,me=Gt(je)}else await q({fields:r,eventType:mo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Kt(me,xe);if(Kt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),un(),setTimeout(un);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},ts=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,Gt(ke(i,z))):(I(z,Y.defaultValue),wt(i,z,Gt(Y.defaultValue))),Y.keepTouched||Kt(n.touchedFields,z),Y.keepDirty||(Kt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,Gt(ke(i,z))):ee()),Y.keepError||(Kt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},At=(z,Y={})=>{const W=z?Gt(z):i,de=Gt(W),me=xn(z),xe=de,je=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ri(i,l,void 0,je))]);for(const Ae of Array.from(_e)){const Ke=ke(n.dirtyFields,Ae),Ct=ke(l,Ae),sn=ke(xe,Ae);Ke&&!Mt(Ct)?wt(xe,Ae,Ct):!Ke&&!Mt(sn)&&I(Ae,sn)}}else{if(gf&&Mt(z))for(const _e of f.mount){const Ae=ke(r,_e);if(Ae&&Ae._f){const Ke=Array.isArray(Ae._f.refs)?Ae._f.refs[0]:Ae._f.ref;if(kd(Ke)){const Ct=Ke.closest("form");if(Ct){Ct.reset();break}}}}if(Y.keepFieldsRef)for(const _e of f.mount)I(_e,ke(xe,_e));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?Gt(i):{},Y.keepFieldsRef)for(const _e of f.mount)wt(l,_e,ke(xe,_e))}else l=Gt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?ri(i,l,void 0,je):n.dirtyFields:Y.keepDefaultValues&&z?ri(i,z,void 0,je):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},nn=(z,Y)=>At(Ns(z)?z(l):z,{...t.resetOptions,...Y}),ns=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Ns(me.select)&&me.select()})}},hr=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},Tn={control:{register:Nt,unregister:ot,getFieldState:Me,handleSubmit:Lt,setError:ht,_subscribe:es,_runSchema:le,_updateIsValidating:A,_focusError:un,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:mn,_setErrors:U,_getFieldArray:O,_reset:At,_resetDefaultValues:()=>Ns(t.defaultValues)&&t.defaultValues().then(z=>{nn(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:jt,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Ku(t.mode),w=Ku(t.reValidateMode)}},subscribe:Fe,trigger:Se,register:Nt,handleSubmit:Lt,watch:tt,setValue:I,setValues:re,getValues:ve,reset:nn,resetField:ts,resetDefaultValues:(z,Y={})=>{if(i=Gt(z),!Y.keepDirty){const W=ri(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!xn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ye,unregister:ot,setError:ht,setFocus:ns,getFieldState:Me};return{...Tn,formControl:Tn}}function Vv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Gt(BE),isLoading:Ns(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Ns(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Ns(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},ug=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&ug(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));wt(u,"root",l),wt(n,r,u)}else wt(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Hv=globalThis.__zod_globalConfig;function gi(e){return Hv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function dg(e,t){return typeof t=="bigint"?t.toString():t}function qv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bv(e){return e==null}function Gv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function St(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ma(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=qv(()=>{if(Hv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Jl(e){if(Md(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Md(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function k8(e,t){if(!Jl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ma(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return ji(this,"shape",l),l}});return Ta(e,i)}function R8(e,t){if(!Jl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ji(this,"shape",r),r}});return Ta(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ta(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Ma(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return ji(this,"shape",h),h},checks:[]});return Ta(t,u)}function O8(e,t,n){const r=Ma(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return ji(this,"shape",l),l}});return Ta(t,r)}function wo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Zu(e){return typeof e=="string"?e:e?.message}function vi(e,t,n){const r=e.message?e.message:Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Kv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ec(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zv=pe("$ZodError",XE),xf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new _o;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},L8=bf(xf),wf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},$8=wf(xf),Sf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new _o;return l.issues.length?{success:!1,error:new(e??Zv)(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},F8=Sf(xf),jf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},I8=jf(xf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,i)},U8=e=>(t,n,r)=>bf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},H8=e=>async(t,n,r)=>wf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},B8=e=>(t,n,r)=>Sf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},K8=e=>async(t,n,r)=>jf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Kv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cf=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),Cf.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),Cf.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=yf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${yf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${yf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
 `).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>`  ${l}`)];return new t(...n,i.join(`
-`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=vo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new wo;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=vo(u,w)))});else{if(u.issues.length===w)continue;m||(m=vo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(vo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new wo;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new wo;return h.then(m=>i(m,r,f))}return i(h,r,f)}}_t(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Zv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),At=pe("$ZodStringFormat",(e,t)=>{_f.init(e,t),Zv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),At.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());At.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),At.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{At.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),At.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),At.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),At.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),At.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),At.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),At.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),At.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),At.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),At.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),At.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),At.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),At.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),At.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),At.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),At.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),At.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),At.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),At.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{At.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Od(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Od(j,n,w,t,y,g))):Od(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=Hv(()=>n2(t));_t(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Td,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Od(_,f,w,m,j,S))):Od(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=Hv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(`
+`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=wo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new _o;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=wo(u,w)))});else{if(u.issues.length===w)continue;m||(m=wo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(wo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new _o;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new _o;return h.then(m=>i(m,r,f))}return i(h,r,f)}}St(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Yv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ot=pe("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Yv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Ot.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Ot.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Ot.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Ot.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Ot.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Ot.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Ot.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Ot.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Ot.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Ot.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Ot.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Ot.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Ot.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Ot.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Ot.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Ot.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Ot.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Ot.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Ot.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Ot.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Ot.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Td(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Td(j,n,w,t,y,g))):Td(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=qv(()=>n2(t));St(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Md,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Td(_,f,w,m,j,S))):Td(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=qv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(`
         if (${T}.issues.length) {
           if (${A} in input) {
             payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
@@ -111,21 +111,21 @@ Error generating stack: `+d.message+`
           }
         }
 
-      `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Td,f=!Vv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!vo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>yi(u,r,vi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Bv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function dg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xl(e)&&Xl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=dg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),vo(e))return e;const u=dg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?xf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new wo;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bv(n.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>yi(u,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>yi(l,r,vi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Qu(u,t.in,r)):Qu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Qu(l,t.out,r)):Qu(i,t.out,r)}});function Qu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{hr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Wl(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Ll=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Ad(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Oo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Oo(t=>t.normalize(e))}function aP(){return Oo(e=>e.trim())}function iP(){return Oo(e=>e.toLowerCase())}function oP(){return Oo(e=>e.toUpperCase())}function lP(){return Oo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Wl(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(Wl(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new hr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ll,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&zn(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/
+      `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Md,f=!Hv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!wo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>vi(u,r,gi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),St(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),St(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),St(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),St(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Gv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function fg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Jl(e)&&Jl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=fg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),wo(e))return e;const u=fg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?yf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new _o;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),St(e._zod,"optin",()=>t.innerType._zod.optin),St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)}|null)$`):void 0}),St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),St(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>vi(u,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>vi(l,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),St(e._zod,"values",()=>t.in._zod.values),St(e._zod,"optin",()=>t.in._zod.optin),St(e._zod,"optout",()=>t.out._zod.optout),St(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Yu(u,t.in,r)):Yu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Yu(l,t.out,r)):Yu(i,t.out,r)}});function Yu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),St(e._zod,"propValues",()=>t.innerType._zod.propValues),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"optin",()=>t.innerType?._zod?.optin),St(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{fr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(ec(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Fl=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Od(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Lo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Lo(t=>t.normalize(e))}function aP(){return Lo(e=>e.trim())}function iP(){return Lo(e=>e.toLowerCase())}function oP(){return Lo(e=>e.toUpperCase())}function lP(){return Lo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(ec(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(ec(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new fr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Fl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Ln(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/
 
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dd(t,"input",e.processors),output:Dd(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return zn(r.element,n);if(r.type==="set")return zn(r.valueType,n);if(r.type==="lazy")return zn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return zn(r.innerType,n);if(r.type==="intersection")return zn(r.left,n)||zn(r.right,n);if(r.type==="record"||r.type==="map")return zn(r.keyType,n)||zn(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(r.in,n)||zn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zn(i,n))return!0;return!!(r.rest&&zn(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Dd=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function fg(){return fg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(fg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Pv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Yv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&cg({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Kv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Kv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ug,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ug,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ms=pe("ZodError",HP,{Parent:Error}),qP=wf(Ms),BP=Sf(Ms),GP=jf(Ms),KP=Cf(Ms),ZP=P8(Ms),YP=U8(Ms),QP=V8(Ms),XP=H8(Ms),WP=q8(Ms),JP=B8(Ms),e9=G8(Ms),t9=K8(Ms),P1=new WeakMap;function Ef(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dd(e,"input"),output:Dd(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),Ef(e,"ZodType",{check(...n){const r=this.def;return this.clone(Oa(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Aa(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Oo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Ll.add(r,{description:n}),r},meta(...n){if(n.length===0)return Ll.get(this);const r=this.clone();return Ll.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ll.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Zv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ef(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Ad(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Ad(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Zv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Xu,n)),e.uuidv4=n=>e.check(EI(Xu,n)),e.uuidv6=n=>e.check(NI(Xu,n)),e.uuidv7=n=>e.check(kI(Xu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function fd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{At.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Xu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,Ef(e,"ZodArray",{min(n,r){return this.check(Ad(n,r))},nonempty(n){return this.check(Ad(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),_t(e,"shape",()=>t.shape),Ef(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Qv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const hg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new hg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(Wl(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(Wl(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:st("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:st("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:st("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:st("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:st("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:st("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ag(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ag(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ag(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...In(Ln(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>On(g.row.original.url).then(w=>ke(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await or("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),ke("Share revoked."),t()}catch(n){ke(n.message,!0)}}const nU=Qv({name:fd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Uv({resolver:Yv(nU),values:{name:e.name}}),{data:m}=nt({queryKey:["invites",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=nt({queryKey:["orgShares",e.id],queryFn:()=>Qe(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),ke("Renamed."),l()}catch(j){ke(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await On(x.url);ke(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){ke(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>On(x.url).then(j=>ke(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await or("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),ke("Revoked."),u()}catch(j){ke(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=nt({queryKey:["apps",e.id],queryFn:()=>Qe(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&ke(f)}catch(h){ke(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await On(u),await Ql("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Ql("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>On(u.principal).then(f=>ke(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await or("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await or("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),ke("Role updated.")}catch(x){ke(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await or("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),ke("Removed."),r()}catch(w){ke(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Qv({require_verification:V1(),require_approval:V1()});function oU(){const e=mn(),{data:t,error:n}=nt({queryKey:["admin","policy"],queryFn:()=>Qe("/api/admin/policy")}),{data:r}=pE(!0),i=Uv({resolver:Yv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&ke(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),ke((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){ke(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),ke("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){ke(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function Es({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:st("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ns({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:st("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:st("leading-none font-semibold",e),...t})}function lr({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:st("text-muted-foreground text-sm",e),...t})}function Ps({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:st("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=mn(),n=nt({queryKey:["mcp","grants"],queryFn:()=>Qe("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{ke("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>ke(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(Es,{children:o.jsxs(Ns,{children:[o.jsx(ks,{children:"No agents connected"}),o.jsxs(lr,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(Es,{className:"mcp-grant",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:u.client_name||"Unnamed client"}),o.jsxs(lr,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Ps,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Xv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Wv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function Jv({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:st("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Cs({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:st("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function mg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const zd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ey(e){try{return localStorage.getItem(e)}catch{return null}}function hc(e,t){try{localStorage.setItem(e,t)}catch{}}const pg=new Set;function ty(){for(const e of pg)e()}function ny(e){return pg.add(e),()=>{pg.delete(e)}}const Ld=new Map;function hU(e){let t=Ld.get(e);if(t===void 0){const n=Number(ey(zd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),Ld.set(e,t),n>0||hc(zd(e),String(t))}return t}function mU(e){hc(zd(e),String(Date.now())),Ld.delete(e)}function pU(e){const t=Date.now();Ld.set(e,t),hc(zd(e),String(t)),ty()}function sy(e){return b.useSyncExternalStore(ny,()=>e?hU(e):0)}const gg=new Map,gU=[];function ry(e){let t=gg.get(e);if(!t){try{const n=JSON.parse(ey(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}gg.set(e,t)}return t}function W1(e,t){const n=ry(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];gg.set(e,r),hc(b2(e),JSON.stringify(r)),ty()}function vU(e){return b.useSyncExternalStore(ny,()=>e?ry(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(ny,()=>ey(w2)==="recent"?"recent":"name")}function xU(e){hc(w2,e),ty()}function hd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Vs(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Wu(e){const t=Vs(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ur="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Vs(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=hp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=hp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=hp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function ay(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function iy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=ay(t);return!e||n===null||!C2(Vs(e),n)?"":`stale · last changed ${iy(n)}`}function E2(e,t=!0){const n=nt({queryKey:["tree",e],queryFn:()=>Qe(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return nt({queryKey:["heat",e],queryFn:()=>Qe(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return nt({queryKey:["history",e,"prefix",t,20],queryFn:()=>Qe(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",$d=100;function T2(e,t=!0){const n=sy(e),r=e?M2(e):"";return nt({queryKey:["history",r,"since",n],queryFn:()=>Qe(r+"history?n="+$d+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=nt({queryKey:["heatDevices",n],queryFn:()=>Qe(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=nt({queryKey:["comments",e,"open-all"],queryFn:()=>Qe(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function ho(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let dr={query:"",sel:0},md=0,A2=null;const vg=new Set;function Nf(e){dr=e;for(const t of vg)t()}function oy(){return b.useSyncExternalStore(e=>(vg.add(e),()=>vg.delete(e)),()=>dr)}function D2(e){e!==dr.query&&Nf({query:e,sel:0})}function yg(){D2("")}function DU(e,t){md=e,A2=t,dr.sel>=e&&Nf({...dr,sel:Math.max(0,e-1)})}function zU(e){md!==0&&Nf({...dr,sel:(dr.sel+e+md)%md})}function J1(e){e!==dr.sel&&Nf({...dr,sel:e})}function LU(){A2?.(dr.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function mc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],Fd=e=>e>=$d?$d-1+"+":String(e);function mp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?mc(l.name):void 0,children:o.jsx(ui,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${Fd(u)} changes since your last visit`,children:Fd(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=_v(),w=r?.org??null,x=w?In(w.manage_url):null,j=r?.billing?In(r.billing.url):null,S=In("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Xv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Wv,{asChild:!0,children:l}),o.jsxs(Jv,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Cs,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&&vt("/"+_.id),ds()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(_.name),children:o.jsx(ui,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Cs,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(mg,{}),n&&t&&o.jsxs(Cs,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Cs,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(mg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Cs,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Cs,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+ho(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(uf,{delayDuration:300,children:[o.jsx(df,{asChild:!0,children:f}),o.jsx(ff,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=oy();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),bo(),ds())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?bo(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?yg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:yg,children:"esc"}):o.jsxs(uf,{delayDuration:150,children:[o.jsx(df,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{bo(),ds()},children:Yl?"⌘K":"Ctrl K"})}),o.jsxs(ff,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Yl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(jv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?Fd(n)+" new":void 0,badge:r==="activity"&&n?Fd(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.current.name),children:o.jsx(ui,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Fr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:st("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=nt({queryKey:["billing"],queryFn:()=>Qe(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsxs(ks,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(lr,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:r.name}),o.jsx(lr,{children:r.blurb})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Manage subscription"}),o.jsx(lr,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function pd({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:st("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function pp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:st("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:st("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function Fn(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const xg=280,ZU=Qv({name:fd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:fd().max(xg,`Keep the description under ${xg} characters.`),icon:fd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=Fn(e.perm,"admin"),l=Uv({resolver:Yv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),ke("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){ke(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!Fn(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"General"}),o.jsx(lr,{children:"Name, description and icon for this project."})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:u})}),o.jsxs(Xv,{children:[o.jsx(Wv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(Jv,{align:"start",className:"ps-icon-grid",children:[o.jsx(Cs,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ui,{})}),Object.keys(Yp).map(m=>o.jsx(Cs,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ui,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(pp,{htmlFor:"ps-name",children:"Name"}),o.jsx(pd,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(pp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",xg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Fr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(Es,{id:"ps-devices",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Devices"}),o.jsx(lr,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Ps,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...In(dn("install",e.id)),children:"Connect a device"})})})]}),Fn(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(Es,{children:[o.jsx(Ns,{children:o.jsx(ks,{children:"About"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(Es,{className:"ps-danger",children:[o.jsx(Ns,{children:o.jsx(ks,{children:"Danger zone"})}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Ql(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),ke(`Deleted “${e.name}”.`),await n()}catch(y){ke(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(Es,{id:"ps-data",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Data"}),o.jsx(lr,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Ps,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),ke(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){ke(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(Es,{children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"Public links"}),o.jsxs(lr,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Fr,{}),o.jsx(Ps,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:Fn(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const bg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(bg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=mn(),{data:r,error:i}=Nv(e.id),l=Fn(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),ke(j)}catch(S){ke(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Ql("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(Es,{className:"ps-people",children:[o.jsxs(Ns,{children:[o.jsx(ks,{children:"People"}),o.jsx(lr,{children:"Who can see and change this project."})]}),o.jsx(Fr,{}),o.jsxs(Ps,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await On(x.url+"?p="+e.id);ke(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){ke(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await or("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:bg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:bg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function kf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
-to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=kf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive
-bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:mc(e.name),children:o.jsx(ui,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(Jl,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(Jl,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function Jl({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await On(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(Jl,{code:kf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),Qe(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await yd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await yd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await Qe("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=kf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await Qe("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await yd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>vt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(Jl,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&&vt("/setup/connect"),e!=="welcome"&&!t&&vt("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>vt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),vt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(lc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(cc,{className:"modal",showCloseButton:!1,children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ec(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function Rf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Eo(e,t,n){return n?ec(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Vg)||e.status===429||e.status>=500}function ly(e,t,n,r){return nt({queryKey:t,queryFn:()=>Rf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function tc(e,t,n){return ly(t?ec(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=nt({queryKey:["frame",e,t],queryFn:()=>Qe(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=mn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,W)=>{if(!Z)return;const Y=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Y.has(be)?!1:(Y.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,W)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],W=>W&&RU(W,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const W of L.paths)r.invalidateQueries({queryKey:["render",e,W]}),r.invalidateQueries({queryKey:["text",Eo(e,W)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function cy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(`
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ln(r.element,n);if(r.type==="set")return Ln(r.valueType,n);if(r.type==="lazy")return Ln(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ln(r.innerType,n);if(r.type==="intersection")return Ln(r.left,n)||Ln(r.right,n);if(r.type==="record"||r.type==="map")return Ln(r.keyType,n)||Ln(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(r.in,n)||Ln(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Ln(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Ln(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Ln(i,n))return!0;return!!(r.rest&&Ln(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Ad=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function hg(){return hg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(hg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Uv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Qv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Zv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Zv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,dg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,dg,2)}},isEmpty:{get(){return e.issues.length===0}}})},Os=pe("ZodError",HP,{Parent:Error}),qP=bf(Os),BP=wf(Os),GP=Sf(Os),KP=jf(Os),ZP=P8(Os),YP=U8(Os),QP=V8(Os),XP=H8(Os),WP=q8(Os),JP=B8(Os),e9=G8(Os),t9=K8(Os),P1=new WeakMap;function _f(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),_f(e,"ZodType",{check(...n){const r=this.def;return this.clone(Ma(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ta(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Lo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Fl.add(r,{description:n}),r},meta(...n){if(n.length===0)return Fl.get(this);const r=this.clone();return Fl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Fl.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Yv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_f(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Od(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Od(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Yv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Qu,n)),e.uuidv4=n=>e.check(EI(Qu,n)),e.uuidv6=n=>e.check(NI(Qu,n)),e.uuidv7=n=>e.check(kI(Qu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function dd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Qu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,_f(e,"ZodArray",{min(n,r){return this.check(Od(n,r))},nonempty(n){return this.check(Od(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),St(e,"shape",()=>t.shape),_f(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Xv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const mg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new mg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(ec(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(ec(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:at("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:at("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:at("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:at("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:at("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:at("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ig(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ig(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ig(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Pn($n(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Mn(g.row.original.url).then(w=>Ne(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const nU=Xv({name:dd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=hn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Vv({resolver:Qv(nU),values:{name:e.name}}),{data:m}=rt({queryKey:["invites",e.id],queryFn:()=>We(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=rt({queryKey:["orgShares",e.id],queryFn:()=>We(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await Mn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Mn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=hn(),n=`/api/orgs/${e.id}/apps`,{data:r}=rt({queryKey:["apps",e.id],queryFn:()=>We(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Mn(u),await Wl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Wl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Mn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(w){Ne(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Xv({require_verification:V1(),require_approval:V1()});function oU(){const e=hn(),{data:t,error:n}=rt({queryKey:["admin","policy"],queryFn:()=>We("/api/admin/policy")}),{data:r}=pE(!0),i=Vv({resolver:Qv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:at("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rs({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:at("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ms({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:at("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:at("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:at("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=hn(),n=rt({queryKey:["mcp","grants"],queryFn:()=>We("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(ks,{children:o.jsxs(Rs,{children:[o.jsx(Ms,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(ks,{className:"mcp-grant",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Jv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function ey({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:at("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Es({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:at("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function pg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const Dd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ty(e){try{return localStorage.getItem(e)}catch{return null}}function pc(e,t){try{localStorage.setItem(e,t)}catch{}}const gg=new Set;function ny(){for(const e of gg)e()}function sy(e){return gg.add(e),()=>{gg.delete(e)}}const zd=new Map;function hU(e){let t=zd.get(e);if(t===void 0){const n=Number(ty(Dd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),zd.set(e,t),n>0||pc(Dd(e),String(t))}return t}function mU(e){pc(Dd(e),String(Date.now())),zd.delete(e)}function pU(e){const t=Date.now();zd.set(e,t),pc(Dd(e),String(t)),ny()}function ry(e){return b.useSyncExternalStore(sy,()=>e?hU(e):0)}const vg=new Map,gU=[];function ay(e){let t=vg.get(e);if(!t){try{const n=JSON.parse(ty(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}vg.set(e,t)}return t}function W1(e,t){const n=ay(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];vg.set(e,r),pc(b2(e),JSON.stringify(r)),ny()}function vU(e){return b.useSyncExternalStore(sy,()=>e?ay(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(sy,()=>ty(w2)==="recent"?"recent":"name")}function xU(e){pc(w2,e),ny()}function fd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Xu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ir="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=mp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=mp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=mp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function iy(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function oy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=iy(t);return!e||n===null||!C2(Ps(e),n)?"":`stale · last changed ${oy(n)}`}function E2(e,t=!0){const n=rt({queryKey:["tree",e],queryFn:()=>We(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return rt({queryKey:["heat",e],queryFn:()=>We(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return rt({queryKey:["history",e,"prefix",t,20],queryFn:()=>We(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",Ld=100;function T2(e,t=!0){const n=ry(e),r=e?M2(e):"";return rt({queryKey:["history",r,"since",n],queryFn:()=>We(r+"history?n="+Ld+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=rt({queryKey:["heatDevices",n],queryFn:()=>We(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=rt({queryKey:["comments",e,"open-all"],queryFn:()=>We(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function vo(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},hd=0,A2=null;const yg=new Set;function Ef(e){ur=e;for(const t of yg)t()}function ly(){return b.useSyncExternalStore(e=>(yg.add(e),()=>yg.delete(e)),()=>ur)}function D2(e){e!==ur.query&&Ef({query:e,sel:0})}function xg(){D2("")}function DU(e,t){hd=e,A2=t,ur.sel>=e&&Ef({...ur,sel:Math.max(0,e-1)})}function zU(e){hd!==0&&Ef({...ur,sel:(ur.sel+e+hd)%hd})}function J1(e){e!==ur.sel&&Ef({...ur,sel:e})}function LU(){A2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function gc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],$d=e=>e>=Ld?Ld-1+"+":String(e);function pp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?gc(l.name):void 0,children:o.jsx(ci,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${$d(u)} changes since your last visit`,children:$d(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=Ev(),w=r?.org??null,x=w?Pn(w.manage_url):null,j=r?.billing?Pn(r.billing.url):null,S=Pn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Wv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Jv,{asChild:!0,children:l}),o.jsxs(ey,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Es,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),fs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(_.name),children:o.jsx(ci,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Es,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(pg,{}),n&&t&&o.jsxs(Es,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Es,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(pg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Es,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+vo(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(cf,{delayDuration:300,children:[o.jsx(uf,{asChild:!0,children:f}),o.jsx(df,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=ly();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),Co(),fs())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?Co(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?xg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:xg,children:"esc"}):o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{Co(),fs()},children:Xl?"⌘K":"Ctrl K"})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Xl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(Cv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?$d(n)+" new":void 0,badge:r==="activity"&&n?$d(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.current.name),children:o.jsx(ci,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Lr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:at("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=rt({queryKey:["billing"],queryFn:()=>We(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsxs(Ms,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function md({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:at("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function gp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:at("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:at("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function In(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const bg=280,ZU=Xv({name:dd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:dd().max(bg,`Keep the description under ${bg} characters.`),icon:dd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=In(e.perm,"admin"),l=Vv({resolver:Qv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){Ne(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!In(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:u})}),o.jsxs(Wv,{children:[o.jsx(Jv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(ey,{align:"start",className:"ps-icon-grid",children:[o.jsx(Es,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ci,{})}),Object.keys(Qp).map(m=>o.jsx(Es,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ci,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-name",children:"Name"}),o.jsx(md,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(gp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",bg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Lr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(ks,{id:"ps-devices",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Pn(ln("install",e.id)),children:"Connect a device"})})})]}),In(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(ks,{children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"About"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(ks,{className:"ps-danger",children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"Danger zone"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Wl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(ks,{id:"ps-data",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=hn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:In(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const wg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(wg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=hn(),{data:r,error:i}=kv(e.id),l=In(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Wl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(ks,{className:"ps-people",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await Mn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:wg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:wg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function Nf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
+to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=Nf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive
+bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(tc,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(tc,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function tc({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Mn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(tc,{code:Nf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),We(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await vd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await vd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await We("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=Nf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await We("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await vd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(tc,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(uc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(dc,{className:"modal",showCloseButton:!1,children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function nc(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function kf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Mo(e,t,n){return n?nc(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Hg)||e.status===429||e.status>=500}function cy(e,t,n,r){return rt({queryKey:t,queryFn:()=>kf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function sc(e,t,n){return cy(t?nc(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=rt({queryKey:["frame",e,t],queryFn:()=>We(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=hn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,X)=>{if(!Z)return;const Q=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Q.has(be)?!1:(Q.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,X)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],X=>X&&RU(X,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const X of L.paths)r.invalidateQueries({queryKey:["render",e,X]}),r.invalidateQueries({queryKey:["text",Mo(e,X)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function uy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(`
 `).filter(f=>f.trim()).join(`
 `),t.push(i),i=null)};for(const u of e.split(`
 `)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(`
-`).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=cy(e),n=[];let r=0;return e.split(`
+`).map(r=>r.replace(/^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?/,"").trim()).filter(Boolean).join(" · ");return n.length>t?n.slice(0,t-1)+"…":n}const q2=/^\s*[-*+]\s+\[([ xX])\]\s+(.*)$/;function gV(e){const t=uy(e),n=[];let r=0;return e.split(`
 `).forEach((i,l)=>{const u=q2.exec(i);if(u){const f=/(?:^|\s)@([\w.-]+)/.exec(u[2])?.[1]??"",h=u[2].replace(/(?:^|\s)@[\w.-]+/g,"").trim();n.push({text:h,owner:f,done:u[1]!==" ",section:H2(t,r)?.name??"",line:l+1})}r+=i.length+1}),n}function vV(e){return e.map(t=>`- [${t.done?"x":" "}] ${t.text}${t.owner?" @"+t.owner:""}`).join(`
 `)}function BB(e){return e.split(`
-`).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>wg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const Sg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":Sg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${Sg(u.name)} 70% 88%)`,color:`hsl(${Sg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let Al;const gp=()=>{if(Al!==void 0)return Al;if(typeof navigator>"u")return Al=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Al=!0;const e=navigator.maxTouchPoints;return Al=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Id={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Id),l&&r.addEventListener("scrollend",y,Id),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=fo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!gp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Id),l.addEventListener("touchend",f,Id),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=fo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=fo(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],W=Z!==void 0?x[Z]:void 0;A=W?W.end+m:r+i}else if(E===f){let Z=0,W=S[0],Y=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=fo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=fo(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(gp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const vp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?nc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),vp(()=>h._didMount(),[]),vp(()=>h._willUpdate()),vp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:st("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:st("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:st("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function qr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,jg=-.005,Q2=-.01,Cg=1,Pl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Ju=new Map,sH=2e5;function W2(e){let t=Ju.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Ju.size>=sH&&Ju.clear(),Ju.set(e,t),t}let Ul=new Int32Array(64);function aS(e,t,n){Ul.length0&&(N=Math.max(h[y+_-1]+Pl[f[n+_]],h[m+_-1]+Cg)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Pl[f[n+E]],h[_-l-1]+Cg)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+Cg,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ba[i+1]>n?t.lastIndexOf(e[i],ba[i+1]-1):-1;if(u=0;i--)ba[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&_g(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function xp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=_g(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class bp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new bp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new bp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=xp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new bp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return xp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),qr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=qr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=qr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!qr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Eg({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function wp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,W)=>o.jsx("span",{className:"tguide",style:{left:8+W*13+5},"aria-hidden":"true"},W)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:wp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:W,depth:Y,conflicts:ae,fresh:le}=Z,be=W.dir?n.has(W.path):!1,$=()=>{if(R.current===W.path){R.current=null;return}if(W.dir&&i===W.path&&l){r(W.path);return}m.open(W.path),W.dir||ds()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=W.path)):R.current===W.path&&(R.current=null),E(V=>q?W.path:V===W.path?null:V)},children:[o.jsxs(Xv,{open:x===W.path,onOpenChange:q=>{q&&T(),j(q?W.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(W.dir?"dir":"file")+(i===W.path?" active":"")+(W.dir&&!be?" collapsed":"")+(x===W.path||S===W.path?" menu-open":""),"data-path":W.path,tabIndex:0,role:"button",title:W.name,"aria-expanded":W.dir?be:void 0,style:H(U.start,Y),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=W.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}wp($)(q)}},children:[L(Y),o.jsx("span",{className:"chev",onClick:q=>{W.dir&&(q.stopPropagation(),r(W.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:W.dir?"folder":W.link?"link":"doc"})}),o.jsx("span",{className:"label",title:W.link?`${W.name} → ${W.link}`:void 0,children:W.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),W.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),W.dir&&u.has(W.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":W.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[W.dir&&m.newFile&&(m.canCreateIn?.(W.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+W.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(W.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Wv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+W.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(Jv,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:W.path,dir:!!W.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,Sp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=oy(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,Sp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||ds()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Eg,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>Sp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-Sp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>bo(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Yl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Pd(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Pd(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Pd(u,"comment"),f&&Pd(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(jv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Ud={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},uy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function di(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function Ng(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?uy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?Ng(e.since):null,l=e?.until?Ng(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&uy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&uy[e.range]||30}function AH(e){return e?.range&&Ud[e.range]?Ud[e.range]:e?.since||e?.until?"Custom range":"All time"}function dy(e,t=new Date){if(e===di(t))return"Today";if(e===di(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=Ng(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function xi(e){return!!e.session}function Mf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
-`);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const fy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Gp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Gp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Vs(t):0,l=_2(t,e.time),u=ay(e.time),f=e.user_name||e.user||e.author?hf(e):"",h=f?yv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",pi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":iy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ur,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=fy(),[f,h]=b.useState(!1),m=UH(l),y=r?Vs(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Vs(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ur,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ur]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.lengthq2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
+`);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=fy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?cy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await On(vV(h));ke(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=wg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>wg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=nt({queryKey:["history",e,"edit-rail",t],queryFn:()=>Qe(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});ke("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){ke("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DzIcnMyR.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CQ41m5Hk.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function jp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Eo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>Rf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Eo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):oi.test(n)?o.jsx(a7,{...e}):Lr.test(n)?o.jsx(WH,{...e,fileURL:l}):id.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=ly(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Tf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${pi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Lr.test(n)&&!e.editSource,l=Eo(t,n),u=V2(t,n,l).url,f=ly(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(it=>{Fe&&it.status==="success"&&!it.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=oi.test(n),U=pV(n),[Z,W]=b.useState(H?"write":"markdown"),[Y,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(it=>it+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Y?.collab??null,P=b.useRef("");P.current=Y?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const it=[];B.awareness.getStates().forEach(ht=>{const sn=ht.user?.name;sn&&it.push(sn)}),K([...new Set(it)]);const nn=cy(P.current),yt=new Set;for(const ht of B.remoteCursors()){const sn=H2(nn,ht.pos);sn&&yt.add(sn.name)}D(yt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),je=b.useRef(null),ve=async Fe=>{try{const it=await Rf(l),nn=je.current;if(it.kind==="text"&&nn){const yt=nn.merge(it.text,it.sha,{held:Fe});re(yt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Te}=e;b.useEffect(()=>{if(!Te)return;const Fe=async()=>{const it=je.current;if(!it)return!0;const nn=it.mayServerRefuseShrink(),yt=it.saveNow();let ht;try{nn?await yt:await Promise.race([yt,new Promise(sn=>{ht=setTimeout(sn,1500)})])}catch{}finally{clearTimeout(ht)}return it.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Te.current=Fe,()=>{Te.current===Fe&&(Te.current=null)}},[Te,we,t,n,l]);const Ze=b.useRef(0),mt=Fe=>{ke("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=it=>{if(it.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ze.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const Je=M==="offline",Wn=Je&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:Je?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),Wn]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,Wn,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),Je&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>W(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Y?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:mt,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me,onRendered:e.onRendered,handle:je}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:je,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:mt,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&ke("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ze.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",pi(xV(Y?.text??x.text))," ·"," ",bV(Y?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Y&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Y.line,", Col ",Y.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function hy(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=nt(hy(t,n)),f=b.useMemo(()=>u?py(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>my(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=fy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=nt(hy(n,r,i)),w=b.useMemo(()=>y?py(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=_v(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Tf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?dn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>my(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function my(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function py(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",Ln(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Tf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Tf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=nt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Tf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Rg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Rg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:ec(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:ec(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=tc(e,n,!0),l=tc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?kg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=tc(e,t,r&&!!t),l=tc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:kg(i.data.text,l.data.text):kg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=nt({queryKey:["render",e,t,n],queryFn:()=>Qe(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?py(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Rg(t),src:ec(e,n,Rg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>my(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=tc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
-`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function gy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=hf(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,W=!!l?.busy&&l.busy===e.path,Y=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?qr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":xi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:yv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?pi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:W,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),W?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Y)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Y&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=hd(n,t.path,!0);m&&h.push(Wu(m)+" in 30 days");const y=!!m||l.some(g=>hd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ur}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?pi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=hd(n,g.path,!!g.dir);x&&(w=Wu(x)+(w?" · "+w:""));const j=g.dir?null:qr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Wu(x)+" in 30 days. "+Ur,title:Wu(x)+" in 30 days. "+Ur}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(gy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=Nv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=Fn(e.perm,"admin"),x=Fn(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[W,Y]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),ke(I)}catch(re){ke(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Y(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Y(null),nj("share_created");const he=await On(re.url);ke(he?"Link created and copied.":"Link created."),i()}catch(I){ke("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Y(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){ke(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(lc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(cc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(To,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(W)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Y(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>On(T?T.url:window.location.href).then(P=>ke(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>On(r.url).then(i=>ke(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return nt({queryKey:["comments",e,t],queryFn:()=>Qe(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function $l(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=$l(t.quote||"").text;if(!n)return null;const{text:r,map:i}=$l(e),l=S7(r,n,$l(t.prefix||"").text,$l(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!$l(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
-`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",ed="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,W]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,W(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!td(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=nd();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(ed,new Highlight(B)):ee.delete(ed)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Y=b.useRef(null);b.useEffect(()=>{const V=nd();!V||r||(j?.composing&&Y.current?V.set(ed,new Highlight(Y.current)):W(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{nd()?.delete(jS),nd()?.delete(ed)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{td(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||td(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Y.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(td(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){ke("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){ke("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){ke(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await or("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function td(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function nd(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,Cp=.1,_p=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Mg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Mg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(_p,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(_p,j.length))):(g*=z7,i>0&&(g*=Math.pow(_p,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(gg&&(g=w*Cp)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Mg(e,t,ES(e),ES(t),0,0,{})}var Dl='[cmdk-group=""]',Ep='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Tg="cmdk-item-select",mo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),pc=()=>b.useContext(wN),SN=b.createContext(void 0),vy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=po(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=po(()=>new Set),i=po(()=>new Map),l=po(()=>new Map),u=po(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=us(),R=us(),T=us(),A=b.useRef(null),M=eq();bi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),bi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Y(),Z(),M(1,W);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let je=document.getElementById(T);je?je.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var je;n.current.selectedItemId=(je=le())==null?void 0:je.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let je=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,je);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Y(),Z(),n.current.value||W(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Y(),P?.getAttribute("id")===D&&W(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let je=D.get(we);he=Math.max(je,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let je=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(je))!=null?we:0)}).forEach(I=>{let re=I.closest(Ep);re?re.appendChild(I.parentElement===re?I:I.closest(`${Ep} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Ep} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Dl}[${mo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function W(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(mo);L.setState("value",B||void 0)}function Y(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",je=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,je);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let je of we)if(n.current.filtered.items.get(je)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Dl))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(mo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(mo))}function V(D){let B=le(),P=B?.closest(Dl),I;for(;P&&!I;)P=D>0?W7(P,Dl):J7(P,Dl),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(mo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(ot.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Tg);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Of(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=us(),l=b.useRef(null),u=b.useContext(jN),f=pc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;bi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=vy(),w=ka(M=>M.value&&M.value===y.current),x=ka(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Tg,j),()=>M.removeEventListener(Tg,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(ot.div,{ref:So(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=us(),f=b.useRef(null),h=b.useRef(null),m=us(),y=pc(),g=ka(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);bi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(ot.div,{ref:So(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Of(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=ka(u=>!u.search);return!n&&!l?null:b.createElement(ot.div,{ref:So(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=vy(),u=ka(m=>m.search),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(ot.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=ka(m=>m.selectedItemId),h=pc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(ot.div,{ref:So(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Of(e,m=>b.createElement("div",{ref:So(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Gg,{open:n,onOpenChange:r},b.createElement(Zg,{container:u},b.createElement(Yg,{"cmdk-overlay":"",className:i}),b.createElement(Qg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>ka(n=>n.filtered.count===0)?b.createElement(ot.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(ot.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Of(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),gc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return bi(()=>{t.current=e}),t}var bi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function po(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function ka(e){let t=vy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=pc();return bi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(mo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=po(()=>new Map);return bi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Of({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(gc,{"data-slot":"command",className:st("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(gc.Input,{"data-slot":"command-input",className:st("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(gc.List,{"data-slot":"command-list",className:st("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(gc.Group,{"data-slot":"command-group",className:st("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(gc.Item,{"data-slot":"command-item",className:st("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Eg,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Eg,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(lc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(cc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(To,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Og=new Map,hq=[],Ag=new Set;function mq(e){return Ag.add(e),()=>{Ag.delete(e)}}function kN(e){let t=Og.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Og.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Og.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Ag)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function yy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||yy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),xi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&xi(r)&&(l.agent=Mf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=qr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=ay(l.time,n);if(!u||f===null)continue;const h=Vs(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=hd(t,l.path,!0),f=u?Vs(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Vd=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=sy(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=nt({queryKey:["homeHistory",u],queryFn:()=>Qe(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=nt({queryKey:["comments",u,"open-all"],queryFn:()=>Qe(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=$d),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Y=>i&&Y.user===i.email).map(Y=>Y.path)),W=new Map;for(const Y of x.data?.comments||[]){const ae=!!i&&(Y.author===i.email||Y.messages.some(le=>le.author===i.email));!Z.has(Y.path)&&!ae||W.set(Y.path,(W.get(Y.path)||0)+1)}for(const[Y,ae]of W)U.push({kind:"comments",path:Y,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===xi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>Ln(U,l),H=dn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${ho(f)}.`:`Since your last visit ${ho(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...In(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Vd(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",ho(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...In(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],W=U.run,Y=xi(Z),ae=Y?Mf(Z.note):Z.user_name||Z.author||"Someone",le=W?`${Z.kind==="delete"?"changed":"updated"} ${yy(W)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Y?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Y?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),W?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Vd(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...In(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:ho(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(Jl,{code:kf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...In(dn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...In(dn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...In(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Vd(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Vd(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${iy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...In(t(e.path)),children:l})]})}function Rq(e,t){return nt({queryKey:["heatDevices",e],queryFn:()=>Qe(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},Dg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Hs=(e,t)=>`${e} ${t}${e===1?"":"s"}`,vc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Af(e){const t=[e.path,`${Hs(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${vc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
-`),{data:r}=nt({queryKey:["emptied",e,n],queryFn:()=>Qe(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...In(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Vs(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Vs(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Hs(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ur}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ur}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Df(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",Dg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Hs(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Hs(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Af(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[vc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Af(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Hs(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Hs(e.files.length,"file")} · read files changed ~${vc(e.days)}`,...n].join(" — ")}const Np=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,Np,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:vc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Df,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${Np} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:Np},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,W=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Y=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Y,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Y,children:[W,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Hs(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[Dg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":vc(l.days)})]},l.path))})]});return o.jsx(Df,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Hs(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",Dg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Af(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Df,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Af(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Hs(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?bv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Df,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Hs(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Rv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(pd,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Ud).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(pd,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(pd,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Ud[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>Qe(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),W=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Y=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Y))Z.current.add(ve);for(const ve of Y)ve.device?.id&&!W.current.has(ve.device.id)&&W.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...W.current].map(([ve,Te])=>({id:ve,name:Te})).sort((ve,Te)=>ve.name.localeCompare(Te.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Y),[Y]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Te=>{if(Te.metaKey||Te.ctrlKey||Te.altKey||Te.defaultPrevented)return;const Ze=Te.target;if(Ze&&(Ze.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ze.tagName)))return;if(Te.key==="Escape"&&V!==null){ee(null);return}if(Te.key!=="j"&&Te.key!=="k"||!q.length)return;Te.preventDefault();const mt=V===null?-1:q.indexOf(V),Je=Te.key==="j"?Math.min(q.length-1,mt+1):Math.max(0,mt===-1?0:mt-1);ee(q[Je])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Y[ve].prev||Y[ve].kind==="delete")return Y[ve].prev||void 0;for(let Te=ve+1;Te{const Te=Y[ve].kind==="delete"?K(ve):Y[ve].blob;return Te&&Te===O.get(Y[ve].path)?void 0:Te},B=ve=>O.get(Y[ve].path)==="",P=ve=>{const Te=K(ve);return Te&&Te!==O.get(Y[ve].path)?Te:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Y){const Te=di(new Date(ve.time));he.set(Te,(he.get(Te)??0)+1)}const we=V!==null?Y[V]:void 0,je=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Y.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Y.length===0&&(Rv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Te])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Te),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Te)=>{const Ze=di(new Date(Y[ve.i].time)),mt=Ze!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:dy(Ze)}),o.jsxs("span",{children:["· ",he.get(Ze)," change",he.get(Ze)===1?"":"s",R&&Ze===di(new Date(Y[Y.length-1].time))?"+":""]})]},"d"+Ze):null;re=Ze;const Je=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Te):o.jsx(gy,{idx:ve.i,entry:Y[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return mt?[mt,Je]:Je}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:je>0?()=>ee(q[je-1]):void 0,onNext:jeee(q[je+1]):void 0},V):Y.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=nt({queryKey:["history-summary",e,u],queryFn:()=>Qe(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=di(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?dy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=xi(t)?Mf(t.note):yv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:xi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",dy(di(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);ke(await On(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=hf(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=nt({queryKey:["session-reads",r,_,N],queryFn:()=>Qe(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Y=>Y.path)),M=[...T].filter(Y=>!A.has(Y)).sort(),L=e.entries.map(Y=>new Date(Y.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=yy(e),W=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Mf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:W,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),W?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Y,ae)=>o.jsx(gy,{entry:Y,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Y.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Y=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Y),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Y}),!t.has(Y)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Y))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,zg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,zg),Math.max(t,zg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Gp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":zg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nQe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?hf(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Ov()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),W=!!M&&g&&!U&&!Z&&!L,Y=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&oi.test(M)&&f.prefetchQuery(hy(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=nt({queryKey:["resolve",n,M],queryFn:()=>Qe(n+"resolve?path="+encodeURIComponent(M)),enabled:W,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!W||!ae?.to||(be({from:M,to:ae.to}),vt(Ln(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[W,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ne=>Ne.dir);ie.length===1&&q(Ne=>new Set(Ne).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ne=new Set(ie);for(const Le of _H(H))Ne.add(Le);return y.has(H)&&Ne.add(H),Ne})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ne=>{const Le=new Set(Ne);return Le.has(ie)?Le.delete(ie):Le.add(ie),Le})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ne=CB(D.current,u);Ne!==null&&ie.scrollTo({top:Ne,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ne)=>{vt(Ln(ie,l?.id,Ne)),ds()},[l?.id]),re=b.useCallback(ie=>vt(dn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[je,ve]=b.useState(!1),[Te,Ze]=b.useState(!1),[mt,Je]=b.useState(!1),[Wn,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),Je(!0)}),[]);const it=b.useRef(null),nn=b.useRef(null),yt=b.useRef(null),ht=e.panel??null,sn=!ht&&i&&!!l&&(Z||U)&&Fn(l.perm,"write"),Ut=ie=>K2(_,ie)?.me,An=!ht&&Z&&!L&&(!i||!!l&&Fn(Ut(M)??l.perm,"write")),dt=!!r.editing&&An;b.useEffect(()=>{if(!An||!Z||dt)return;(window.requestIdleCallback??(Ne=>window.setTimeout(Ne,1500)))(()=>jp())},[An,Z,dt]);const[Bs,hs]=b.useState(!1);b.useEffect(()=>{hs(!1)},[M,L]);const Gr=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ne=0;for(let Le=0;Lemr||[],[mr]),z=Cn.filter(ie=>!ie.resolved).length,[Q,X]=b.useState(!1),[fe,me]=b.useState(null),[xe,Se]=b.useState(!1),_e=b.useCallback(()=>X(!0),[]);b.useEffect(()=>{me(null),Se(!1)},[M]),b.useEffect(()=>{r.comment&&(X(!0),me(r.comment))},[r.comment]);const Ee=!!r.full&&!r.view&&!!M&&!U&&!ht,[rt,kt]=b.useState(null),Zt=b.useRef(null),Dt=b.useRef(null),ze=b.useRef(!1);b.useEffect(()=>{ze.current=!1},[M]);const xt=b.useCallback(()=>{ze.current=!0,vt(Ln(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),bt=b.useCallback(()=>{ze.current?(ze.current=!1,history.back()):vt(Ln(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ee)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),gi(),()=>{document.body.classList.remove("full-view"),gi()}},[Ee]),b.useEffect(()=>{if(!Ee)return;const ie=Ne=>{Ne.key==="Escape"&&!mt&&bt()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ee,mt,bt]);const Vt=b.useRef(!1);b.useEffect(()=>{Ee?Dt.current?.focus():Vt.current&&Zt.current?.focus(),Vt.current=Ee},[Ee]);const{data:_n}=mE(l?.id,i&&!!l),Et=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),En=Z?(_n||[]).filter(ie=>ie.path===M):[],{data:pr}=nt({queryKey:["desktop-status"],queryFn:()=>Qe("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),rn=t.desktop&&l?pr?.mounts.find(ie=>ie.project===l.id)?.server:void 0,Nn=b.useCallback(async()=>{if(!rn)return;const ie=rn+window.location.pathname,Ne=await On(ie);ke(Ne?"Web link copied":ie,!Ne)},[rn]),gr=!ht&&i&&!!l,Jn=!ht&&Z&&!r.view,Kr=!ht&&Z,_i=Kr&&!P_.test(M)&&!id.test(M)&&!Lr.test(M),es=Kr&&!id.test(M)&&!dt,an=!ht&&(Z||i&&!!l&&U),kn=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Gs=!Lr.test(M),Ao=Eo(n,M,L)+"&print=1",Do=b.useCallback(()=>{Ze(!1),Gs?window.print():nn.current?.click()},[Gs]),zo=b.useCallback(async()=>{try{const ie=await Rf(Eo(n,M,L));if(ie.kind!=="text")return ke(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ne=await On(ie.text);ke(Ne?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ne)}catch(ie){ke("Copy failed: "+ie.message,!0)}},[n,M,L]),Ei=b.useCallback(()=>ve(!0),[]),[Da,Ni]=b.useState(""),ms=i&&!!l&&Fn(l?.perm,"write"),Zr=b.useCallback(async(ie,Ne,Le)=>{if(await or("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(Le?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){Ni(ie+Ne);try{await Sn(n+"restore",{path:ie,sha:Ne}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Restored "+ie+" — it syncs to every device like any other change.")}catch(lt){ke("Restore failed: "+lt.message,!0)}finally{Ni("")}}},[n,f]),[za,vr]=b.useState(""),Lt=b.useCallback(async ie=>{if(await or("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){vr(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),ke("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ne){ke("Remove failed: "+Ne.message,!0)}finally{vr("")}}},[n,f]),[yc,Lo]=b.useState(""),yr=b.useCallback(async ie=>{const Ne=ie.session||ie.note,Le=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};Lo(Ne);try{const lt=await Sn(n+"undo-run",{...Le,preview:!0}),$t=new Set(lt.changed_after);if(!lt.undone.length){ke("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await or("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ne," — ",lt.undone.length," file",lt.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:lt.undone.map(Ds=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Ds.path}),$t.has(Ds.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Ds.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Ds.path))}),$t.size>0&&o.jsxs("div",{className:"undo-warn",children:[$t.size," file",$t.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",$t.size===1?"that change":"those changes"," too."]}),lt.skipped.length>0&&o.jsxs("div",{children:[lt.skipped.length," already hold",lt.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),lt.refused.length>0&&o.jsxs("div",{children:[lt.refused.length," path",lt.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",lt.refused.join(", "),"."]})]}),"Undo run",!0))return;const ps=await Sn(n+"undo-run",Le);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Ys=ps.skipped.length?`, skipped ${ps.skipped.length} (already current)`:"";ke(`Undid ${ps.undone.length} file${ps.undone.length===1?"":"s"}${Ys}.`)}catch(lt){ke("Undo failed: "+lt.message,!0)}finally{Lo("")}},[n,f]),Ts=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ne=>{(Ne.metaKey||Ne.ctrlKey)&&Ne.key.toLowerCase()==="k"&&(Ne.preventDefault(),Fe(""),Je(Le=>!Le))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const zf=b.useCallback(()=>{const ie=[],Ne=Le=>ie.push(Le);if(i&&l){const Le=l.id,lt=Zs=>()=>{e.onClosePanel?.(),vt(Zs)};Ne({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:lt("/"+Le)});const $t=(Zs,ps,Ys)=>Ne({icon:Zs,label:ps,kind:"page",group:"Go to",run:lt(Ys)});$t("activity","Activity",dn("history",Le)),$t("insights","Insights",dn("dashboard",Le)),$t("gear","Settings",dn("settings",Le)),$t("laptop","Connect a device",dn("install",Le))}if(i&&l&&M){const Le=M.slice(M.lastIndexOf("/")+1),lt=($t,Zs,ps)=>Ne({icon:$t,label:Zs,hint:Le,kind:"action",group:Le,run:ps});sn&<("share","Share",Ei),lt("hist","History",Ts),Z&<("download","Download",()=>it.current?.click()),es&<("printer","Print",Do),_i&<("copy","Copy",zo)}if(i)for(const Le of e.projects||[])(!l||Le.id!==l.id)&&Ne({icon:"folder",label:Le.name,kind:"project",group:"Projects",run:()=>vt("/"+Le.id)});t.auth?.enabled&&Ne({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const Le of y.keys())Ne({icon:"folder",label:Le,kind:"folder",run:()=>I(Le)});for(const Le of m)qr(Le.path)||Ne({icon:"doc",label:Le.path,kind:"file",run:()=>I(Le.path)});return ie},[i,l,M,Z,sn,_i,es,t.auth?.enabled,y,m,e.projects,e.onClosePanel,Ei,zo,Do,Ts,I]),$o=RN(i?l?.id:void 0),xc=b.useMemo(()=>$o.map(ie=>ie.path).filter(ie=>ie!==M),[$o,M]),on=i?l?.id:void 0;b.useEffect(()=>{if(!on)return;const ie=()=>mU(on);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[on]);const La=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{on&&La&&pU(on)},[on,La]);const $a=sy(on),ts=b.useMemo(()=>hH(h,$a),[h,$a]),Rn=vU(on),Fo=AU(n,!!on&&!!t.comments&&Rn.length>0),bc=b.useMemo(()=>({comments:Fo,conflicts:ts.conflicts}),[Fo,ts.conflicts]),Yr=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),wc=b.useCallback(ie=>Yr.has(ie)||y.has(ie),[Yr,y]),ki=b.useMemo(()=>[...y.keys()],[y]),{query:Sc}=oy(),ln=yU();b.useEffect(()=>yg,[]);const Fa=i&&!!l&&t.upload.enabled&&Fn(l.perm,"write"),Io=b.useCallback(ie=>!!l&&Fn(Ut(ie?ie+"/":"")??l.perm,"write"),[l,_]),Ia=b.useCallback(async ie=>{const Ne=(await Ql("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ne)return;const Le=(ie?ie+"/":"")+Ne;if(Yr.has(Le)||y.has(Le)){ke(Le+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(Le),""),await f.invalidateQueries({queryKey:["tree",n]}),vt(Ln(Le,l?.id,void 0,!1,!0)),ds()}catch(lt){ke("Could not create "+Le+": "+lt.message,!0)}},[n,Yr,y,l?.id,f]),Os=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Fa?Ia:void 0,canCreateIn:Io,pinned:on?ie=>ry(on).includes(ie):void 0,togglePin:on?ie=>W1(on,ie):void 0,copyPath:async ie=>{const Ne=await On(ie);ke(Ne?"Path copied":ie,!Ne)},copyShareLink:i&&l&&Fn(l.perm,"write")?async ie=>{const Ne=(_n||[]).find(Le=>Le.path===ie);if(Ne){const Le=await On(Ne.url);ke(Le?"Share link copied":Ne.url,!Le);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>vt(dn("dashboard",l.id,ie)):void 0,remove:ms?Lt:void 0}),[Fa,Ia,Io,on,i,l,_n,I,re,ms,Lt,e.onClosePanel]);b.useEffect(()=>{if(!Te)return;const ie=()=>Ze(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Te]);const Ri=b.useCallback(ie=>y.has(ie),[y]);let Ks="app",As,Hn;if(ht)Hn=ht.body;else if(r.view==="dashboard")Ks="wide",Hn=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?dn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Ri});else if(r.view==="history")Ks="wide",As="activity-page",Hn=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Ri,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:ms?{onRestore:Zr,busy:Da}:void 0,remove:ms?{onRemove:Lt,busy:za}:void 0,undoRun:ms?{onUndoRun:yr,busy:yc}:void 0,filters:r.filters,linkFor:(ie,Ne)=>Ln(ie,l?.id,Ne),onFilters:ie=>vt(dn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)Hn=oi.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(W)Hn=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)Hn=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Ks=Lr.test(M)||id.test(M)?"wide":"read",As="markdown",Ee&&!oi.test(M)&&(As+=" bleed");const ie=qr(M);Hn=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ne=>Ne.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ne=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:dt,editSource:Bs,me:Gr,commentable:Vn,flushRef:yt});return Vn?o.jsx(k7,{apiBase:n,path:M,framed:Lr.test(M),lines:!oi.test(M)&&!Lr.test(M)&&!U_.test(M),threads:Cn,focus:fe,onFocus:me,onOpenPanel:_e,picking:xe,onPicking:Se,children:Ne}):Ne})()]})}else R?(m.length>0&&(Ks="wide"),Hn=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):Hn=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(Hn=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),Hn]}));const jc=ht?ht.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!dt&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Ri):R?l.name:null,Cc=o.jsx(ci,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),Vn&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:z?`${z} open comment${z===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":Q,onClick:()=>X(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),z>0&&o.jsx("span",{className:"cm-count",children:z})]}),gr&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ts,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),An&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{dt||(jp(),gS(f,n,M))},onFocus:()=>{dt||(jp(),gS(f,n,M))},title:dt?"Stop editing":"Edit this file",onClick:async()=>{if(!dt){vt(Ln(M,l?.id,L,r.full,!0));return}const ie=Ln(M,l?.id,L,r.full,!1),Ne=window.location.pathname+window.location.search;let Le=!0;try{Le=await(yt.current?.()??Promise.resolve(!0))}catch{}Le&&window.location.pathname+window.location.search===Ne&&vt(ie)},children:[!dt&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:dt?"Done":"Edit"})]}),dt&&Lr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:Bs?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hs(ie=>!ie),children:Bs?"Edit page":"Edit source"}),sn&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:Ei,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),Jn&&o.jsx(Ie,{id:"full-btn",ref:Zt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:xt,children:o.jsx(ge,{name:"expand"})}),Kr&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:kn,ref:it,children:"Download"}),es&&!Gs&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Ao,ref:nn,children:"Print"}),an&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ze(!Te)},children:o.jsx(ge,{name:"dots"})}),Te&&o.jsxs("div",{id:"more-menu",role:"menu",children:[gr&&o.jsx("button",{className:"more-item",onClick:Ts,children:"History"}),Kr&&o.jsx("button",{className:"more-item",onClick:()=>it.current?.click(),children:"Download"}),es&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Do,children:"Print"}),rn&&o.jsx("button",{className:"more-item",onClick:Nn,children:"Copy web link"}),_i&&o.jsx("button",{className:"more-item",onClick:zo,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),vt(dn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(li,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Rn,badges:bc,onOpen:Os.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),Sc.trim()?o.jsx(CH,{query:Sc,dirs:ki,files:m,onOpen:Os.open}):o.jsxs(o.Fragment,{children:[on&&o.jsx(EH,{pins:Rn,badges:bc,exists:wc,currentPath:H,onOpen:Os.open,onUnpin:ie=>W1(on,ie)}),on&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(ln==="recent"?" on":""),id:"tree-sort-btn","aria-label":ln==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":ln==="recent",title:ln==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(ln==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Fa&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Ia(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Y,restricted:N,stats:ts,order:ln,actions:Os})]})]}),topbar:Cc,exit:Ee?o.jsxs("button",{id:"exit-full",ref:Dt,onClick:bt,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(go,{width:Ks,className:As,style:Ks==="read"&&rt!==null?{"--page-read":rt+"px"}:void 0,children:[!ht&&Z&&o.jsx(b7,{shares:En,canRevoke:!!l&&Fn(l.perm,"write"),onChanged:Et}),Hn,Ks==="read"&&o.jsx(SB,{width:rt,onChange:kt})]})}),je&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:_n||[],onChanged:Et,onOpenFolder:ie=>vt(Ln(ie,l.id)),onClose:()=>{ve(!1),Et()}}),Vn&&Q&&o.jsx(R7,{apiBase:n,path:M,threads:Cn,focus:fe,onFocus:me,onClose:()=>{X(!1),Se(!1)},framed:Lr.test(M),picking:xe,onPicking:Se,me:t.me?.email,admin:Fn(l?.perm,"admin")}),o.jsx(cq,{open:mt,onClose:()=>Je(!1),candidates:zf,recent:xc,initialQuery:Wn})]})}function kB({config:e}){const t=Ov(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Mv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?vt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),vt("/"+we.project.id+(he?"?connect=existing":"")),ke(`Created “${we.project.name}”.`)}catch(we){ke("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=Nv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);vt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,W=o.jsx(mf,{name:U,onHome:()=>vt("/"),beta:U==="BearDrive"}),Y=mn(),ae=(I,re)=>{re&&ke(re),yd(I).catch(()=>{}).finally(()=>Y.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),ds()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(li,{vault:W,topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(ri,{to:"/setup"});if(!M)return o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(ri,{to:S.view?dn(S.view,I,S.viewTarget,S.filters):Ln(S.path,I,S.version,S.full,S.editing)}):o.jsxs(li,{vault:W,projectsNav:o.jsx(mp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(ci,{}),children:[o.jsx(go,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",pf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...In("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),vt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(ri,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(ri,{to:dn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(ri,{to:dn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(ri,{to:Ln(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),vt(I==="home"?"/"+M.id:dn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),ds()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:W,projectsNav:o.jsx(mp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(Sv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),vt(dn("install",M.id)),ds()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(ke(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(ke("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(li,{vault:o.jsx(mf,{name:"BearDrive",beta:!0}),topbar:o.jsx(ci,{}),children:o.jsx(go,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Ov(),n=e.volume||"BearDrive",r=b.useMemo(()=>Mv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(ri,{to:Ln(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(mf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(li,{vault:o.jsx(mf,{name:"…",showSignout:!1}),topbar:o.jsx(ci,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Mv(t,"hub"),i=>oi.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Vg as H,VB as a,wg as b,qB as c,GB as d,Eo as e,Rf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,cy as s,ke as t,HB as w};
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=hn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DYK0viPg.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-x7yoZJb9.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(un=>{const jt=un.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const mn=uy(P.current),Nt=new Set;for(const un of B.remoteCursors()){const jt=H2(mn,un.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=hn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),mn=Se.current;if(ot.kind==="text"&&mn){const Nt=mn.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;try{await ot.saveNow()}catch{}return ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?ln("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=hn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=hn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
+`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=ln("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(ln("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(ln("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
+`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=hn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=hn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(ln("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),mn=b.useRef(null),Nt=b.useRef(null),un=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),nn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||nn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,nn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,sn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),dn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),rn=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!rn)return;const ie=rn+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[rn]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!nn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():mn.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",ln("history",ze)),Nn("insights","Insights",ln("dashboard",ze)),Nn("gear","Settings",ln("settings",ze)),Nn("laptop","Connect a device",ln("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(ln("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?ln("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(ln("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:nn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!nn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{nn||(Cp(),gS(f,n,M))},onFocus:()=>{nn||(Cp(),gS(f,n,M))},title:nn?"Stop editing":"Edit this file",onClick:async()=>{if(!nn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&un.current===ie)){un.current=ie;try{const Ee=$n(M,l?.id,L,r.full,!1),ze=window.location.pathname+window.location.search;let Qe=!0;try{Qe=await(ie?.()??Promise.resolve(!0))}catch{}if(!Qe||window.location.pathname+window.location.search!==ze)return;gt(Ee)}finally{un.current===ie&&(un.current=null)}}},children:[!nn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:nn?"Done":"Edit"})]}),nn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:mn,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),rn&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(ln("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:dn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:sn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:dn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),dn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=hn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?ln(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:ln(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:ln(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:ln(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(ln("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-UW7NkjEZ.js b/internal/webapp/static/assets/sharedfile-Bq16w-Wl.js
similarity index 77%
rename from internal/webapp/static/assets/sharedfile-UW7NkjEZ.js
rename to internal/webapp/static/assets/sharedfile-Bq16w-Wl.js
index 5c88924c..f52a64e2 100644
--- a/internal/webapp/static/assets/sharedfile-UW7NkjEZ.js
+++ b/internal/webapp/static/assets/sharedfile-Bq16w-Wl.js
@@ -1,17 +1,17 @@
-import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-CiZlXtW0.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){It(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const St=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&St(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=St(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=St(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=St(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),Sl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):Sl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class kl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},at=()=>{throw Ct("Unexpected case")},ui=Ct("Unexpected end of array"),fi=Ct("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=St(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,Se=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Gt;let bt;const Yl=()=>{if(bt===void 0)if(Gt){bt=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${Mr(t,"-")}`,n),bt.set(`-${Mr(t,"-")}`,n)}})):bt=rt();return bt},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),ki=e=>Ls("--"+e)||Rn(e)!==null,ql=ki("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!ki("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=Si?Ql:Zl,sc=Si?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,Ss=(e,t,n)=>St(e.next()*(n+1-t)+t),_i=(e,t,n)=>St(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
-`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&Se(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),Sc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const kc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=kc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const ke=G(e=>typeof e=="number"),Mi=G(e=>e===ke),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(ke,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(ke,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
-${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>Ss(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(Ss(t,Ur,On))).if(Un,(e,t)=>ge(t,ks(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rks(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,ks(t,[ke,Ie,Qn,Ni,nr,Kn,Oi(ke),Ii(Me("a","b","c"),ke)]))).if(Sc,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;r$i(tn(t),e),Tt=typeof document<"u"?document:{},Nc=e=>Tt.createElement(e),$c=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),iu=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const ou=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=Tt.ELEMENT_NODE,Jc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const Wc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Yc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=St((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==pt){const p=It(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const lu=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},Sa=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class ka{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new ka(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},cu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},au=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=It(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=St(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==gt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class hu extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const k=c.beforeState.get(w)||0,A=b-k;A>0&&en(f,w,k,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===pt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===pt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==pt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===pt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Ct("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ko=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
-`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==gt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof gt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case At:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case xt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case Y:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return ko(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Ct("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):ko(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(Sh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(kh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw yt()}mergeWith(t){return!1}write(t,n,s){throw yt()}integrate(t,n){throw yt()}}const sh=0;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class Y{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Y(this.key,this.value)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new Y(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new At(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,Sh=5,kh=6;class xt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new xt(this.type._copy())}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new xt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===gt||this.right&&this.right.constructor===gt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===gt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new gt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class pt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>It(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},St(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),Se(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}.
-${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),k=Q();_(k,Ce),H(k,ze(i,w)),Ds(this,B(k))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(Sa(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&k[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const k=h[w-1],A=f-d,O=A===-w||A!==w&&k[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const k=u[w],A=u[w+1];(k>y||A>b)&&p.push({aS:n+y,aE:n+k,bS:n+b,bE:n+A}),y=k+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(`
+import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-CCNmuVia.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const yt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&yt(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=yt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=yt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=yt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),kl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Et=e=>new Error(e),mt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},ui=Et("Unexpected end of array"),fi=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=yt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ki=typeof window<"u"&&typeof document<"u"&&!Gt;let St;const Yl=()=>{if(St===void 0)if(Gt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Mr(t,"-")}`,n),St.set(`-${Mr(t,"-")}`,n)}})):St=rt();return St},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),Si=e=>Ls("--"+e)||Rn(e)!==null,ql=Si("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!Si("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=ki?Ql:Zl,sc=ki?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,ks=(e,t,n)=>yt(e.next()*(n+1-t)+t),_i=(e,t,n)=>yt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){mt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),kc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const Se=G(e=>typeof e=="number"),Mi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}.
+${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>ks(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(ks(t,Ur,On))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,Ni,nr,Kn,Oi(Se),Ii(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;r$i(tn(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=yt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==gt){const p=At(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof Tt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=yt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==dt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Ct(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Ct(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Ct(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&en(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===gt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===gt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==gt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===gt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw mt()}clone(){throw mt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Et("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},ko=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},So=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
+`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==dt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof dt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return So(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):So(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw mt()}mergeWith(t){return!1}write(t,n,s){throw mt()}integrate(t,n){throw mt()}}const sh=0;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===dt||this.right&&this.right.constructor===dt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===dt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new dt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},yt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}.
+${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ce),H(S,ze(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&S[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(`
 `)||i[o.length]===`
-`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=_t(e,s),l=_t(t,s),c=_t(n,s),h=Et(o,i),a=[...Ue(h,Et(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,Et(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,k)=>b.slice(w,k).join(""),f=(b,w,k,A)=>{let O="",R=k;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,k);continue}const O=f(b,0,w,k),R=f(b,1,w,k);if(O===R){d+=O;continue}if(w===k){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,k),O,R,As):Jn(u(o,w,k),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(`
+`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),h=_t(o,i),a=[...Ue(h,_t(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,_t(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",R=S;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),R=f(b,1,w,S);if(O===R){d+=O;continue}if(w===S){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,S),O,R,As):Jn(u(o,w,S),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(`
 `)?e:e+`
 `;function Vo(e,t,n,s){let r=t.endsWith(`
 `);return r===e.endsWith(`
 `)&&(r=n.endsWith(`
 `)),s===""||r===s.endsWith(`
 `)?s:r?s+`
-`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function uu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(`
-`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,Yt),i=_t(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=k>0?p.charCodeAt(p.length-k):0;O>=56320&&O<=57343&&k--,b+=w,p=p.slice(w,p.length-k),y=y.slice(w,y.length-k),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=Et(_t(t,Yt),s),i=Ue(Et(_t(e,Yt),s),r),o=Ue(r,Et(_t(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(`
-`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",nu=32e3,su=32;function fu(e){const t=(g,S,m)=>Xh(e.path,g,S,m);let n=e.seed,s=e.baseSha;const r=(g,S)=>{n=g,i=S,ot(S);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const S=[];for(let m=g;m!==null&&S.length<4;m=m.prev)m.sent!==m.from&&!S.includes(m.sent)&&S.push(m.sent);return S.length?S:void 0},l=(g,S=tt)=>{const m=o(S);return i&&i===s&&n.length>nu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,k=null,A=null,O="",R=0;const N=(g=Date.now())=>{const S=Math.max(g,R+1e3);return R=S,Go(e.path,e.who||"browser",new Date(S))},F=new Map;let Kt=0,Ot=!1,ht=null,Fe=0,rs=!1,tt=null,kt=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>su&&Bt.shift())};let wt=!1,Be=null,Qt=0;const Ve=()=>{wt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,mt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},Sr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const S=L();if(S===g)return!0;const m=oi(S,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,W||a||w)return;const S=L();if(S===n&&!kt){$("clean");return}if($("saving"),e.onWriting?.(),Ot){if(k!==null&&A===S){if(await yn(S,O)==="stop")return;continue}Ot=!1}const m=c||h?await Ho(S):await Jo(S);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!kt?"clean":"dirty");return}}};let ft=!1;const Ho=async g=>{Lt=g,je=!1;let S;try{S=await bn(gn(e.path),g,s,ft)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(ft=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,ft=!1,Sr(),S.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,S.sha),e.onSaved?.(g),"done")},cs=async(g,S)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(S&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),S&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let S=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){S=m;break}if(tt=null,S){kt=!0;const m=t(S.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=S.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let S;const m=tt;try{tt={sent:g,from:n,prev:m},S=await Ht(jt,{...l(g,m),...ft?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return ft=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,ft=!1,Sr(),S.update&&x.applyRemoteUpdate(S.update),tt=null,kt=!1,a)return"stop";const I=t(g,S.text,L());return I.ok&&Rt(I.text)&&(je||r(S.text,S.sha)),e.onSaved?.(S.text),"done"};let W=null;const ee=g=>{W||f||!e.onShrinkRefused||($("error"),W={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const S=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(S,m);const C=!wt&&mt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&mt{if(!f)try{const S=await xr(Or(e.apiBase,e.path));if(f||S.kind!=="text")return;if(r(S.text,S.sha),Rt(S.text),W=null,a&&!u){if(await fe(!1),f)return;$(mt>=it&&!wt?"clean":"dirty");return}mt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{W=null}}},e.onShrinkRefused(W))};let dt=null;const Wo=()=>{dt&&clearTimeout(dt),dt=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},kr=async(g,S,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,S&&(s=S),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),S,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(k===null||A!==g)&&(k=N(),A=g);const m=k;O=S,Ot=!0;const I=await kr(g,S,m);return f?"stop":I?(wn(I.err),"stop"):(Ot=!1,A===g&&(k=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,S)=>{mt=Math.max(mt,g),is(S),!(f||u)&&(d=it-mt,e.onPending?.(d))},Yo=()=>{f||u||W||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(mt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const S=(async()=>{try{for(;!u&&!f&&!W&&mt{y=!1,k=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,kt=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||kt)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const S=x.text.toString(),m=t(n,S,g);if(m.ok)return hs(()=>x.applySplices(oi(S,m.text)));y=!0,(k===null||A!==g)&&(k=N(),A=g),b=!0;let I;try{I=await kr(g,s??"",k)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(k=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),mt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,S)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(S?.origin)){if($("dirty"),a){wt=!0,Be=m,Qt+=1,u||(it+=1,d=it-mt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,S,m)=>{if(m?.held)return r(g,S),"same";if(g===n||g===Lt)return ot(S),"same";const I=L();if(g===I)return r(g,S),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,S),wt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,S),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,S),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let Sn=null;const zo=()=>{if(!f){if(W)return Promise.resolve();if((a?u?wt:d>0:L()!==n)&&!ft&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(dt??void 0),dt=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!wt)return Promise.resolve();if(Sn)return Sn;const g=Qt;$("saving");const S=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(wt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(dt??void 0),dt=null,ee(L()),W))return;$(wt?"dirty":"clean")}finally{Sn=null}})();return Sn=S,S};let Ut=null;const kn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,S)=>{if(W)return;if(a){const T=!u&&d>0;if(!T&&!(u&&wt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),kn(V));return}if(y||Ot){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=k!==null&&A===g?k:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!kt)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!S){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){kn(m)(),f||(clearTimeout(dt??void 0),dt=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return kn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;Ot=!0;let Mt=k!==null&&A===g?k:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),k=Mt,A=g,br(Mt,g,m,lt=>{Ot=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(ft=!1,tt===j&&(tt=null),kt=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,ft,!0,!0).then(T=>{if(ft=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>W!==null,mayServerRefuseShrink:()=>W||f||ft||!e.onShrinkRefused||!s||s===eu?!1:a?n===""&&(wt||d>0):n===""&&(L()!==""||kt)||(c||h)&&L()!==n,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(dt??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,W?e.onShrinkWithdrawn?.(W):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,hu as U,cu as a,Sa as b,Ea as c,oi as d,au as e,Ps as f,ae as g,iu as h,vt as i,uu as m,fu as o,lu as r,ou as t};
+`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(`
+`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,Yt),i=bt(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,Yt),s),i=Ue(_t(bt(e,Yt),s),r),o=Ue(r,_t(bt(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(`
+`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",R=0;const N=(g=Date.now())=>{const k=Math.max(g,R+1e3);return R=k,Go(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,xt=!1,ht=null,Fe=0,rs=!1,tt=null,Ot=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let kt=!1,Be=null,Qt=0;const Ve=()=>{kt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,pt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},kr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const k=L();if(k===g)return!0;const m=oi(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=L();if(k===n&&!Ot){$("clean");return}if($("saving"),e.onWriting?.(),xt){if(S!==null&&A===k){if(await yn(k,O)==="stop")return;continue}xt=!1}const m=c||h?await Ho(k):await Jo(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!Ot?"clean":"dirty");return}}};let wt=!1;const Ho=async g=>{Lt=g,je=!1;let k;try{k=await bn(gn(e.path),g,s,wt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(wt=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,wt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){Ot=!0;const m=t(k.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...wt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return wt=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,wt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,Ot=!1,a)return"stop";const I=t(g,k.text,L());return I.ok&&Rt(I.text)&&(je||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ee=g=>{Y||f||!e.onShrinkRefused||($("error"),Y={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!kt&&pt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&pt{if(!f)try{const k=await xr(Or(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;$(pt>=it&&!kt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let ft=null;const Wo=()=>{ft&&clearTimeout(ft),ft=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},Sr=async(g,k,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=N(),A=g);const m=S;O=k,xt=!0;const I=await Sr(g,k,m);return f?"stop":I?(wn(I.err),"stop"):(xt=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(f||u)&&(d=it-pt,e.onPending?.(d))},Yo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const k=(async()=>{try{for(;!u&&!f&&!Y&&pt{y=!1,S=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,Ot=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||Ot)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(oi(k,m.text)));y=!0,(S===null||A!==g)&&(S=N(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if($("dirty"),a){kt=!0,Be=m,Qt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=L();if(g===I)return r(g,k),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,k),kt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,k),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let kn=null;const zo=()=>{if(!f){if(Y)return Promise.resolve();if((a?u?kt:d>0:L()!==n)&&!wt&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(ft??void 0),ft=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!kt)return Promise.resolve();if(kn)return kn;const g=Qt;$("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(kt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(ft??void 0),ft=null,ee(L()),Y))return;$(kt?"dirty":"clean")}finally{kn=null}})();return kn=k,k};let Ut=null;const Sn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&kt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),Sn(V));return}if(y||xt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!Ot)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){Sn(m)(),f||(clearTimeout(ft??void 0),ft=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return Sn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;xt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),S=Mt,A=g,br(Mt,g,m,lt=>{xt=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(wt=!1,tt===j&&(tt=null),Ot=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,wt,!0,!0).then(T=>{if(wt=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(ft??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,au as U,lu as a,ka as b,Ea as c,oi as d,cu as e,Ps as f,ae as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t};
diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html
index 40ad82b2..70d04ab7 100644
--- a/internal/webapp/static/index.html
+++ b/internal/webapp/static/index.html
@@ -9,7 +9,7 @@
 
 BearDrive
 
-  
+  
   
   
   

From a14f2a4fbb112350d1d69d08de7208069bcd6c2a Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Wed, 11 Nov 2026 23:13:29 +0900
Subject: [PATCH 10/34] fix(webapp): drain concurrent edits in saveNow and keep
 editor open on failure

---
 CHANGELOG.md                                  |   2 +-
 architecture/webapp-frontend.md               |   4 +-
 .../frontend/src/components/FileView.tsx      |  16 ++-
 .../webapp/frontend/src/lib/sharedfile.ts     | 134 +++++++++++-------
 .../src/lib/sharedfile_restore.test.ts        |  95 ++++++++++++-
 ...{Editor-DYK0viPg.js => Editor--_Kdbq8f.js} |   2 +-
 ...dit-x7yoZJb9.js => VisualEdit-DEcaIEmO.js} |   2 +-
 .../{index-CCNmuVia.js => index-COodWbrp.js}  |  28 ++--
 .../static/assets/sharedfile-BEKa8tPX.js      |  17 +++
 .../static/assets/sharedfile-Bq16w-Wl.js      |  17 ---
 internal/webapp/static/index.html             |   2 +-
 11 files changed, 225 insertions(+), 94 deletions(-)
 rename internal/webapp/static/assets/{Editor-DYK0viPg.js => Editor--_Kdbq8f.js} (99%)
 rename internal/webapp/static/assets/{VisualEdit-x7yoZJb9.js => VisualEdit-DEcaIEmO.js} (97%)
 rename internal/webapp/static/assets/{index-CCNmuVia.js => index-COodWbrp.js} (96%)
 create mode 100644 internal/webapp/static/assets/sharedfile-BEKa8tPX.js
 delete mode 100644 internal/webapp/static/assets/sharedfile-Bq16w-Wl.js

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 611c4706..6c9ee432 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +23,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root.
 - **`POST /api/p//ycollab/sync` merges browser edits into a room over HTTP.** A browser without a connected socket sends its Yjs state, or its text with the base it started from; `peek` reads the room without writing. The hub answers `ok` only after storage holds the edit, waiting up to 8 seconds (`ycollabSyncDurableWait`), including for the lease holder in another process; otherwise it returns `503` and the browser keeps its edits.
 - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict.
 - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op.
-- **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done waits for the save to settle before leaving, staying on the editor if a shrink confirmation opens. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element.
+- **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element.
 
 ## v0.18.9 — 2026-11-11
 
diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md
index 481fd1c7..7218825e 100644
--- a/architecture/webapp-frontend.md
+++ b/architecture/webapp-frontend.md
@@ -59,7 +59,7 @@ classDiagram
         +scroll restoration: contentRef, memo, goal from lib/scroll
         +fullscreen: body.full-view from route.full, Exit / Esc / Back
         +readWidth: dragged reading width, tab memory only
-        +Done: awaits editFlushRef (saveNow) until it settles, then leaves the editor
+        +Done: saves via editFlushRef (saveNow) before leaving; stays in the editor if the save fails or asks about a shrink
     }
     note for Browser "readWidth is the reading column's width as the reader drags it (components/WidthHandle.tsx), held in Browser's state and nowhere else: it follows the reader across files and in and out of fullscreen because Browser outlives both, and a reload or a new tab is the reset — no storage, by design. It reaches the DOM as ONE variable, --page-read on the .page element, so the file rail's placement arithmetic follows without its own rule. During a drag the handle writes that variable straight onto the element and commits to state only on release, so the file page is not re-rendered on every pointer move"
     note for Browser "Fullscreen is a QUERY PARAM on the file route (?full=1), for the reason ?v= is one: the first segment after the project id is reserved for view names, and a fullscreen file is the same page with different chrome. Two things the code forced: routeKey is withoutFull(useLocationPath()), because a ?full=1 push otherwise looks like a fresh route and arms a scroll goal of 0 — the reader is thrown to the top of the document the moment they ask for more of it; and the chrome is HIDDEN by a body class, never unmounted, so <article id=content> survives the toggle and keeps its scrollTop in both directions. display:none also takes the hidden controls out of the tab order and the accessibility tree together, which is what syncSidebarInert already encodes for the off-canvas sidebar. The Exit control is rendered by AppShell OUTSIDE the topbar it hides and painted over the content: the HTML sandbox is an opaque origin and the PDF viewer is the browser's own, so Esc can never reach the app from inside either one (BEA-195)"
@@ -232,7 +232,7 @@ classDiagram
     Browser --> components
     components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand)
     note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain 
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
-    note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow + askingShrink, and Done awaits it until the save settles before leaving; an open shrink question keeps the user in the editor"
+    note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow (Promise<boolean>) + askingShrink, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx
index 0d260ce8..031a2290 100644
--- a/internal/webapp/frontend/src/components/FileView.tsx
+++ b/internal/webapp/frontend/src/components/FileView.tsx
@@ -513,19 +513,21 @@ function EditView(props: Parameters[0]) {
   const { flushRef } = props;
   useEffect(() => {
     if (!flushRef) return;
-    /* Save and leave, once the save has settled — however long the hub
-       takes, since its answer may be a question (a shrink only it can see)
-       the user must answer here. Clean or a bystander settles at once, and a
-       failed request fails fast. */
+    /* Save and leave, only once everything typed is saved. A question the
+       user must answer (a shrink, however late the hub reports it) keeps
+       them here, and so does a save that failed: leaving would destroy the
+       only copy of the buffer and the retry that is still trying to land it.
+       Clean or a bystander settles at once. */
     const flush = async () => {
       const f = fileHandle.current;
       if (!f) return true;
+      let saved = false;
       try {
-        await f.saveNow();
+        saved = await f.saveNow();
       } catch {
-        // The editor's own teardown still sends what it holds.
+        return false;
       }
-      if (f.askingShrink()) return false;
+      if (!saved || f.askingShrink()) return false;
       void qc.invalidateQueries({ queryKey: ["render", apiBase, path] });
       void qc.invalidateQueries({ queryKey: ["text", fileURL] });
       return true;
diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts
index fb28928e..1338fc10 100644
--- a/internal/webapp/frontend/src/lib/sharedfile.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile.ts
@@ -87,7 +87,7 @@ export type SharedFile = {
   /** Force a save now, skipping the idle wait (Done, Mod-s). In a live room
       this hands the hub the room's state only when this tab has typing no
       snapshot carries yet; clean or a bystander, it sends nothing. */
-  saveNow(): Promise;
+  saveNow(): Promise;
   /** A shrink question is waiting on the user: leaving now would leave it
       unanswered (Done stays on the editor). */
   askingShrink(): boolean;
@@ -1239,61 +1239,99 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile {
   /* An explicit save (Done, Mod-s). In a live room idle typing never writes
      anything from here — the hub snapshots the room — but a user who asked to
      save and leave must not leave on a snapshot still pending: the room's
-     state goes to the hub, which answers only once storage holds it. Clean,
-     or a bystander: nothing to send. Concurrent calls share one request. */
-  let liveFlushing: Promise | null = null;
-  const saveNow = (): Promise => {
-    if (!gone) {
-      // The question is open: Done stays put until it is answered.
-      if (asking) return Promise.resolve();
-      /* A sharp shrink against what the file is known to hold needs the
-         user's word before any request: ask at once, so Done never waits on
-         the network (or times out past it) to learn what is known here. A
-         shrink only the hub can see (a `saved` that is not the whole file)
-         is still its 422, answered the same way. */
-      const wouldSend = hubHoldsIt ? (live ? localDirtyInRoom : pending > 0) : current() !== saved;
-      if (wouldSend && !confirmShrinkOnce && opts.onShrinkRefused && sharpShrink(byteLength(saved), byteLength(current()))) {
+     state goes to the hub, which answers only once storage holds it.
+
+     It sends until nothing is owed, so typing that lands while a pass is on
+     the wire is saved (and shrink-checked) by the next pass before it
+     answers. True: everything typed so far is saved and no question is open.
+     False: a question is open, or a pass failed and the buffer is still
+     unsaved — its retry stays armed, and Done stays on the editor. Clean, or
+     a bystander: true at once. Concurrent calls share one loop. */
+  const owesSave = (): boolean => {
+    if (gone) return false;
+    if (hubHoldsIt) return live ? localDirtyInRoom : offlineAckedSeq < offlineEditSeq;
+    return pendingJoin || stagingConflict || current() !== saved || roomNeedsFlush;
+  };
+  // A sharp shrink against what the file is known to hold is asked about
+  // before any request: the network is never waited on to learn it.
+  const askIfShrunk = (): boolean => {
+    if (confirmShrinkOnce || !opts.onShrinkRefused || !sharpShrink(byteLength(saved), byteLength(current()))) return false;
+    clearTimeout(shrinkTimer ?? undefined);
+    shrinkTimer = null;
+    askShrink(current());
+    return true;
+  };
+  // One live pass: the room's state to the hub, answered once storage holds it.
+  const flushLive = async (): Promise => {
+    const sentRoomSeq = localRoomSeq;
+    setState("saving");
+    try {
+      const out = await syncCollab(syncURL, { update: collab.encodeState() });
+      if (gone) return false;
+      if (out.update) collab.applyRemoteUpdate(out.update);
+      adopt(out.text, out.sha);
+      // Typing that landed while this was out is not in it: owed still.
+      roomHandedOver(sentRoomSeq);
+      setState(localDirtyInRoom ? "dirty" : "clean");
+      opts.onSaved?.(saved);
+      return true;
+    } catch (e) {
+      if (gone) return false;
+      /* The hub refused to write a document this much smaller than the
+         file without a word from the user: ask now (the caller stays put
+         until it is answered), rather than wait for the idle check. */
+      if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) {
         clearTimeout(shrinkTimer ?? undefined);
         shrinkTimer = null;
         askShrink(current());
-        return Promise.resolve();
+        if (asking) return false;
       }
+      // The room still holds every edit and the hub still snapshots it.
+      setState(localDirtyInRoom ? "dirty" : "clean");
+      return false;
     }
-    if (!hubHoldsIt) return save();
-    if (gone) return Promise.resolve();
-    if (!live) return pending > 0 ? flushOffline(false) : Promise.resolve();
-    if (!localDirtyInRoom) return Promise.resolve();
-    if (liveFlushing) return liveFlushing;
-    const sentRoomSeq = localRoomSeq;
-    setState("saving");
-    const run = (async () => {
-      try {
-        const out = await syncCollab(syncURL, { update: collab.encodeState() });
-        if (gone) return;
-        if (out.update) collab.applyRemoteUpdate(out.update);
-        adopt(out.text, out.sha);
-        // Typing that landed while this was out is not in it.
-        roomHandedOver(sentRoomSeq);
-        setState(localDirtyInRoom ? "dirty" : "clean");
-        opts.onSaved?.(saved);
-      } catch (e) {
-        if (gone) return;
-        /* The hub refused to write a document this much smaller than the
-           file without a word from the user: ask now (the caller stays put
-           until it is answered), rather than wait for the idle check. */
-        if (e instanceof HttpError && e.status === 422 && isShrinkRefusal(e)) {
-          clearTimeout(shrinkTimer ?? undefined);
-          shrinkTimer = null;
-          askShrink(current());
-          if (asking) return;
+  };
+  let explicitSaving: Promise | null = null;
+  const saveNow = (): Promise => {
+    if (explicitSaving) {
+      // Typing since the pass on the wire: the save loop sends it next.
+      if (saving) dirtyWhileSaving = true;
+      return explicitSaving;
+    }
+    if (gone || asking) return Promise.resolve(false);
+    if (!owesSave()) return Promise.resolve(true);
+    const p = (async (): Promise => {
+      while (!gone && !asking && owesSave()) {
+        if (askIfShrunk()) return false;
+        if (hubHoldsIt) {
+          if (live) {
+            if (!(await flushLive())) return false;
+            continue;
+          }
+          // flushOffline sends until every edit is acknowledged; stopping
+          // short of that is a failure (its retry is armed) or a question.
+          await flushOffline(false);
+          if (gone || asking || (!live && offlineAckedSeq < offlineEditSeq)) return false;
+          continue;
+        }
+        // Staging or solo. A pass that moved nothing failed (a 503, a
+        // refused park, a join still waiting): its retry is armed, and
+        // looping would only send it again now.
+        const beforeText = current();
+        const beforeSaved = saved;
+        const beforeFlush = roomNeedsFlush;
+        await save();
+        if (gone || asking) return false;
+        if (owesSave() && current() === beforeText && saved === beforeSaved && roomNeedsFlush === beforeFlush) {
+          return false;
         }
-        // The room still holds every edit and the hub still snapshots it.
-        setState(localDirtyInRoom ? "dirty" : "clean");
-      } finally {
-        liveFlushing = null;
       }
+      return !gone && !asking && !owesSave();
     })();
-    liveFlushing = run;
+    const run = p.finally(() => {
+      if (explicitSaving === run) explicitSaving = null;
+    });
+    explicitSaving = run;
     return run;
   };
 
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index 716b5221..a022ac28 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -248,7 +248,7 @@ test("staging checkpoint refused 503 once is retried until it saves", async () =
     assert.ok(connect.mock.callCount() > 0);
 
     buffer = "B\n";
-    await file.saveNow();
+    assert.equal(await file.saveNow(), false); // unsaved: Done stays on the editor
     assert.equal(sent.length, 1);
     assert.ok(sent[0].includes("ycollab/sync"));
     assert.equal(states.at(-1), "error");
@@ -260,6 +260,7 @@ test("staging checkpoint refused 503 once is retried until it saves", async () =
     assert.equal(sent.length, 2);
     same(savedTexts, ["B\n"]);
     assert.equal(states.at(-1), "clean");
+    assert.equal(await file.saveNow(), true); // nothing owed: no request
 
     // Saved: no further attempts.
     await advance(60_000);
@@ -1024,7 +1025,7 @@ for (const closeBeforeRetry of [false, true]) {
       await waitFor(() => assert.equal(solo, true));
 
       buffer = "B\n";
-      await file.saveNow();
+      assert.equal(await file.saveNow(), false); // the park failed: Done stays
       // The file refused it, the head clashes, and the park was refused.
       assert.equal(puts.length, 2);
       assert.ok(!puts[0].url.includes("bdrive-conflict"));
@@ -1057,6 +1058,8 @@ for (const closeBeforeRetry of [false, true]) {
       // Parked: nothing more is sent.
       await advance(60_000);
       assert.equal(puts.length, 3);
+      assert.equal(await file.saveNow(), true); // parked: nothing owed
+      assert.equal(puts.length, 3);
       file.destroy();
       assert.equal(puts.length, 3);
     } finally {
@@ -2330,6 +2333,94 @@ test("a live save the hub refuses 422 for a shrink only it can see asks, however
   }
 });
 
+/* Typing while Done's save is on the wire is saved — and shrink-checked —
+   before saveNow answers: a second pass sends it, or a shrink in it opens the
+   question (asked here in solo, refused by the hub in a live room), and
+   saveNow answers false so Done stays on the editor. */
+for (const mode of ["live", "solo"] as const) {
+  for (const followUp of ["typing", "shrink"] as const) {
+    test(`typing while saveNow is on the wire is saved before it answers (${mode}, ${followUp})`, async () => {
+      fakeTimers();
+      const h = await heldRoom(mode === "solo" ? { apiBase: "/api/" } : {});
+      try {
+        if (mode === "solo") await advance(0); // no room route: solo
+        else await h.goLive();
+        if (mode === "live") h.localEdit((t) => t.insert(t.length, "d\n"));
+        else h.state.buffer = "a\nb\nc\nd\n";
+        const gate = Promise.withResolvers();
+        h.net.hold = gate.promise;
+        let result: boolean | null = null;
+        void h.file.saveNow().then((r) => {
+          result = r;
+        });
+        await advance(0);
+        assert.equal(h.reqs.length, 1);
+
+        // Typed while the first pass is out.
+        if (followUp === "typing") {
+          if (mode === "live") h.localEdit((t) => t.insert(t.length, "e\n"));
+          else h.state.buffer = "a\nb\nc\nd\ne\n";
+        } else if (mode === "live") {
+          h.localEdit((t) => t.delete(0, t.length));
+          // The room's own answer carries the deletion, so only the hub can
+          // tell it is a shrink: it refuses the second pass.
+          h.net.status = 422;
+          h.net.error = JSON.stringify({ error: "this would empty the file", shrink: true });
+        } else h.state.buffer = "";
+        h.net.hold = null;
+        gate.resolve();
+        await advance(0);
+
+        if (followUp === "typing") {
+          assert.equal(result, true);
+          assert.equal(h.reqs.length, 2);
+          if (mode === "solo") assert.equal(h.reqs[1].body, "a\nb\nc\nd\ne\n");
+          assert.equal(h.states.at(-1), "clean");
+        } else {
+          assert.equal(result, false);
+          assert.equal(h.file.askingShrink(), true);
+          assert.equal(h.asks.length, 1);
+          assert.equal(h.reqs.length, mode === "live" ? 2 : 1); // solo asks before sending
+        }
+      } finally {
+        h.done();
+        realTimers();
+      }
+    });
+  }
+}
+
+/* A save that fails leaves the buffer unsaved: saveNow answers false (its
+   retry stays armed, Done stays on the editor), and true once a save lands. */
+for (const mode of ["live", "offline", "solo"] as const) {
+  test(`saveNow answers false while a save fails and true once one lands (${mode})`, async () => {
+    fakeTimers();
+    const h = await heldRoom(mode === "solo" ? { apiBase: "/api/" } : {});
+    try {
+      if (mode === "solo") await advance(0); // no room route: solo
+      else await h.goLive();
+      if (mode === "offline") h.c.onStatus("offline");
+      if (mode === "solo") h.state.buffer = "a\nb\nc\nd\n";
+      else h.localEdit((t) => t.insert(t.length, "d\n"));
+
+      h.net.status = 503;
+      h.net.error = "unavailable";
+      assert.equal(await h.file.saveNow(), false);
+      assert.equal(h.reqs.length, 1);
+
+      h.net.status = 200;
+      assert.equal(await h.file.saveNow(), true);
+      assert.equal(h.reqs.length, 2);
+      // Nothing owed now: true at once, nothing sent.
+      assert.equal(await h.file.saveNow(), true);
+      assert.equal(h.reqs.length, 2);
+    } finally {
+      h.done();
+      realTimers();
+    }
+  });
+}
+
 /* Keep, with the socket down, after Done asked about a sharp shrink: the
    deletion is queued in this tab's document, so putting the file's bytes
    back is an edit the room must get too — over HTTP at once, or, if that
diff --git a/internal/webapp/static/assets/Editor-DYK0viPg.js b/internal/webapp/static/assets/Editor--_Kdbq8f.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-DYK0viPg.js
rename to internal/webapp/static/assets/Editor--_Kdbq8f.js
index 3234f450..73e33284 100644
--- a/internal/webapp/static/assets/Editor-DYK0viPg.js
+++ b/internal/webapp/static/assets/Editor--_Kdbq8f.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-CCNmuVia.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-Bq16w-Wl.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-COodWbrp.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BEKa8tPX.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-x7yoZJb9.js b/internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
similarity index 97%
rename from internal/webapp/static/assets/VisualEdit-x7yoZJb9.js
rename to internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
index 65f88dea..e92ffff0 100644
--- a/internal/webapp/static/assets/VisualEdit-x7yoZJb9.js
+++ b/internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
@@ -1 +1 @@
-import{r as i,j as y,w as ge,a as me}from"./index-CCNmuVia.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-Bq16w-Wl.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit};
+import{r as i,j as y,w as ge,a as me}from"./index-COodWbrp.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-BEKa8tPX.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit};
diff --git a/internal/webapp/static/assets/index-CCNmuVia.js b/internal/webapp/static/assets/index-COodWbrp.js
similarity index 96%
rename from internal/webapp/static/assets/index-CCNmuVia.js
rename to internal/webapp/static/assets/index-COodWbrp.js
index f5e699fb..f716c5fb 100644
--- a/internal/webapp/static/assets/index-CCNmuVia.js
+++ b/internal/webapp/static/assets/index-COodWbrp.js
@@ -1,13 +1,13 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DYK0viPg.js","assets/sharedfile-Bq16w-Wl.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-x7yoZJb9.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor--_Kdbq8f.js","assets/sharedfile-BEKa8tPX.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DEcaIEmO.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1p||F[d]!==ne[p]){var ce=`
-`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{es=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?tt(c):""}function ot(s,a){switch(s.tag){case 26:case 27:case 5:return tt(s.type);case 16:return tt("Lazy");case 13:return s.child!==a&&a!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return tt("Activity");default:return""}}function mn(s){try{var a="",c=null;do a+=ot(s,c),c=s,s=s.return;while(s);return a}catch(d){return`
+`+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{es=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?tt(c):""}function ot(s,a){switch(s.tag){case 26:case 27:case 5:return tt(s.type);case 16:return tt("Lazy");case 13:return s.child!==a&&a!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return tt("Activity");default:return""}}function Yt(s){try{var a="",c=null;do a+=ot(s,c),c=s,s=s.return;while(s);return a}catch(d){return`
 Error generating stack: `+d.message+`
-`+d.stack}}var Nt=Object.prototype.hasOwnProperty,un=e.unstable_scheduleCallback,jt=e.unstable_cancelCallback,Lt=e.unstable_shouldYield,ts=e.unstable_requestPaint,At=e.unstable_now,nn=e.unstable_getCurrentPriorityLevel,ns=e.unstable_ImmediatePriority,hr=e.unstable_UserBlockingPriority,Hs=e.unstable_NormalPriority,ms=e.unstable_LowPriority,Tn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Ae,je=Math.log,_e=Math.LN2;function Ae(s){return s>>>=0,s===0?32:31-(je(s)/_e|0)|0}var Ke=256,Ct=262144,sn=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function dt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function Et(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $t(){var s=sn;return sn<<=1,(sn&62914560)===0&&(sn=4194304),s}function Hn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function vt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function dn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Lf=/[\n"\\]/g;function On(s){return s.replace(Lf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Bs(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+En(a)):s.value!==""+En(a)&&(s.value=""+En(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ti(s,C,En(a)):c!=null?Ti(s,C,En(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+En(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){ki(s);return}c=c!=null?""+En(c):"",a=a!=null?""+En(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),ki(s)}function Ti(s,a,c){a==="number"&&Ri(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Gs(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ff=!1;if(vr)try{var Ho={};Object.defineProperty(Ho,"passive",{get:function(){Ff=!0}}),window.addEventListener("test",Ho,Ho),window.removeEventListener("test",Ho,Ho)}catch{Ff=!1}var Zr=null,If=null,Cc=null;function wy(){if(Cc)return Cc;var s,a=If,c=a.length,d,p="value"in Zr?Zr.value:Zr.textContent,v=p.length;for(s=0;s=Go),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Di=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Di)return s==="compositionend"||!qf&&Ry(s,a)?(s=wy(),Cc=If=Zr=null,Di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Ri(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Ri(s.document)}return a}function Kf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=vr&&"documentMode"in document&&11>=document.documentMode,zi=null,Zf=null,Qo=null,Yf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Yf||zi==null||zi!==Ri(d)||(d=zi,"selectionStart"in d&&Kf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Qo&&Yo(Qo,d)||(Qo=d,d=vu(Zf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ze?(st=De,De=null):st=De.sibling;var ut=se(J,De,te[Ze],ue);if(ut===null){De===null&&(De=st);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=st}if(Ze===te.length)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;ZeZe?(st=De,De=null):st=De.sibling;var ga=se(J,De,ut.value,ue);if(ga===null){De===null&&(De=st);break}s&&De&&ga.alternate===null&&a(J,De),G=v(ga,G,Ze),ct===null?$e=ga:ct.sibling=ga,ct=ga,De=st}if(ut.done)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;!ut.done;Ze++,ut=te.next())ut=fe(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return it&&xr(J,Ze),$e}for(De=d(De);!ut.done;Ze++,ut=te.next())ut=oe(De,J,Ze,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ze:ut.key),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),it&&xr(J,Ze),$e}function bt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Za($e)===G.type){c(J,G.sibling),ue=p(G,te.props),nl(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ha(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=Dc(te.type,te.key,te.props,null,J.mode,ue),nl(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=nh(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Za(te),bt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if($e=Q(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return bt(J,G,Uc(te),ue);if(te.$$typeof===R)return bt(J,G,$c(J,te),ue);Vc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=th(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{tl=0;var $e=bt(J,G,te,ue);return Gi=null,$e}catch(De){if(De===Bi||De===Ic)throw De;var ct=rs(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Qa=d0(!0),f0=d0(!1),Jr=!1;function mh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ph(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ea(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function ta(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Ac(s),Yy(s,null,c),a}return Oc(s,d,a,c),Ac(s)}function sl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}function gh(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var vh=!1;function rl(){if(vh){var s=qi;if(s!==null)throw s}}function al(s,a,c,d){vh=!1;var p=s.updateQueue;Jr=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(nt&se)===se:(d&se)===se){se!==0&&se===Hi&&(vh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Pe=k;se=a;var bt=c;switch(Pe.tag){case 1:if(Oe=Pe.payload,typeof Oe=="function"){fe=Oe.call(bt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Pe.payload,se=typeof Oe=="function"?Oe.call(bt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:Jr=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ia|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,Lh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);ll(s,a,ce,cs(s))}else ll(s,a,d,cs(s))}catch(fe){ll(s,a,{then:function(){},status:"rejected",reason:fe},cs())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Dh(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),ll(s,a.next.queue,{},cs())}function zh(){return gn(_l)}function Z0(){return Bt().memoizedState}function Y0(){return Bt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=cs();s=ea(c);var d=ta(a,s,c);d!==null&&(Xn(d,a,c),sl(d,a,c)),a={cache:uh()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=cs();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Wc(s)?X0(a,c):(c=Jf(s,a,c,d),c!==null&&(Xn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=cs();ll(s,a,c,d)}function ll(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Wc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ss(k,C))return Oc(s,a,p,0),_t===null&&Tc(),!1}catch{}if(c=Jf(s,a,p,d),c!==null)return Xn(c,s,d),W0(c,a,d),!0}return!1}function Lh(s,a,c,d){if(d={lane:2,revertLane:mm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Wc(s)){if(a)throw Error(r(479))}else a=Jf(s,c,d,2),a!==null&&Xn(a,s,2)}function Wc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Zi=Bc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}var cl={readContext:gn,use:Zc,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};cl.useEffectEvent=Pt;var J0={readContext:gn,use:Zc,useCallback:function(s,a){return zn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Qc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Qc(4194308,4,s,a)},useInsertionEffect:function(s,a){Qc(4,2,s,a)},useMemo:function(s,a){var c=zn();a=a===void 0?null:a;var d=s();if(Xa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=zn();if(c!==void 0){var p=c(a);if(Xa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=zn();return s={current:s},a.memoizedState=s},useState:function(s){s=Rh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Oh,useDeferredValue:function(s,a){var c=zn();return Ah(c,s,a)},useTransition:function(){var s=Rh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),zn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=zn();if(it){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),_t===null)throw Error(r(349));(nt&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Qi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=zn(),a=_t.identifierPrefix;if(it){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Gc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[Ft]=a,v[_n]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&_r(a)}}return Rt(a),Qh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&_r(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ui(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[Ft]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Xr(a,!0)}else s=yu(s).createTextNode(d),s[Ft]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ui(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(is(a),a):(is(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ui(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(is(a),a):(is(a),null)}return is(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),su(a,a.updateQueue),Rt(a),null);case 4:return Se(),s===null&&ym(a.stateNode.containerInfo),Rt(a),null;case 10:return wr(a.type),Rt(a),null;case 19:if(D(qt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)dl(d,!1);else{if(Ut!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=qc(s),v!==null){for(a.flags|=128,dl(d,!1),s=v.updateQueue,a.updateQueue=s,su(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(qt,qt.current&1|2),it&&xr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&At()>lu&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304)}else{if(!p)if(s=qc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,su(a,s),dl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!it)return Rt(a),null}else 2*At()-d.renderingStartTime>lu&&c!==536870912&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=At(),s.sibling=null,c=qt.current,B(qt,p?c&1|2:c&1),it&&xr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return is(a),xh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&su(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Ka),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),wr(Yt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(rh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return wr(Yt),Se(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Me(a),null;case 31:if(a.memoizedState!==null){if(is(a),a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(is(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(qt),null;case 4:return Se(),null;case 10:return wr(a.type),null;case 22:case 23:return is(a),xh(),s!==null&&D(Ka),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return wr(Yt),null;case 25:return null;default:return null}}function jx(s,a){switch(rh(a),a.tag){case 3:wr(Yt),Se();break;case 26:case 27:case 5:Me(a);break;case 4:Se();break;case 31:a.memoizedState!==null&&is(a);break;case 13:is(a);break;case 19:D(qt);break;case 10:wr(a.type);break;case 22:case 23:is(a),xh(),s!==null&&D(Ka);break;case 24:wr(Yt)}}function fl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ra(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Wa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function hl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Xh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[_n]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&da(s.type)||s.tag===4}function Wh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&da(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Jh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Qe));else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Jh(s,a,c),s=s.sibling;s!==null;)Jh(s,a,c),s=s.sibling}function ru(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(ru(s,a,c),s=s.sibling;s!==null;)ru(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[Ft]=s,a[_n]=c}catch(v){pt(s,s.return,v)}}var Er=!1,Wt=!1,em=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,fn=null;function Vk(s,a){if(s=s.containerInfo,wm=_u,s=Uy(s),Kf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(Sm={focusedElem:s,selectionRange:c},_u=!1,fn=a;fn!==null;)if(a=fn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,fn=s;else for(;fn!==null;){switch(a=fn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[Ft]=s,Ht(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kbt&&(C=bt,bt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,bt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>bt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=om,om=null;var v=la,C=Tr;if(an=0,to=la=null,Tr=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,xl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=xs(c,a),a=Ph(s.stateNode,a,2),s=ta(s,a,2),s!==null&&(vt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(oa===null||!oa.has(d))){s=xs(c,s),c=ox(2),d=ta(a,c,2),d!==null&&(lx(c,d,a,s),vt(d,2),Ws(d));break}}a=a.return}}function dm(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(sm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,_t===s&&(nt&c)===c&&(Ut===4||Ut===3&&(nt&62914560)===nt&&300>At()-ou?(ft&2)===0&&no(s,0):rm|=c,eo===nt&&(eo=0)),Ws(s)}function ob(s,a){a===0&&(a=$t()),s=Va(s,a),s!==null&&(vt(s,a),Ws(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return un(s,a)}var mu=null,ro=null,fm=!1,pu=!1,hm=!1,ua=0;function Ws(s){s!==ro&&s.next===null&&(ro===null?mu=ro=s:ro=ro.next=s),pu=!0,fm||(fm=!0,tR())}function xl(s,a){if(!hm&&pu){hm=!0;do for(var c=!1,d=mu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=nt,v=Le(d,d===_t?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||dt(d,v)||(c=!0,db(d,v));d=d.next}while(c);hm=!1}}function eR(){lb()}function lb(){pu=fm=!1;var s=0;ua!==0&&dR()&&(s=ua);for(var a=At(),c=null,d=mu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?mu=p:c.next=p,p===null&&(ro=c)):(c=d,(s!==0||(v&3)!==0)&&(pu=!0)),d=p}an!==0&&an!==5||xl(s),ua!==0&&(ua=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=ao;if(d&&typeof a=="string"&&a){var p=On(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function bR(s){Or.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Or.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Or.L(s,a,c);var d=ao;if(d&&s&&a){var p='link[rel="preload"][as="'+On(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+On(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+On(c.imageSizes)+'"]')):p+='[href="'+On(s)+'"]';var v=p;switch(a){case"style":v=io(s);break;case"script":v=oo(s)}_s.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),_s.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(jl(v))||a==="script"&&d.querySelector(Cl(v))||(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function jR(s,a){Or.m(s,a);var c=ao;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+On(d)+'"][href="'+On(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=oo(s)}if(!_s.has(v)&&(s=g({rel:"modulepreload",href:s},a),_s.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Cl(v)))return}d=c.createElement("link"),yn(d,"link",s),Ht(d),c.head.appendChild(d)}}}function CR(s,a,c){Or.S(s,a,c);var d=ao;if(d&&s){var p=Gr(d).hoistableStyles,v=io(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(jl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=_s.get(v))&&Rm(s,c);var F=C=d.createElement("link");Ht(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,bu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Or.X(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Or.M(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?xu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=io(c.href),c=Gr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=io(c.href);var v=Gr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(jl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),_s.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},_s.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=oo(c),c=Gr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function io(s){return'href="'+On(s)+'"'}function jl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Ht(a),s.head.appendChild(a))}function oo(s){return'[src="'+On(s)+'"]'}function Cl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+On(c.href)+'"]');if(d)return a.instance=d,Ht(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Ht(d),yn(d,"style",p),bu(d,c.precedence,s),a.instance=d;case"stylesheet":p=io(c.href);var v=s.querySelector(jl(p));if(v)return a.state.loading|=4,a.instance=v,Ht(v),v;d=Ab(c),(p=_s.get(p))&&Rm(d,p),v=(s.ownerDocument||s).createElement("link"),Ht(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,bu(v,c.precedence,s),a.instance=v;case"script":return v=oo(c.src),(p=s.querySelector(Cl(v)))?(a.instance=p,Ht(p),p):(d=c,(p=_s.get(v))&&(d=g({},c),Mm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Ht(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,bu(d,c.precedence,s));return a.instance}function bu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=io(d.href),v=a.querySelector(jl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=Su.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Ht(v);return}v=a.ownerDocument||a,d=Ab(d),(p=_s.get(p))&&Rm(d,p),v=v.createElement("link"),Ht(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=Su.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Tm=0;function MR(s,a){return s.stylesheets&&s.count===0&&Cu(s,s.stylesheets),0Tm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ju=null;function Cu(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ju=new Map,a.forEach(TR,s),ju=null,Su.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=ju.get(s);if(c)var d=c.get(null);else{c=new Map,ju.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Pm.exports=XR(),Pm.exports}var JR=WR(),To=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends To{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fg=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ai=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Fn(){}function aM(e,t){return typeof e=="function"?e(t):e}function Rp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Sa(e,t){return typeof e=="function"?e(t):e}function us(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Ig(u,t.options))return!1}else if(!ql(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(di(t.options.mutationKey)!==di(l))return!1}else if(!ql(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ig(e,t){return(t?.queryKeyHashFn||di)(e)}function di(e){return JSON.stringify(e,(t,n)=>Mp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function ql(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ql(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Mp(e)&&Mp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ai.setTimeout(t,e)})}function Tp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pg=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ug(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Bl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Op(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var cn=fM(),hM=class extends To{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},gd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?gd.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Op(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Ap(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>Fg.isFocused()&&(e.networkMode==="always"||gd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Bl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rp(this.gcTime)&&(this.#e=ai.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Bl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ai.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Dp,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Dp(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Dp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Dp(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Tp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Fn).catch(Fn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>us(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Sa(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Ap&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Ap){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),cn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends To{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Op(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof us(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!pd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||Sa(this.options.staleTime,this.#t)!==Sa(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Fn)),t}#g(){this.#b();const e=Sa(this.options.staleTime,this.#t);if(Bl.isServer()||this.#s.isStale||!Rp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ai.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Bl.isServer()||us(this.options.enabled,this.#t)===!1||!Rp(this.#c)||this.#c===0)&&(this.#f=ai.setInterval(()=>{(this.options.refetchIntervalInBackground||Fg.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ai.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ai.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Tp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Tp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Vg(e,t),refetch:this.refetch,promise:this.#o,isEnabled:us(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Op();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),pd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){cn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return us(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&us(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&zp(e,t,t.refetchOnMount)}function zp(e,t,n){if(us(t.enabled,e)!==!1&&Sa(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vg(e,t)}return!1}function mw(e,t,n,r){return(e!==t||us(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vg(e,n)}function Vg(e,t){return us(t.enabled,e)!==!1&&e.isStaleByTime(Sa(t.staleTime,e))}function bM(e,t){return!pd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),cn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ou(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ou(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){cn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){cn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return cn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Fn))))}};function Ou(e){return e.options.scope?.id}var CM=class extends To{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),pd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&di(n.mutationKey)!==di(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){cn.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Ig(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){cn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){cn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){cn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){cn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Fg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Sa(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return cn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;cn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return cn.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=cn.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Fn).catch(Fn)}invalidateQueries(e,t={}){return cn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=cn.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Fn)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Fn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Sa(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Fn).catch(Fn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Fn).catch(Fn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(di(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ql(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(di(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{ql(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ig(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),hn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Ug(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Ug(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=hn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(cn.batchCalls(x)):Fn;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Bl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Fn).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function rt(e,t){return tj(e,XS)}function FM(e,t){const n=hn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(cn.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Fn)},[r]);if(i.error&&Ug(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function Hd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function qd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Hg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function Oo(e){const t=await e.text();throw new Hg(e.status,HM(e.status,t),t)}async function We(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&qd(),t.ok||await Oo(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&qd(),t.ok||await Oo(t),t}async function Jt(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await Oo(i),Hd(e,t),i.status===204?{}:i.json()}async function vd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&Hd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&qd(),n.ok||await Oo(n),Hd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&qd(),f.ok||await Oo(f),Hd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await Oo(l),await l.json()}let Lp=null;function GM(){Lp??=We("/api/config")}function KM(){return rt({queryKey:["config"],queryFn:async()=>{const e=Lp;Lp=null;const t=await(e??We("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var rc=VS();const ZM=PS(rc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Eo(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Au=="function"&&(i=Au(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Au=="function"&&(j=Au(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Zt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=No("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Au=Vd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=aT.reduce((e,t)=>{const n=No(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&rc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(lt.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Na(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Na(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=No(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Zt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=No(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Zt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?b.useLayoutEffect:()=>{},uT=Vd[" useInsertionEffect ".trim().toString()]||ar;function ac({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Tl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Tl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Tl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Tl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Tl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function ds(e){const[t,n]=b.useState(vT());return ar(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Pr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",$p="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,qg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Bd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(qg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Zt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=kT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Pr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const X=()=>j({});return document.addEventListener($p,X),()=>document.removeEventListener($p,X)},[]),o.jsx(lt.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Bd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(qg),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(lt.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(qg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Pr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Pr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent($p);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var qm="focusScope.autoFocusOnMount",Bm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",Bg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Pr(i),y=Pr(l),g=b.useRef(null),w=Zt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:xa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||xa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&xa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(qm,jw);f.addEventListener(qm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&xa(f))}return()=>{f.removeEventListener(qm,m),setTimeout(()=>{const _=new CustomEvent(Bm,jw);f.addEventListener(Bm,y),f.dispatchEvent(_),_.defaultPrevented||xa(S??document.body,{select:!0}),f.removeEventListener(Bm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&xa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&xa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(lt.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});Bg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function xa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Gd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?rc.createPortal(o.jsx(lt.div,{...r,ref:t}),u):null});Gd.displayName=LT;var Du=0,co=null;function dj(){b.useEffect(()=>{co||(co={start:Nw(),end:Nw()});const{start:e,end:t}=co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Du++,()=>{Du===1&&(co?.start.remove(),co?.end.remove(),co=null),Du=Math.max(0,Du-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),So="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
+`+d.stack}}var Nt=Object.prototype.hasOwnProperty,dn=e.unstable_scheduleCallback,jt=e.unstable_cancelCallback,Lt=e.unstable_shouldYield,ts=e.unstable_requestPaint,At=e.unstable_now,sn=e.unstable_getCurrentPriorityLevel,ns=e.unstable_ImmediatePriority,hr=e.unstable_UserBlockingPriority,Hs=e.unstable_NormalPriority,ms=e.unstable_LowPriority,Tn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Ae,je=Math.log,_e=Math.LN2;function Ae(s){return s>>>=0,s===0?32:31-(je(s)/_e|0)|0}var Ke=256,Ct=262144,rn=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function dt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function Et(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $t(){var s=rn;return rn<<=1,(rn&62914560)===0&&(rn=4194304),s}function Hn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function vt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function fn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Lf=/[\n"\\]/g;function On(s){return s.replace(Lf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Bs(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+En(a)):s.value!==""+En(a)&&(s.value=""+En(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ti(s,C,En(a)):c!=null?Ti(s,C,En(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+En(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){ki(s);return}c=c!=null?""+En(c):"",a=a!=null?""+En(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),ki(s)}function Ti(s,a,c){a==="number"&&Ri(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Gs(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ff=!1;if(vr)try{var Ho={};Object.defineProperty(Ho,"passive",{get:function(){Ff=!0}}),window.addEventListener("test",Ho,Ho),window.removeEventListener("test",Ho,Ho)}catch{Ff=!1}var Zr=null,If=null,Cc=null;function wy(){if(Cc)return Cc;var s,a=If,c=a.length,d,p="value"in Zr?Zr.value:Zr.textContent,v=p.length;for(s=0;s=Go),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Di=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Di)return s==="compositionend"||!qf&&Ry(s,a)?(s=wy(),Cc=If=Zr=null,Di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Ri(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Ri(s.document)}return a}function Kf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=vr&&"documentMode"in document&&11>=document.documentMode,zi=null,Zf=null,Qo=null,Yf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Yf||zi==null||zi!==Ri(d)||(d=zi,"selectionStart"in d&&Kf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Qo&&Yo(Qo,d)||(Qo=d,d=vu(Zf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ze?(st=De,De=null):st=De.sibling;var ut=se(J,De,te[Ze],ue);if(ut===null){De===null&&(De=st);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=st}if(Ze===te.length)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;ZeZe?(st=De,De=null):st=De.sibling;var ga=se(J,De,ut.value,ue);if(ga===null){De===null&&(De=st);break}s&&De&&ga.alternate===null&&a(J,De),G=v(ga,G,Ze),ct===null?$e=ga:ct.sibling=ga,ct=ga,De=st}if(ut.done)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;!ut.done;Ze++,ut=te.next())ut=fe(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return it&&xr(J,Ze),$e}for(De=d(De);!ut.done;Ze++,ut=te.next())ut=oe(De,J,Ze,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ze:ut.key),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),it&&xr(J,Ze),$e}function bt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Za($e)===G.type){c(J,G.sibling),ue=p(G,te.props),nl(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ha(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=Dc(te.type,te.key,te.props,null,J.mode,ue),nl(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=nh(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Za(te),bt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if($e=Q(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return bt(J,G,Uc(te),ue);if(te.$$typeof===R)return bt(J,G,$c(J,te),ue);Vc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=th(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{tl=0;var $e=bt(J,G,te,ue);return Gi=null,$e}catch(De){if(De===Bi||De===Ic)throw De;var ct=rs(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Qa=d0(!0),f0=d0(!1),Jr=!1;function mh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ph(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ea(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function ta(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Ac(s),Yy(s,null,c),a}return Oc(s,d,a,c),Ac(s)}function sl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}function gh(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var vh=!1;function rl(){if(vh){var s=qi;if(s!==null)throw s}}function al(s,a,c,d){vh=!1;var p=s.updateQueue;Jr=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(nt&se)===se:(d&se)===se){se!==0&&se===Hi&&(vh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Pe=k;se=a;var bt=c;switch(Pe.tag){case 1:if(Oe=Pe.payload,typeof Oe=="function"){fe=Oe.call(bt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Pe.payload,se=typeof Oe=="function"?Oe.call(bt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:Jr=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ia|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,Lh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);ll(s,a,ce,cs(s))}else ll(s,a,d,cs(s))}catch(fe){ll(s,a,{then:function(){},status:"rejected",reason:fe},cs())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Dh(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),ll(s,a.next.queue,{},cs())}function zh(){return gn(_l)}function Z0(){return Bt().memoizedState}function Y0(){return Bt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=cs();s=ea(c);var d=ta(a,s,c);d!==null&&(Xn(d,a,c),sl(d,a,c)),a={cache:uh()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=cs();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Wc(s)?X0(a,c):(c=Jf(s,a,c,d),c!==null&&(Xn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=cs();ll(s,a,c,d)}function ll(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Wc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ss(k,C))return Oc(s,a,p,0),_t===null&&Tc(),!1}catch{}if(c=Jf(s,a,p,d),c!==null)return Xn(c,s,d),W0(c,a,d),!0}return!1}function Lh(s,a,c,d){if(d={lane:2,revertLane:mm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Wc(s)){if(a)throw Error(r(479))}else a=Jf(s,c,d,2),a!==null&&Xn(a,s,2)}function Wc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Zi=Bc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}var cl={readContext:gn,use:Zc,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};cl.useEffectEvent=Pt;var J0={readContext:gn,use:Zc,useCallback:function(s,a){return zn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Qc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Qc(4194308,4,s,a)},useInsertionEffect:function(s,a){Qc(4,2,s,a)},useMemo:function(s,a){var c=zn();a=a===void 0?null:a;var d=s();if(Xa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=zn();if(c!==void 0){var p=c(a);if(Xa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=zn();return s={current:s},a.memoizedState=s},useState:function(s){s=Rh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Oh,useDeferredValue:function(s,a){var c=zn();return Ah(c,s,a)},useTransition:function(){var s=Rh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),zn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=zn();if(it){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),_t===null)throw Error(r(349));(nt&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Qi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=zn(),a=_t.identifierPrefix;if(it){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Gc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[Ft]=a,v[_n]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&_r(a)}}return Rt(a),Qh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&_r(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ui(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[Ft]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Xr(a,!0)}else s=yu(s).createTextNode(d),s[Ft]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ui(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(is(a),a):(is(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ui(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(is(a),a):(is(a),null)}return is(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),su(a,a.updateQueue),Rt(a),null);case 4:return Se(),s===null&&ym(a.stateNode.containerInfo),Rt(a),null;case 10:return wr(a.type),Rt(a),null;case 19:if(D(qt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)dl(d,!1);else{if(Ut!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=qc(s),v!==null){for(a.flags|=128,dl(d,!1),s=v.updateQueue,a.updateQueue=s,su(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(qt,qt.current&1|2),it&&xr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&At()>lu&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304)}else{if(!p)if(s=qc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,su(a,s),dl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!it)return Rt(a),null}else 2*At()-d.renderingStartTime>lu&&c!==536870912&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=At(),s.sibling=null,c=qt.current,B(qt,p?c&1|2:c&1),it&&xr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return is(a),xh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&su(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Ka),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),wr(Qt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(rh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return wr(Qt),Se(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Me(a),null;case 31:if(a.memoizedState!==null){if(is(a),a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(is(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(qt),null;case 4:return Se(),null;case 10:return wr(a.type),null;case 22:case 23:return is(a),xh(),s!==null&&D(Ka),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return wr(Qt),null;case 25:return null;default:return null}}function jx(s,a){switch(rh(a),a.tag){case 3:wr(Qt),Se();break;case 26:case 27:case 5:Me(a);break;case 4:Se();break;case 31:a.memoizedState!==null&&is(a);break;case 13:is(a);break;case 19:D(qt);break;case 10:wr(a.type);break;case 22:case 23:is(a),xh(),s!==null&&D(Ka);break;case 24:wr(Qt)}}function fl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ra(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Wa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function hl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Xh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[_n]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&da(s.type)||s.tag===4}function Wh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&da(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Jh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Qe));else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Jh(s,a,c),s=s.sibling;s!==null;)Jh(s,a,c),s=s.sibling}function ru(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(ru(s,a,c),s=s.sibling;s!==null;)ru(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[Ft]=s,a[_n]=c}catch(v){pt(s,s.return,v)}}var Er=!1,Jt=!1,em=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Vk(s,a){if(s=s.containerInfo,wm=_u,s=Uy(s),Kf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(Sm={focusedElem:s,selectionRange:c},_u=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[Ft]=s,Ht(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kbt&&(C=bt,bt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,bt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>bt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=om,om=null;var v=la,C=Tr;if(on=0,to=la=null,Tr=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,xl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=xs(c,a),a=Ph(s.stateNode,a,2),s=ta(s,a,2),s!==null&&(vt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(oa===null||!oa.has(d))){s=xs(c,s),c=ox(2),d=ta(a,c,2),d!==null&&(lx(c,d,a,s),vt(d,2),Ws(d));break}}a=a.return}}function dm(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(sm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,_t===s&&(nt&c)===c&&(Ut===4||Ut===3&&(nt&62914560)===nt&&300>At()-ou?(ft&2)===0&&no(s,0):rm|=c,eo===nt&&(eo=0)),Ws(s)}function ob(s,a){a===0&&(a=$t()),s=Va(s,a),s!==null&&(vt(s,a),Ws(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return dn(s,a)}var mu=null,ro=null,fm=!1,pu=!1,hm=!1,ua=0;function Ws(s){s!==ro&&s.next===null&&(ro===null?mu=ro=s:ro=ro.next=s),pu=!0,fm||(fm=!0,tR())}function xl(s,a){if(!hm&&pu){hm=!0;do for(var c=!1,d=mu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=nt,v=Le(d,d===_t?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||dt(d,v)||(c=!0,db(d,v));d=d.next}while(c);hm=!1}}function eR(){lb()}function lb(){pu=fm=!1;var s=0;ua!==0&&dR()&&(s=ua);for(var a=At(),c=null,d=mu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?mu=p:c.next=p,p===null&&(ro=c)):(c=d,(s!==0||(v&3)!==0)&&(pu=!0)),d=p}on!==0&&on!==5||xl(s),ua!==0&&(ua=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=ao;if(d&&typeof a=="string"&&a){var p=On(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function bR(s){Or.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Or.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Or.L(s,a,c);var d=ao;if(d&&s&&a){var p='link[rel="preload"][as="'+On(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+On(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+On(c.imageSizes)+'"]')):p+='[href="'+On(s)+'"]';var v=p;switch(a){case"style":v=io(s);break;case"script":v=oo(s)}_s.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),_s.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(jl(v))||a==="script"&&d.querySelector(Cl(v))||(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function jR(s,a){Or.m(s,a);var c=ao;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+On(d)+'"][href="'+On(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=oo(s)}if(!_s.has(v)&&(s=g({rel:"modulepreload",href:s},a),_s.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Cl(v)))return}d=c.createElement("link"),yn(d,"link",s),Ht(d),c.head.appendChild(d)}}}function CR(s,a,c){Or.S(s,a,c);var d=ao;if(d&&s){var p=Gr(d).hoistableStyles,v=io(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(jl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=_s.get(v))&&Rm(s,c);var F=C=d.createElement("link");Ht(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,bu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Or.X(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Or.M(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?xu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=io(c.href),c=Gr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=io(c.href);var v=Gr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(jl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),_s.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},_s.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=oo(c),c=Gr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function io(s){return'href="'+On(s)+'"'}function jl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Ht(a),s.head.appendChild(a))}function oo(s){return'[src="'+On(s)+'"]'}function Cl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+On(c.href)+'"]');if(d)return a.instance=d,Ht(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Ht(d),yn(d,"style",p),bu(d,c.precedence,s),a.instance=d;case"stylesheet":p=io(c.href);var v=s.querySelector(jl(p));if(v)return a.state.loading|=4,a.instance=v,Ht(v),v;d=Ab(c),(p=_s.get(p))&&Rm(d,p),v=(s.ownerDocument||s).createElement("link"),Ht(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,bu(v,c.precedence,s),a.instance=v;case"script":return v=oo(c.src),(p=s.querySelector(Cl(v)))?(a.instance=p,Ht(p),p):(d=c,(p=_s.get(v))&&(d=g({},c),Mm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Ht(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,bu(d,c.precedence,s));return a.instance}function bu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=io(d.href),v=a.querySelector(jl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=Su.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Ht(v);return}v=a.ownerDocument||a,d=Ab(d),(p=_s.get(p))&&Rm(d,p),v=v.createElement("link"),Ht(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=Su.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Tm=0;function MR(s,a){return s.stylesheets&&s.count===0&&Cu(s,s.stylesheets),0Tm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ju=null;function Cu(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ju=new Map,a.forEach(TR,s),ju=null,Su.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=ju.get(s);if(c)var d=c.get(null);else{c=new Map,ju.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Pm.exports=XR(),Pm.exports}var JR=WR(),To=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends To{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fg=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ai=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Fn(){}function aM(e,t){return typeof e=="function"?e(t):e}function Rp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Sa(e,t){return typeof e=="function"?e(t):e}function us(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Ig(u,t.options))return!1}else if(!ql(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(di(t.options.mutationKey)!==di(l))return!1}else if(!ql(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ig(e,t){return(t?.queryKeyHashFn||di)(e)}function di(e){return JSON.stringify(e,(t,n)=>Mp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function ql(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ql(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Mp(e)&&Mp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ai.setTimeout(t,e)})}function Tp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pg=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ug(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Bl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Op(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends To{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},gd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?gd.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Op(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Ap(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>Fg.isFocused()&&(e.networkMode==="always"||gd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Bl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rp(this.gcTime)&&(this.#e=ai.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Bl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ai.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Dp,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Dp(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Dp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Dp(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Tp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Fn).catch(Fn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>us(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Sa(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Ap&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Ap){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends To{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Op(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof us(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!pd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||Sa(this.options.staleTime,this.#t)!==Sa(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Fn)),t}#g(){this.#b();const e=Sa(this.options.staleTime,this.#t);if(Bl.isServer()||this.#s.isStale||!Rp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ai.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Bl.isServer()||us(this.options.enabled,this.#t)===!1||!Rp(this.#c)||this.#c===0)&&(this.#f=ai.setInterval(()=>{(this.options.refetchIntervalInBackground||Fg.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ai.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ai.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Tp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Tp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Vg(e,t),refetch:this.refetch,promise:this.#o,isEnabled:us(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Op();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),pd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return us(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&us(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&zp(e,t,t.refetchOnMount)}function zp(e,t,n){if(us(t.enabled,e)!==!1&&Sa(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vg(e,t)}return!1}function mw(e,t,n,r){return(e!==t||us(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vg(e,n)}function Vg(e,t){return us(t.enabled,e)!==!1&&e.isStaleByTime(Sa(t.staleTime,e))}function bM(e,t){return!pd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ou(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ou(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch(Fn))))}};function Ou(e){return e.options.scope?.id}var CM=class extends To{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),pd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&di(n.mutationKey)!==di(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Ig(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Fg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Sa(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Fn).catch(Fn)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Fn)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Fn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Sa(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Fn).catch(Fn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Fn).catch(Fn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(di(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ql(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(di(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{ql(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ig(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),mn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Ug(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Ug(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):Fn;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Bl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Fn).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function rt(e,t){return tj(e,XS)}function FM(e,t){const n=mn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Fn)},[r]);if(i.error&&Ug(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function Hd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function qd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Hg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function Oo(e){const t=await e.text();throw new Hg(e.status,HM(e.status,t),t)}async function We(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&qd(),t.ok||await Oo(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&qd(),t.ok||await Oo(t),t}async function en(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await Oo(i),Hd(e,t),i.status===204?{}:i.json()}async function vd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&Hd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&qd(),n.ok||await Oo(n),Hd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&qd(),f.ok||await Oo(f),Hd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await Oo(l),await l.json()}let Lp=null;function GM(){Lp??=We("/api/config")}function KM(){return rt({queryKey:["config"],queryFn:async()=>{const e=Lp;Lp=null;const t=await(e??We("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var rc=VS();const ZM=PS(rc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Eo(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Au=="function"&&(i=Au(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Au=="function"&&(j=Au(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Zt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=No("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Au=Vd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=aT.reduce((e,t)=>{const n=No(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&rc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(lt.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Na(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Na(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=No(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Zt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=No(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Zt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?b.useLayoutEffect:()=>{},uT=Vd[" useInsertionEffect ".trim().toString()]||ar;function ac({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Tl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Tl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Tl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Tl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Tl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function ds(e){const[t,n]=b.useState(vT());return ar(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Pr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",$p="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,qg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Bd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(qg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Zt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=kT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Pr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const X=()=>j({});return document.addEventListener($p,X),()=>document.removeEventListener($p,X)},[]),o.jsx(lt.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Bd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(qg),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(lt.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(qg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Pr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Pr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent($p);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var qm="focusScope.autoFocusOnMount",Bm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",Bg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Pr(i),y=Pr(l),g=b.useRef(null),w=Zt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:xa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||xa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&xa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(qm,jw);f.addEventListener(qm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&xa(f))}return()=>{f.removeEventListener(qm,m),setTimeout(()=>{const _=new CustomEvent(Bm,jw);f.addEventListener(Bm,y),f.dispatchEvent(_),_.defaultPrevented||xa(S??document.body,{select:!0}),f.removeEventListener(Bm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&xa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&xa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(lt.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});Bg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function xa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Gd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?rc.createPortal(o.jsx(lt.div,{...r,ref:t}),u):null});Gd.displayName=LT;var Du=0,co=null;function dj(){b.useEffect(()=>{co||(co={start:Nw(),end:Nw()});const{start:e,end:t}=co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Du++,()=>{Du===1&&(co?.start.remove(),co?.end.remove(),co=null),Du=Math.max(0,Du-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),So="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
   .`.concat(FT,` {
    overflow: hidden `).concat(r,`;
    padding-right: `).concat(f,"px ").concat(r,`;
@@ -47,12 +47,12 @@ Error generating stack: `+d.message+`
 `)},Rw=function(){var e=parseInt(document.body.getAttribute(So)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(So,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(So):document.body.setAttribute(So,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},Fp=!1;if(typeof window<"u")try{var zu=Object.defineProperty({},"passive",{get:function(){return Fp=!0,!0}});window.addEventListener("test",zu,zu),window.removeEventListener("test",zu,zu)}catch{Fp=!1}var uo=Fp?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},Lu=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return`
   .block-interactivity-`.concat(e,` {pointer-events: none;}
   .allow-interactivity-`).concat(e,` {pointer-events: all;}
-`)},pO=0,fo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],l=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=Lu(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return fO(Q,E,S,Q==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!fo.length||fo[fo.length-1]!==l)){var _="deltaY"in E?Tw(E):Lu(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=Lu(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,Lu(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return fo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,uo),document.addEventListener("touchmove",h,uo),document.addEventListener("touchstart",y,uo),function(){fo=fo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,uo),document.removeEventListener("touchmove",h,uo),document.removeEventListener("touchstart",y,uo)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Gg=b.forwardRef(function(e,t){return b.createElement(Kd,sr({},e,{ref:t,sideCar:yO}))});Gg.classNames=Kd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ho=new WeakMap,$u=new WeakMap,Fu={},Ym=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Fu[n]||(Fu[n]=new WeakMap);var l=Fu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(ho.get(w)||0)+1,E=(l.get(w)||0)+1;ho.set(w,S),l.set(w,E),u.push(w),S===1&&j&&$u.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Ym++,function(){u.forEach(function(g){var w=ho.get(g)-1,x=l.get(g)-1;ho.set(g,w),l.set(g,x),w||($u.has(g)||g.removeAttribute(r),$u.delete(g)),x||g.removeAttribute(n)}),Ym--,Ym||(ho=new WeakMap,ho=new WeakMap,$u=new WeakMap,Fu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Zd="Dialog",[wj]=Na(Zd),[SO,Vs]=wj(Zd),Kg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=ac({prop:r,defaultProp:i??!1,onChange:l,caller:Zd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:ds(),titleId:ds(),descriptionId:ds(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Kg.displayName=Zd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Sj,n),l=Zt(t,i.triggerRef);return o.jsx(lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Wg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Zg="DialogPortal",[CO,jj]=wj(Zg,{forceMount:void 0}),Yg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Zg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:u})}))})};Yg.displayName=Zg;var yd="DialogOverlay",Qg=b.forwardRef((e,t)=>{const n=jj(yd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(yd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Qg.displayName=yd;var _O=No("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(yd,n),l=_T(),u=Zt(t,l);return o.jsx(Gg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(lt.div,{"data-state":Wg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),ko="DialogContent",Xg=b.forwardRef((e,t)=>{const n=jj(ko,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(ko,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Xg.displayName=ko;var NO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(null),i=Zt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(ko,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(Bg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Bd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Wg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(_j,n);return o.jsx(lt.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Nj,n);return o.jsx(lt.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Rj,n);return o.jsx(lt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Wg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],ja=Math.min,$r=Math.max,xd=Math.round,Iu=Math.floor,Fr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return $r(e,ja(t,n))}function Ur(e,t){return typeof e=="function"?e(t):e}function Ca(e){return e.split("-")[0]}function Ao(e){return e.split("-")[1]}function Jg(e){return e==="x"?"y":"x"}function ev(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function tv(e){return Jg(rr(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ao(e),i=tv(e),l=ev(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=bd(u)),[u,bd(u)]}function AO(e){const t=bd(e);return[Ip(e),t,Ip(t)]}function Ip(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ao(e);let l=LO(Ca(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Ip)))),l}function bd(e){const t=Ca(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function wd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=tv(t),f=ev(u),h=Ca(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ao(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Ur(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=wd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=wd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ur(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=tv(i),j=ev(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=ja(g[_],U),X=ja(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Q),be=!h.arrow&&Ao(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ur(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ca(n),f=Ao(n),h=rr(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Ur(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ur(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=rr(i),x=Jg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ur(e,t),w={x:i,y:l},x=rr(u),j=Jg(x);let S=w[j],E=w[x];const _=Ur(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ca(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ur(e,t),h=await i.detectOverflow(t,f),m=Ca(n),y=Ao(n),g=rr(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=ja(x-h[j],E),R=ja(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*$r(h.left,h.right):M=x-2*$r(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Yd(){return typeof window<"u"}function Do(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Hr(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Yd()?e instanceof Node||e instanceof Jn(e).Node:!1}function lr(e){return Yd()?e instanceof Element||e instanceof Jn(e).Element:!1}function ka(e){return Yd()?e instanceof HTMLElement||e instanceof Jn(e).HTMLElement:!1}function Fw(e){return!Yd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Jn(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Do(e))}function Xd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ti=e=>!!e&&e!=="none";let Qm;function nv(e){const t=lr(e)?cr(e):e;return ti(t.transform)||ti(t.translate)||ti(t.scale)||ti(t.rotate)||ti(t.perspective)||!sv()&&(ti(t.backdropFilter)||ti(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=fi(e);for(;ka(t)&&!Gl(t);){if(nv(t))return t;if(Xd(t))return null;t=fi(t)}return null}function sv(){return Qm==null&&(Qm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Qm}function Gl(e){return/^(html|body|#document)$/.test(Do(e))}function cr(e){return Jn(e).getComputedStyle(e)}function Wd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fi(e){if(Do(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Hr(e);return Fw(t)?t.host:t}function zj(e){const t=fi(e);return Gl(t)?(e.ownerDocument||e).body:ka(t)&&Qd(t)?t:zj(t)}function Kl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Jn(i);if(l){const f=Pp(u);return t.concat(u,u.visualViewport||[],Qd(i)?i:[],f&&n?Kl(f):[])}else return t.concat(i,Kl(i,[],n))}function Pp(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=ka(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=xd(n)!==l||xd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function rv(e){return lr(e)?e:e.contextElement}function jo(e){const t=rv(e);if(!ka(t))return Fr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?xd(n.width):n.width)/r,f=(l?xd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Fr(0);function $j(e){const t=Jn(e);return!sv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Jn(e)}function hi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=rv(e);let u=Fr(1);t&&(r?lr(r)&&(u=jo(r)):u=jo(e));const f=tA(l,n,r)?$j(l):Fr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Jn(l),x=lr(r)?Jn(r):r;let j=w,S=Pp(j);for(;S&&x!==j;){const E=jo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Jn(S),S=Pp(j)}}return wd({width:y,height:g,x:h,y:m})}function Jd(e,t){const n=Wd(e).scrollLeft;return t?t.left+n:hi(Hr(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Jd(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Hr(r),f=t?Xd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Fr(1);const y=Fr(0),g=ka(r);if((g||!l)&&((Do(r)!=="body"||Qd(u))&&(h=Wd(r)),g)){const x=hi(r);m=jo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Fr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Wd(e),n=e.ownerDocument.body,r=$r(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=$r(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+Jd(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=$r(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Jn(e),l=Hr(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!sv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(Jd(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=hi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=jo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Hr(e));else if(lr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Kl(e,[],!1).filter(f=>lr(f)&&Do(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?fi(e):e;for(;lr(u)&&!Gl(u);){const f=cr(u),h=nv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=fi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Xd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Jn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=rv(e),y=i||l?[...m?Kl(m):[],...t?Kl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?hi(e):null;h&&E();function E(){const _=hi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},rd=CA?b.useLayoutEffect:_A;function Sd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Sd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!Sd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Wm(e){const t=b.useRef(e);return rd(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);Sd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Wm(h),X=Wm(i),Q=Wm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};X.current&&(V.platform=X.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!Sd(H.current,K)&&(H.current=K,rc.flushSync(()=>{g(K)}))})},[w,t,n,X,Q]);rd(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);rd(()=>(le.current=!0,()=>{le.current=!1}),[]),rd(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(lt.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,av="Popper",[Hj,ef]=Na(av),[$A,qj]=Hj(av),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=av;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Zt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&ov(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(lt.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var iv="PopperContent",[FA,IA]=Hj(iv),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(iv,n),[_,N]=b.useState(null),R=Zt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(UA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:Se,availableWidth:ve,availableHeight:Me})=>{const{width:Ye,height:ht}=Se.reference,tt=we.floating.style;tt.setProperty("--radix-popper-available-width",`${ve}px`),tt.setProperty("--radix-popper-available-height",`${Me}px`),tt.setProperty("--radix-popper-anchor-width",`${Ye}px`),tt.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=ov($),D=Pr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(lt.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=iv;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=ov(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function ov(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Jm=!1;function HA(){const[e,t]=b.useState(Jm);return b.useEffect(()=>{Jm||(Jm=!0,t(!0))},[]),e}var tC=Vd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,ep="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},ic="RovingFocusGroup",[Up,nC,ZA]=oj(ic),[YA,sC]=Na(ic,[ZA]),[QA,XA]=YA(ic),rC=b.forwardRef((e,t)=>o.jsx(Up.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Up.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=ic;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Zt(t,w),j=lj(l),[S,E]=ac({prop:u,defaultProp:f??null,onChange:h,caller:ic}),[_,N]=b.useState(!1),R=Pr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(ep,R),()=>H.removeEventListener(ep,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(lt.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(ep,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ds(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Up.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(lt.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Vp=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Vp,"ArrowRight"],rtl:[...Vp,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oc="Menu",[Zl,cD,uD]=oj(oc),[bi,tf]=Na(oc,[uD,ef,sC]),nf=ef(),cC=sC(),[dD,wi]=bi(oc),[fD,lc]=bi(oc),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=nf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Pr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=oc;var hD="MenuAnchor",lv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(Wj,{...i,...r,ref:t})});lv.displayName=hD;var cv="MenuPortal",[mD,dC]=bi(cv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=wi(cv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};fC.displayName=cv;var Ts="MenuContent",[pD,uv]=bi(Ts),hC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=wi(Ts,e.__scopeMenu),u=lc(Ts,e.__scopeMenu);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(dv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu);return o.jsx(dv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=No("MenuContent.ScrollLock"),dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=wi(Ts,n),_=lc(Ts,n),N=nf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Zt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),X=b.useRef(0),Q=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Gg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Q.current?.side&&OD(ee,Q.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:b.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(Bg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Yl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Ts;var xD="MenuGroup",fv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"group",...r,ref:t})});fv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{...r,ref:t})});mC.displayName=bD;var jd="MenuItem",Hw="menu.itemSelect",sf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=lc(jd,e.__scopeMenu),f=uv(jd,e.__scopeMenu),h=Zt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Vp.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});sf.displayName=jd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=uv(jd,n),f=cC(n),h=b.useRef(null),m=Zt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Zl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(lt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Yl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Yl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(sf,{role:"menuitemcheckbox","aria-checked":Cd(n)?"mixed":n,...i,ref:t,"data-state":mv(n),onSelect:Ue(i.onSelect,()=>r?.(Cd(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=bi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Pr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(fv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(sf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":mv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var hv="MenuItemIndicator",[wC,CD]=bi(hv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(hv,n);return o.jsx(dr,{present:r||Cd(l.checked)||l.checked===!0,children:o.jsx(lt.span,{...i,ref:t,"data-state":mv(l.checked)})})});SC.displayName=hv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=bi(ND),$l="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=wi($l,e.__scopeMenu),r=lc($l,e.__scopeMenu),i=_C($l,e.__scopeMenu),l=uv($l,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Zt(t,i.onTriggerChange);return o.jsx(lv,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Yl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Yl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=$l;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=wi(Ts,e.__scopeMenu),f=lc(Ts,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Zt(t,m);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:o.jsx(dv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function Cd(e){return e==="indeterminate"}function mv(e){return Cd(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Yl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=lv,OC=fC,AC=hC,DC=fv,zC=mC,LC=sf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,rf="ContextMenu",[AD]=Na(rf,[tf]),Un=tf(),[DD,BC]=AD(rf),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=ac({prop:i,defaultProp:!1,onChange:r,caller:rf}),y=Un(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=rf;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Un(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(lt.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Pu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Pu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Pu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Pu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Pu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,af="DropdownMenu",[lz]=Na(af,[tf]),Vn=tf(),[cz,e_]=lz(af),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Vn(t),m=b.useRef(null),[y,g]=ac({prop:i,defaultProp:l??!1,onChange:u,caller:af});return o.jsx(cz,{scope:t,triggerId:ds(),triggerRef:m,contentId:ds(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=af;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Vn(n),f=Zt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(lt.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Vn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Vn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(lt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(lt.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[of]=Na("Tooltip",[ef]),lf=ef(),p_="TooltipProvider",Hz=700,Hp="tooltip.open",[qz,pv]=of(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Ql="Tooltip",[Bz,cc]=of(Ql),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=pv(Ql,e.__scopeTooltip),m=lf(t),[y,g]=b.useState(null),w=ds(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=ac({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Hp))):h.onClose(),l?.(L)},caller:Ql}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Ql;var qp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cc(qp,n),l=pv(qp,n),u=lf(n),f=b.useRef(null),h=Zt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(lt.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=qp;var gv="TooltipPortal",[Gz,Kz]=of(gv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=cc(gv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};x_.displayName=gv;var Ro="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(Ro,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=cc(Ro,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=cc(Ro,e.__scopeTooltip),r=pv(Ro,e.__scopeTooltip),i=b.useRef(null),l=Zt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=of(Ql,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=cc(Ro,n),m=lf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Hp,y),()=>document.removeEventListener(Hp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=Ro;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=lf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),_d="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(_d),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(_d):e.slice(t).join(_d),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];vv(i,n,r,t)}return n},vv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){vv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(_d),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},Bp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+Bp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],on=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,va=e=>A4.test(e),Xe=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),tp=e=>e.endsWith("%")&&Xe(e.slice(0,-1)),Ar=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),yv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Re(e)&&!Te(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ra(e,z_,yv),Re=e=>M_.test(e),ni=e=>Ra(e,L_,I4),Zw=e=>Ra(e,W4,Xe),B4=e=>Ra(e,F_,O_),G4=e=>Ra(e,$_,yv),Yw=e=>Ra(e,A_,yv),K4=e=>Ra(e,D_,U4),Uu=e=>Ra(e,I_,P4),Te=e=>T_.test(e),Ol=e=>Si(e,L_),Z4=e=>Si(e,$_),Qw=e=>Si(e,A_),Y4=e=>Si(e,z_),Q4=e=>Si(e,D_),Vu=e=>Si(e,I_,!0),X4=e=>Si(e,F_,!0),Ra=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Si=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=on("color"),t=on("font"),n=on("text"),r=on("font-weight"),i=on("tracking"),l=on("leading"),u=on("breakpoint"),f=on("container"),h=on("spacing"),m=on("radius"),y=on("shadow"),g=on("inset-shadow"),w=on("text-shadow"),x=on("drop-shadow"),j=on("blur"),S=on("perspective"),E=on("aspect"),_=on("ease"),N=on("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Te,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Te,Re,h],U=()=>[va,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Te,Re],X=()=>["auto",{span:["full",Js,Te,Re]},Js,Te,Re],Q=()=>[Js,"auto",Te,Re],ae=()=>["auto","min","max","fr",Te,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[va,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[va,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[va,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Te,Re],O=()=>[...T(),Qw,Yw,{position:[Te,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Te,Re]}],P=()=>[tp,Ol,ni],I=()=>["","none","full",m,Te,Re],re=()=>["",Xe,Ol,ni],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>[Xe,tp,Qw,Yw],ve=()=>["","none",j,Te,Re],Me=()=>["none",Xe,Te,Re],Ye=()=>["none",Xe,Te,Re],ht=()=>[Xe,Te,Re],tt=()=>[va,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ar],breakpoint:[Ar],color:[O_],container:[Ar],"drop-shadow":[Ar],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ar],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ar],shadow:[Ar],spacing:["px",Xe],text:[Ar],"text-shadow":[Ar],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",va,Re,Te,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Te,Re]}],"container-named":[H4],columns:[{columns:[Xe,Re,Te,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Te,Re]}],basis:[{basis:[va,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,va,"auto","initial","none",Re]}],grow:[{grow:["",Xe,Te,Re]}],shrink:[{shrink:["",Xe,Te,Re]}],order:[{order:[Js,"first","last","none",Te,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ol,ni]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tp,Re]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Te,Re]}],"line-clamp":[{"line-clamp":[Xe,"none",Te,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Te,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Te,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Te,ni]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Xe,"auto",Te,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Te,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Te,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Te,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Te,Re],radial:["",Te,Re],conic:[Js,Te,Re]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Te,Re]}],"outline-w":[{outline:["",Xe,Ol,ni]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Vu,Uu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Vu,Uu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Xe,ni]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Vu,Uu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Xe,Te,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Se()}],"mask-image-linear-to-pos":[{"mask-linear-to":Se()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":Se()}],"mask-image-t-to-pos":[{"mask-t-to":Se()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":Se()}],"mask-image-r-to-pos":[{"mask-r-to":Se()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":Se()}],"mask-image-b-to-pos":[{"mask-b-to":Se()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":Se()}],"mask-image-l-to-pos":[{"mask-l-to":Se()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":Se()}],"mask-image-x-to-pos":[{"mask-x-to":Se()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":Se()}],"mask-image-y-to-pos":[{"mask-y-to":Se()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Te,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":Se()}],"mask-image-radial-to-pos":[{"mask-radial-to":Se()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Se()}],"mask-image-conic-to-pos":[{"mask-conic-to":Se()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Te,Re]}],filter:[{filter:["","none",Te,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Xe,Te,Re]}],contrast:[{contrast:[Xe,Te,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Vu,Uu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Xe,Te,Re]}],"hue-rotate":[{"hue-rotate":[Xe,Te,Re]}],invert:[{invert:["",Xe,Te,Re]}],saturate:[{saturate:[Xe,Te,Re]}],sepia:[{sepia:["",Xe,Te,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Te,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Te,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Te,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Te,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Te,Re]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Te,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Te,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Te,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Te,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Te,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Te,Re]}],ease:[{ease:["linear","initial",_,Te,Re]}],delay:[{delay:[Xe,Te,Re]}],animate:[{animate:["none",N,Te,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Te,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Ye()}],"scale-x":[{"scale-x":Ye()}],"scale-y":[{"scale-y":Ye()}],"scale-z":[{"scale-z":Ye()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Te,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:tt()}],"translate-x":[{"translate-x":tt()}],"translate-y":[{"translate-y":tt()}],"translate-z":[{"translate-z":tt()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Te,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Te,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Te,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Xe,Ol,ni,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function at(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function cf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function uf({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function df({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:at("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Gp=new Set;function n3(e){return Gp.add(e),()=>Gp.delete(e)}function Co(e){for(const t of Gp)t(e)}const ii=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Dr=/\.html?$/i,ad=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Xl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function mi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Mn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Kp="(min-width: 1400px)";function ff(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function xv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var np={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...np,width:t??m??np.width,height:t??m??np.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],bv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],wv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=Sv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),pi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}pi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function fs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),pi(),e&&window.innerWidth<=Sv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const Sv=900;function pi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=Sv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Zp="bdrive.sidebarWidth",aE=210,iE=480;function id(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function sp(e){try{e===null?localStorage.removeItem(Zp):localStorage.setItem(Zp,String(e))}catch{}}const Yp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Yp(m.clientX-l),id(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&sp(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{id(null),sp(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Yp(u+l);id(f),sp(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Zp));e&&id(Yp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",pi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){fs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:bv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:wv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Qp={folder:bv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:wv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ci({name:e,className:t}){const n=e??"",r=Object.hasOwn(Qp,n)?Qp[n]:bv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function jv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function bo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&pi()}function oi(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:fs}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(Cv,{id:"rail-search",icon:"search",label:"Search",hint:Xl?"⌘K":"Ctrl+K",onClick:()=>Co()}),t]})}function Cv(e){return o.jsxs(cf,{delayDuration:100,children:[o.jsx(uf,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(df,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function hf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(jv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function li(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Xl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Xp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Xp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Xp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Wn=new xL,bL=(e,t)=>{const n=t?.id||Xp++;return Wn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Wn.toasts,CL=()=>Wn.getActiveToasts(),Ww=Object.assign(SL,{success:Wn.success,info:Wn.info,warning:Wn.warning,error:Wn.error,custom:Wn.custom,message:Wn.message,promise:Wn.promise,dismiss:Wn.dismiss,loading:Wn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Hu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function er(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[Se,ve]=ye.useState(!1),[Me,Ye]=ye.useState(!1),[ht,tt]=ye.useState(0),[es,Fe]=ye.useState(0),ot=ye.useRef(g.duration||Q||Jw),mn=ye.useRef(null),Nt=ye.useRef(null),un=_===0,jt=_+1<=S,Lt=g.type,ts=g.dismissible!==!1,At=g.className||"",nn=g.descriptionClassName||"",ns=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),hr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hs=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),ms=ye.useRef(0),Tn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,dt,Et)=>Et>=ns?Le:Le+dt.height,0),[E,ns]),xe=yL(),je=g.invert||y,_e=Lt==="loading";Tn.current=ye.useMemo(()=>ns*le+me,[ns,me]),ye.useEffect(()=>{ot.current=Hs},[Hs]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=Nt.current;if(Le){const dt=Le.getBoundingClientRect().height;return Fe(dt),j(Et=>[{toastId:g.id,height:dt,position:g.position},...Et]),()=>j(Et=>Et.filter($t=>$t.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=Nt.current,dt=Le.style.height;Le.style.height="auto";const Et=Le.getBoundingClientRect().height;Le.style.height=dt,Fe(Et),j($t=>$t.find(vt=>vt.toastId===g.id)?$t.map(vt=>vt.toastId===g.id?{...vt,height:Et}:vt):[{toastId:g.id,height:Et,position:g.position},...$t])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ae=ye.useCallback(()=>{re(!0),tt(Tn.current),j(Le=>Le.filter(dt=>dt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Tn]);ye.useEffect(()=>{if(g.promise&&Lt==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ae()},ot.current)),()=>clearTimeout(Le)},[R,x,g,Lt,xe,Ae]),ye.useEffect(()=>{g.delete&&(Ae(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ae,g.delete]);function Ke(){var Le;if(q?.loading){var dt;return ye.createElement("div",{className:er($?.loader,g==null||(dt=g.classNames)==null?void 0:dt.loader,"sonner-loader"),"data-visible":Lt==="loading"},q.loading)}return ye.createElement(fL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Lt==="loading"})}const Ct=g.icon||q?.[Lt]||uL(Lt);var sn,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:er(Z,At,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Lt],g==null||(n=g.classNames)==null?void 0:n[Lt]),"data-sonner-toast":"","data-rich-colors":(sn=g.richColors)!=null?sn:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Me,"data-removed":I,"data-visible":jt,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":un,"data-swiping":he,"data-dismissible":ts,"data-type":Lt,"data-invert":je,"data-swipe-out":Se,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Tn.current}px`,"--initial-height":be?"auto":`${es}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ts||(mn.current=new Date,tt(Tn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,dt,Et;if(Se||!ts)return;Y.current=null;const $t=Number(((Le=Nt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Hn=Number(((dt=Nt.current)==null?void 0:dt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vt=new Date().getTime()-((Et=mn.current)==null?void 0:Et.getTime()),dn=ee==="x"?$t:Hn,mr=Math.abs(dn)/vt;if(Math.abs(dn)>=ML||mr>.11){tt(Tn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?$t>0?"right":"left":Hn>0?"down":"up"),Ae(),ve(!0);return}else{var Cn,rn;(Cn=Nt.current)==null||Cn.style.setProperty("--swipe-amount-x","0px"),(rn=Nt.current)==null||rn.style.setProperty("--swipe-amount-y","0px")}Ye(!1),we(!1),K(null)},onPointerMove:Le=>{var dt,Et,$t;if(!Y.current||!ts||((dt=window.getSelection())==null?void 0:dt.toString().length)>0)return;const vt=Le.clientY-Y.current.y,dn=Le.clientX-Y.current.x;var mr;const Cn=(mr=e.swipeDirections)!=null?mr:OL(ae);!ee&&(Math.abs(dn)>1||Math.abs(vt)>1)&&K(Math.abs(dn)>Math.abs(vt)?"x":"y");let rn={x:0,y:0};const qr=qn=>1/(1.5+Math.abs(qn)/20);if(ee==="y"){if(Cn.includes("top")||Cn.includes("bottom"))if(Cn.includes("top")&&vt<0||Cn.includes("bottom")&&vt>0)rn.y=vt;else{const qn=vt*qr(vt);rn.y=Math.abs(qn)0)rn.x=dn;else{const qn=dn*qr(dn);rn.x=Math.abs(qn)0||Math.abs(rn.y)>0)&&Ye(!0),(Et=Nt.current)==null||Et.style.setProperty("--swipe-amount-x",`${rn.x}px`),($t=Nt.current)==null||$t.style.setProperty("--swipe-amount-y",`${rn.y}px`)}},hr&&!g.jsx&&Lt!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ts?()=>{}:()=>{Ae(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Lt||g.icon||g.promise)&&g.icon!==null&&(q?.[Lt]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||Ke():null,g.type!=="loading"?Ct:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,nn,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&Hu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{Hu(g.cancel)&&ts&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ae())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&Hu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{Hu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ae())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Wn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Wn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,Se)=>{var ve,Me;return ye.createElement(AL,{key:we.id,icons:T,index:Se,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Me=_?.closeButton)!=null?Me:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ye=>Ye.position==we.position),heights:Z.filter(Ye=>Ye.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Ed="bdrive-theme",Wp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function _v(){try{const e=localStorage.getItem(Ed);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function od(){const e=LL(_v()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Wp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Ed):localStorage.setItem(Ed,e)}catch{}od()}let t1=!1;function IL(){if(!t1){t1=!0,od();try{window.matchMedia(lE).addEventListener("change",()=>{_v()==="system"&&od()})}catch{}window.addEventListener("storage",e=>{(e.key===Ed||e.key===null)&&od()})}}function PL(e){return window.addEventListener(Wp,e),()=>window.removeEventListener(Wp,e)}function n1(){return`${_v()}:${$L()}`}function Ev(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=Ev();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:at(qL({variant:t,size:n,className:e})),...i})}function uc({...e}){return o.jsx(Kg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Yg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Qg,{"data-slot":"dialog-overlay",className:at("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function dc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Xg,{"data-slot":"dialog-content",className:at("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zo({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:at("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:at("text-sm text-muted-foreground",e),...t})}let uE=null,ld=[];function fc(e){uE=e,ld.forEach(t=>t())}function Wl(e,t,n="",r="OK",i={}){return new Promise(l=>fc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>fc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(ld.push(n),()=>{ld=ld.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{fc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(uc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(dc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{fc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{fc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let Nd=null,cd=[];const Nv=e=>{Nd=e,cd.forEach(t=>t())};function VB(e,t){Nv({...t,path:e,from:t})}function HB(e){Nd?.from===e&&Nv(null)}function XL(){const e=b.useSyncExternalStore(f=>(cd.push(f),()=>{cd=cd.filter(h=>h!==f)}),()=>Nd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),Nd===e&&Nv(null)}},u=()=>{l(e.keep)};return o.jsx(uc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(dc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:mi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":mi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>We("/api/projects")};function WL(e){return rt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=hn();return()=>e.fetchQuery(dE)}function fE(e){return rt({queryKey:["orgs"],queryFn:()=>We("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function kv(e){return rt({queryKey:["permissions",e],queryFn:()=>We(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return rt({queryKey:["folders",e],queryFn:()=>We(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return rt({queryKey:["shares",e],queryFn:()=>We(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return rt({queryKey:["admin","pending"],queryFn:()=>We("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=hn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function mf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Jp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Jp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Jp,e)?Jp[e]:void 0}const Rv=["q","user","actor","device","range","since","until"];function Mv(e){return!!e&&Rv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of Rv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Tv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of Rv){const y=r?.get(m);y&&(h[m]=y)}if(Mv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=mf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?mf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function $n(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function ln(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=mf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Ov="POP";const eg=new Set;function xE(){for(const e of eg)e()}window.addEventListener("popstate",()=>{Ov="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Ov=t?.replace?"REPLACE":"PUSH",xE())}function Av(){return b.useSyncExternalStore(e=>(eg.add(e),()=>{eg.delete(e)}),()=>location.pathname+location.search)}function c$(){return Ov}function Pn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function si({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function ba(e,t){return typeof e=="function"?e(t):e}function hs(e,t){return n=>{t.setState(r=>({...r,[e]:ba(n,r[e])}))}}function pf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return fO(Q,E,S,Q==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!fo.length||fo[fo.length-1]!==l)){var _="deltaY"in E?Tw(E):Lu(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=Lu(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,Lu(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return fo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,uo),document.addEventListener("touchmove",h,uo),document.addEventListener("touchstart",y,uo),function(){fo=fo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,uo),document.removeEventListener("touchmove",h,uo),document.removeEventListener("touchstart",y,uo)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Gg=b.forwardRef(function(e,t){return b.createElement(Kd,sr({},e,{ref:t,sideCar:yO}))});Gg.classNames=Kd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ho=new WeakMap,$u=new WeakMap,Fu={},Ym=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Fu[n]||(Fu[n]=new WeakMap);var l=Fu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(ho.get(w)||0)+1,E=(l.get(w)||0)+1;ho.set(w,S),l.set(w,E),u.push(w),S===1&&j&&$u.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Ym++,function(){u.forEach(function(g){var w=ho.get(g)-1,x=l.get(g)-1;ho.set(g,w),l.set(g,x),w||($u.has(g)||g.removeAttribute(r),$u.delete(g)),x||g.removeAttribute(n)}),Ym--,Ym||(ho=new WeakMap,ho=new WeakMap,$u=new WeakMap,Fu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Zd="Dialog",[wj]=Na(Zd),[SO,Vs]=wj(Zd),Kg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=ac({prop:r,defaultProp:i??!1,onChange:l,caller:Zd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:ds(),titleId:ds(),descriptionId:ds(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Kg.displayName=Zd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Sj,n),l=Zt(t,i.triggerRef);return o.jsx(lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Wg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Zg="DialogPortal",[CO,jj]=wj(Zg,{forceMount:void 0}),Yg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Zg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:u})}))})};Yg.displayName=Zg;var yd="DialogOverlay",Qg=b.forwardRef((e,t)=>{const n=jj(yd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(yd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Qg.displayName=yd;var _O=No("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(yd,n),l=_T(),u=Zt(t,l);return o.jsx(Gg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(lt.div,{"data-state":Wg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),ko="DialogContent",Xg=b.forwardRef((e,t)=>{const n=jj(ko,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(ko,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Xg.displayName=ko;var NO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(null),i=Zt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(ko,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(Bg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Bd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Wg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(_j,n);return o.jsx(lt.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Nj,n);return o.jsx(lt.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Rj,n);return o.jsx(lt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Wg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],ja=Math.min,$r=Math.max,xd=Math.round,Iu=Math.floor,Fr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return $r(e,ja(t,n))}function Ur(e,t){return typeof e=="function"?e(t):e}function Ca(e){return e.split("-")[0]}function Ao(e){return e.split("-")[1]}function Jg(e){return e==="x"?"y":"x"}function ev(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function tv(e){return Jg(rr(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ao(e),i=tv(e),l=ev(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=bd(u)),[u,bd(u)]}function AO(e){const t=bd(e);return[Ip(e),t,Ip(t)]}function Ip(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ao(e);let l=LO(Ca(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Ip)))),l}function bd(e){const t=Ca(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function wd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=tv(t),f=ev(u),h=Ca(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ao(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Ur(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=wd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=wd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ur(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=tv(i),j=ev(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=ja(g[_],U),X=ja(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Q),be=!h.arrow&&Ao(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ur(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ca(n),f=Ao(n),h=rr(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Ur(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ur(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=rr(i),x=Jg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ur(e,t),w={x:i,y:l},x=rr(u),j=Jg(x);let S=w[j],E=w[x];const _=Ur(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ca(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ur(e,t),h=await i.detectOverflow(t,f),m=Ca(n),y=Ao(n),g=rr(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=ja(x-h[j],E),R=ja(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*$r(h.left,h.right):M=x-2*$r(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Yd(){return typeof window<"u"}function Do(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Hr(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Yd()?e instanceof Node||e instanceof Jn(e).Node:!1}function lr(e){return Yd()?e instanceof Element||e instanceof Jn(e).Element:!1}function ka(e){return Yd()?e instanceof HTMLElement||e instanceof Jn(e).HTMLElement:!1}function Fw(e){return!Yd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Jn(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Do(e))}function Xd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ti=e=>!!e&&e!=="none";let Qm;function nv(e){const t=lr(e)?cr(e):e;return ti(t.transform)||ti(t.translate)||ti(t.scale)||ti(t.rotate)||ti(t.perspective)||!sv()&&(ti(t.backdropFilter)||ti(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=fi(e);for(;ka(t)&&!Gl(t);){if(nv(t))return t;if(Xd(t))return null;t=fi(t)}return null}function sv(){return Qm==null&&(Qm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Qm}function Gl(e){return/^(html|body|#document)$/.test(Do(e))}function cr(e){return Jn(e).getComputedStyle(e)}function Wd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fi(e){if(Do(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Hr(e);return Fw(t)?t.host:t}function zj(e){const t=fi(e);return Gl(t)?(e.ownerDocument||e).body:ka(t)&&Qd(t)?t:zj(t)}function Kl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Jn(i);if(l){const f=Pp(u);return t.concat(u,u.visualViewport||[],Qd(i)?i:[],f&&n?Kl(f):[])}else return t.concat(i,Kl(i,[],n))}function Pp(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=ka(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=xd(n)!==l||xd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function rv(e){return lr(e)?e:e.contextElement}function jo(e){const t=rv(e);if(!ka(t))return Fr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?xd(n.width):n.width)/r,f=(l?xd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Fr(0);function $j(e){const t=Jn(e);return!sv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Jn(e)}function hi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=rv(e);let u=Fr(1);t&&(r?lr(r)&&(u=jo(r)):u=jo(e));const f=tA(l,n,r)?$j(l):Fr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Jn(l),x=lr(r)?Jn(r):r;let j=w,S=Pp(j);for(;S&&x!==j;){const E=jo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Jn(S),S=Pp(j)}}return wd({width:y,height:g,x:h,y:m})}function Jd(e,t){const n=Wd(e).scrollLeft;return t?t.left+n:hi(Hr(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Jd(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Hr(r),f=t?Xd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Fr(1);const y=Fr(0),g=ka(r);if((g||!l)&&((Do(r)!=="body"||Qd(u))&&(h=Wd(r)),g)){const x=hi(r);m=jo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Fr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Wd(e),n=e.ownerDocument.body,r=$r(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=$r(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+Jd(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=$r(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Jn(e),l=Hr(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!sv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(Jd(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=hi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=jo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Hr(e));else if(lr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Kl(e,[],!1).filter(f=>lr(f)&&Do(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?fi(e):e;for(;lr(u)&&!Gl(u);){const f=cr(u),h=nv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=fi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Xd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Jn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=rv(e),y=i||l?[...m?Kl(m):[],...t?Kl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?hi(e):null;h&&E();function E(){const _=hi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},rd=CA?b.useLayoutEffect:_A;function Sd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Sd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!Sd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Wm(e){const t=b.useRef(e);return rd(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);Sd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Wm(h),X=Wm(i),Q=Wm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};X.current&&(V.platform=X.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!Sd(H.current,K)&&(H.current=K,rc.flushSync(()=>{g(K)}))})},[w,t,n,X,Q]);rd(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);rd(()=>(le.current=!0,()=>{le.current=!1}),[]),rd(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(lt.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,av="Popper",[Hj,ef]=Na(av),[$A,qj]=Hj(av),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=av;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Zt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&ov(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(lt.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var iv="PopperContent",[FA,IA]=Hj(iv),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(iv,n),[_,N]=b.useState(null),R=Zt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(UA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:Se,availableWidth:ve,availableHeight:Me})=>{const{width:Ye,height:ht}=Se.reference,tt=we.floating.style;tt.setProperty("--radix-popper-available-width",`${ve}px`),tt.setProperty("--radix-popper-available-height",`${Me}px`),tt.setProperty("--radix-popper-anchor-width",`${Ye}px`),tt.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=ov($),D=Pr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(lt.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=iv;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=ov(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function ov(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Jm=!1;function HA(){const[e,t]=b.useState(Jm);return b.useEffect(()=>{Jm||(Jm=!0,t(!0))},[]),e}var tC=Vd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,ep="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},ic="RovingFocusGroup",[Up,nC,ZA]=oj(ic),[YA,sC]=Na(ic,[ZA]),[QA,XA]=YA(ic),rC=b.forwardRef((e,t)=>o.jsx(Up.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Up.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=ic;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Zt(t,w),j=lj(l),[S,E]=ac({prop:u,defaultProp:f??null,onChange:h,caller:ic}),[_,N]=b.useState(!1),R=Pr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(ep,R),()=>H.removeEventListener(ep,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(lt.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(ep,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ds(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Up.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(lt.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Vp=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Vp,"ArrowRight"],rtl:[...Vp,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oc="Menu",[Zl,cD,uD]=oj(oc),[bi,tf]=Na(oc,[uD,ef,sC]),nf=ef(),cC=sC(),[dD,wi]=bi(oc),[fD,lc]=bi(oc),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=nf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Pr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=oc;var hD="MenuAnchor",lv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(Wj,{...i,...r,ref:t})});lv.displayName=hD;var cv="MenuPortal",[mD,dC]=bi(cv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=wi(cv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};fC.displayName=cv;var Ts="MenuContent",[pD,uv]=bi(Ts),hC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=wi(Ts,e.__scopeMenu),u=lc(Ts,e.__scopeMenu);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(dv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu);return o.jsx(dv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=No("MenuContent.ScrollLock"),dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=wi(Ts,n),_=lc(Ts,n),N=nf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Zt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),X=b.useRef(0),Q=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Gg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Q.current?.side&&OD(ee,Q.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:b.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(Bg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Yl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Ts;var xD="MenuGroup",fv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"group",...r,ref:t})});fv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{...r,ref:t})});mC.displayName=bD;var jd="MenuItem",Hw="menu.itemSelect",sf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=lc(jd,e.__scopeMenu),f=uv(jd,e.__scopeMenu),h=Zt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Vp.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});sf.displayName=jd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=uv(jd,n),f=cC(n),h=b.useRef(null),m=Zt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Zl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(lt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Yl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Yl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(sf,{role:"menuitemcheckbox","aria-checked":Cd(n)?"mixed":n,...i,ref:t,"data-state":mv(n),onSelect:Ue(i.onSelect,()=>r?.(Cd(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=bi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Pr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(fv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(sf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":mv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var hv="MenuItemIndicator",[wC,CD]=bi(hv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(hv,n);return o.jsx(dr,{present:r||Cd(l.checked)||l.checked===!0,children:o.jsx(lt.span,{...i,ref:t,"data-state":mv(l.checked)})})});SC.displayName=hv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=bi(ND),$l="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=wi($l,e.__scopeMenu),r=lc($l,e.__scopeMenu),i=_C($l,e.__scopeMenu),l=uv($l,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Zt(t,i.onTriggerChange);return o.jsx(lv,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Yl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Yl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=$l;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=wi(Ts,e.__scopeMenu),f=lc(Ts,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Zt(t,m);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:o.jsx(dv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function Cd(e){return e==="indeterminate"}function mv(e){return Cd(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Yl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=lv,OC=fC,AC=hC,DC=fv,zC=mC,LC=sf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,rf="ContextMenu",[AD]=Na(rf,[tf]),Un=tf(),[DD,BC]=AD(rf),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=ac({prop:i,defaultProp:!1,onChange:r,caller:rf}),y=Un(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=rf;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Un(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(lt.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Pu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Pu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Pu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Pu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Pu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,af="DropdownMenu",[lz]=Na(af,[tf]),Vn=tf(),[cz,e_]=lz(af),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Vn(t),m=b.useRef(null),[y,g]=ac({prop:i,defaultProp:l??!1,onChange:u,caller:af});return o.jsx(cz,{scope:t,triggerId:ds(),triggerRef:m,contentId:ds(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=af;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Vn(n),f=Zt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(lt.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Vn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Vn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(lt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(lt.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[of]=Na("Tooltip",[ef]),lf=ef(),p_="TooltipProvider",Hz=700,Hp="tooltip.open",[qz,pv]=of(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Ql="Tooltip",[Bz,cc]=of(Ql),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=pv(Ql,e.__scopeTooltip),m=lf(t),[y,g]=b.useState(null),w=ds(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=ac({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Hp))):h.onClose(),l?.(L)},caller:Ql}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Ql;var qp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cc(qp,n),l=pv(qp,n),u=lf(n),f=b.useRef(null),h=Zt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(lt.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=qp;var gv="TooltipPortal",[Gz,Kz]=of(gv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=cc(gv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};x_.displayName=gv;var Ro="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(Ro,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=cc(Ro,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=cc(Ro,e.__scopeTooltip),r=pv(Ro,e.__scopeTooltip),i=b.useRef(null),l=Zt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=of(Ql,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=cc(Ro,n),m=lf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Hp,y),()=>document.removeEventListener(Hp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=Ro;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=lf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),_d="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(_d),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(_d):e.slice(t).join(_d),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];vv(i,n,r,t)}return n},vv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){vv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(_d),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},Bp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+Bp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,va=e=>A4.test(e),Xe=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),tp=e=>e.endsWith("%")&&Xe(e.slice(0,-1)),Ar=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),yv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Re(e)&&!Te(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ra(e,z_,yv),Re=e=>M_.test(e),ni=e=>Ra(e,L_,I4),Zw=e=>Ra(e,W4,Xe),B4=e=>Ra(e,F_,O_),G4=e=>Ra(e,$_,yv),Yw=e=>Ra(e,A_,yv),K4=e=>Ra(e,D_,U4),Uu=e=>Ra(e,I_,P4),Te=e=>T_.test(e),Ol=e=>Si(e,L_),Z4=e=>Si(e,$_),Qw=e=>Si(e,A_),Y4=e=>Si(e,z_),Q4=e=>Si(e,D_),Vu=e=>Si(e,I_,!0),X4=e=>Si(e,F_,!0),Ra=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Si=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Te,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Te,Re,h],U=()=>[va,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Te,Re],X=()=>["auto",{span:["full",Js,Te,Re]},Js,Te,Re],Q=()=>[Js,"auto",Te,Re],ae=()=>["auto","min","max","fr",Te,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[va,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[va,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[va,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Te,Re],O=()=>[...T(),Qw,Yw,{position:[Te,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Te,Re]}],P=()=>[tp,Ol,ni],I=()=>["","none","full",m,Te,Re],re=()=>["",Xe,Ol,ni],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>[Xe,tp,Qw,Yw],ve=()=>["","none",j,Te,Re],Me=()=>["none",Xe,Te,Re],Ye=()=>["none",Xe,Te,Re],ht=()=>[Xe,Te,Re],tt=()=>[va,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ar],breakpoint:[Ar],color:[O_],container:[Ar],"drop-shadow":[Ar],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ar],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ar],shadow:[Ar],spacing:["px",Xe],text:[Ar],"text-shadow":[Ar],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",va,Re,Te,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Te,Re]}],"container-named":[H4],columns:[{columns:[Xe,Re,Te,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Te,Re]}],basis:[{basis:[va,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,va,"auto","initial","none",Re]}],grow:[{grow:["",Xe,Te,Re]}],shrink:[{shrink:["",Xe,Te,Re]}],order:[{order:[Js,"first","last","none",Te,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ol,ni]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tp,Re]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Te,Re]}],"line-clamp":[{"line-clamp":[Xe,"none",Te,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Te,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Te,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Te,ni]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Xe,"auto",Te,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Te,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Te,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Te,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Te,Re],radial:["",Te,Re],conic:[Js,Te,Re]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Te,Re]}],"outline-w":[{outline:["",Xe,Ol,ni]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Vu,Uu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Vu,Uu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Xe,ni]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Vu,Uu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Xe,Te,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Se()}],"mask-image-linear-to-pos":[{"mask-linear-to":Se()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":Se()}],"mask-image-t-to-pos":[{"mask-t-to":Se()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":Se()}],"mask-image-r-to-pos":[{"mask-r-to":Se()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":Se()}],"mask-image-b-to-pos":[{"mask-b-to":Se()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":Se()}],"mask-image-l-to-pos":[{"mask-l-to":Se()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":Se()}],"mask-image-x-to-pos":[{"mask-x-to":Se()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":Se()}],"mask-image-y-to-pos":[{"mask-y-to":Se()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Te,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":Se()}],"mask-image-radial-to-pos":[{"mask-radial-to":Se()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Se()}],"mask-image-conic-to-pos":[{"mask-conic-to":Se()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Te,Re]}],filter:[{filter:["","none",Te,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Xe,Te,Re]}],contrast:[{contrast:[Xe,Te,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Vu,Uu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Xe,Te,Re]}],"hue-rotate":[{"hue-rotate":[Xe,Te,Re]}],invert:[{invert:["",Xe,Te,Re]}],saturate:[{saturate:[Xe,Te,Re]}],sepia:[{sepia:["",Xe,Te,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Te,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Te,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Te,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Te,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Te,Re]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Te,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Te,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Te,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Te,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Te,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Te,Re]}],ease:[{ease:["linear","initial",_,Te,Re]}],delay:[{delay:[Xe,Te,Re]}],animate:[{animate:["none",N,Te,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Te,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Ye()}],"scale-x":[{"scale-x":Ye()}],"scale-y":[{"scale-y":Ye()}],"scale-z":[{"scale-z":Ye()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Te,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:tt()}],"translate-x":[{"translate-x":tt()}],"translate-y":[{"translate-y":tt()}],"translate-z":[{"translate-z":tt()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Te,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Te,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Te,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Xe,Ol,ni,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function at(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function cf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function uf({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function df({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:at("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Gp=new Set;function n3(e){return Gp.add(e),()=>Gp.delete(e)}function Co(e){for(const t of Gp)t(e)}const ii=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Dr=/\.html?$/i,ad=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Xl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function mi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Mn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Kp="(min-width: 1400px)";function ff(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function xv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var np={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...np,width:t??m??np.width,height:t??m??np.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],bv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],wv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=Sv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),pi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}pi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function fs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),pi(),e&&window.innerWidth<=Sv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const Sv=900;function pi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=Sv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Zp="bdrive.sidebarWidth",aE=210,iE=480;function id(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function sp(e){try{e===null?localStorage.removeItem(Zp):localStorage.setItem(Zp,String(e))}catch{}}const Yp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Yp(m.clientX-l),id(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&sp(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{id(null),sp(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Yp(u+l);id(f),sp(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Zp));e&&id(Yp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",pi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){fs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:bv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:wv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Qp={folder:bv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:wv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ci({name:e,className:t}){const n=e??"",r=Object.hasOwn(Qp,n)?Qp[n]:bv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function jv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function bo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&pi()}function oi(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:fs}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(Cv,{id:"rail-search",icon:"search",label:"Search",hint:Xl?"⌘K":"Ctrl+K",onClick:()=>Co()}),t]})}function Cv(e){return o.jsxs(cf,{delayDuration:100,children:[o.jsx(uf,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(df,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function hf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(jv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function li(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Xl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Xp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Xp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Xp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Wn=new xL,bL=(e,t)=>{const n=t?.id||Xp++;return Wn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Wn.toasts,CL=()=>Wn.getActiveToasts(),Ww=Object.assign(SL,{success:Wn.success,info:Wn.info,warning:Wn.warning,error:Wn.error,custom:Wn.custom,message:Wn.message,promise:Wn.promise,dismiss:Wn.dismiss,loading:Wn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Hu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function er(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[Se,ve]=ye.useState(!1),[Me,Ye]=ye.useState(!1),[ht,tt]=ye.useState(0),[es,Fe]=ye.useState(0),ot=ye.useRef(g.duration||Q||Jw),Yt=ye.useRef(null),Nt=ye.useRef(null),dn=_===0,jt=_+1<=S,Lt=g.type,ts=g.dismissible!==!1,At=g.className||"",sn=g.descriptionClassName||"",ns=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),hr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hs=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),ms=ye.useRef(0),Tn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,dt,Et)=>Et>=ns?Le:Le+dt.height,0),[E,ns]),xe=yL(),je=g.invert||y,_e=Lt==="loading";Tn.current=ye.useMemo(()=>ns*le+me,[ns,me]),ye.useEffect(()=>{ot.current=Hs},[Hs]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=Nt.current;if(Le){const dt=Le.getBoundingClientRect().height;return Fe(dt),j(Et=>[{toastId:g.id,height:dt,position:g.position},...Et]),()=>j(Et=>Et.filter($t=>$t.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=Nt.current,dt=Le.style.height;Le.style.height="auto";const Et=Le.getBoundingClientRect().height;Le.style.height=dt,Fe(Et),j($t=>$t.find(vt=>vt.toastId===g.id)?$t.map(vt=>vt.toastId===g.id?{...vt,height:Et}:vt):[{toastId:g.id,height:Et,position:g.position},...$t])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ae=ye.useCallback(()=>{re(!0),tt(Tn.current),j(Le=>Le.filter(dt=>dt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Tn]);ye.useEffect(()=>{if(g.promise&&Lt==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ae()},ot.current)),()=>clearTimeout(Le)},[R,x,g,Lt,xe,Ae]),ye.useEffect(()=>{g.delete&&(Ae(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ae,g.delete]);function Ke(){var Le;if(q?.loading){var dt;return ye.createElement("div",{className:er($?.loader,g==null||(dt=g.classNames)==null?void 0:dt.loader,"sonner-loader"),"data-visible":Lt==="loading"},q.loading)}return ye.createElement(fL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Lt==="loading"})}const Ct=g.icon||q?.[Lt]||uL(Lt);var rn,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:er(Z,At,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Lt],g==null||(n=g.classNames)==null?void 0:n[Lt]),"data-sonner-toast":"","data-rich-colors":(rn=g.richColors)!=null?rn:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Me,"data-removed":I,"data-visible":jt,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":dn,"data-swiping":he,"data-dismissible":ts,"data-type":Lt,"data-invert":je,"data-swipe-out":Se,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Tn.current}px`,"--initial-height":be?"auto":`${es}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ts||(Yt.current=new Date,tt(Tn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,dt,Et;if(Se||!ts)return;Y.current=null;const $t=Number(((Le=Nt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Hn=Number(((dt=Nt.current)==null?void 0:dt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vt=new Date().getTime()-((Et=Yt.current)==null?void 0:Et.getTime()),fn=ee==="x"?$t:Hn,mr=Math.abs(fn)/vt;if(Math.abs(fn)>=ML||mr>.11){tt(Tn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?$t>0?"right":"left":Hn>0?"down":"up"),Ae(),ve(!0);return}else{var Cn,an;(Cn=Nt.current)==null||Cn.style.setProperty("--swipe-amount-x","0px"),(an=Nt.current)==null||an.style.setProperty("--swipe-amount-y","0px")}Ye(!1),we(!1),K(null)},onPointerMove:Le=>{var dt,Et,$t;if(!Y.current||!ts||((dt=window.getSelection())==null?void 0:dt.toString().length)>0)return;const vt=Le.clientY-Y.current.y,fn=Le.clientX-Y.current.x;var mr;const Cn=(mr=e.swipeDirections)!=null?mr:OL(ae);!ee&&(Math.abs(fn)>1||Math.abs(vt)>1)&&K(Math.abs(fn)>Math.abs(vt)?"x":"y");let an={x:0,y:0};const qr=qn=>1/(1.5+Math.abs(qn)/20);if(ee==="y"){if(Cn.includes("top")||Cn.includes("bottom"))if(Cn.includes("top")&&vt<0||Cn.includes("bottom")&&vt>0)an.y=vt;else{const qn=vt*qr(vt);an.y=Math.abs(qn)0)an.x=fn;else{const qn=fn*qr(fn);an.x=Math.abs(qn)0||Math.abs(an.y)>0)&&Ye(!0),(Et=Nt.current)==null||Et.style.setProperty("--swipe-amount-x",`${an.x}px`),($t=Nt.current)==null||$t.style.setProperty("--swipe-amount-y",`${an.y}px`)}},hr&&!g.jsx&&Lt!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ts?()=>{}:()=>{Ae(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Lt||g.icon||g.promise)&&g.icon!==null&&(q?.[Lt]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||Ke():null,g.type!=="loading"?Ct:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,sn,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&Hu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{Hu(g.cancel)&&ts&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ae())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&Hu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{Hu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ae())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Wn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Wn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,Se)=>{var ve,Me;return ye.createElement(AL,{key:we.id,icons:T,index:Se,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Me=_?.closeButton)!=null?Me:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ye=>Ye.position==we.position),heights:Z.filter(Ye=>Ye.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Ed="bdrive-theme",Wp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function _v(){try{const e=localStorage.getItem(Ed);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function od(){const e=LL(_v()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Wp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Ed):localStorage.setItem(Ed,e)}catch{}od()}let t1=!1;function IL(){if(!t1){t1=!0,od();try{window.matchMedia(lE).addEventListener("change",()=>{_v()==="system"&&od()})}catch{}window.addEventListener("storage",e=>{(e.key===Ed||e.key===null)&&od()})}}function PL(e){return window.addEventListener(Wp,e),()=>window.removeEventListener(Wp,e)}function n1(){return`${_v()}:${$L()}`}function Ev(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=Ev();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:at(qL({variant:t,size:n,className:e})),...i})}function uc({...e}){return o.jsx(Kg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Yg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Qg,{"data-slot":"dialog-overlay",className:at("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function dc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Xg,{"data-slot":"dialog-content",className:at("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zo({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:at("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:at("text-sm text-muted-foreground",e),...t})}let uE=null,ld=[];function fc(e){uE=e,ld.forEach(t=>t())}function Wl(e,t,n="",r="OK",i={}){return new Promise(l=>fc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>fc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(ld.push(n),()=>{ld=ld.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{fc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(uc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(dc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{fc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{fc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let Nd=null,cd=[];const Nv=e=>{Nd=e,cd.forEach(t=>t())};function VB(e,t){Nv({...t,path:e,from:t})}function HB(e){Nd?.from===e&&Nv(null)}function XL(){const e=b.useSyncExternalStore(f=>(cd.push(f),()=>{cd=cd.filter(h=>h!==f)}),()=>Nd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),Nd===e&&Nv(null)}},u=()=>{l(e.keep)};return o.jsx(uc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(dc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:mi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":mi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>We("/api/projects")};function WL(e){return rt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=mn();return()=>e.fetchQuery(dE)}function fE(e){return rt({queryKey:["orgs"],queryFn:()=>We("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function kv(e){return rt({queryKey:["permissions",e],queryFn:()=>We(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return rt({queryKey:["folders",e],queryFn:()=>We(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return rt({queryKey:["shares",e],queryFn:()=>We(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return rt({queryKey:["admin","pending"],queryFn:()=>We("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function mf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Jp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Jp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Jp,e)?Jp[e]:void 0}const Rv=["q","user","actor","device","range","since","until"];function Mv(e){return!!e&&Rv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of Rv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Tv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of Rv){const y=r?.get(m);y&&(h[m]=y)}if(Mv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=mf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?mf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function $n(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=mf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Ov="POP";const eg=new Set;function xE(){for(const e of eg)e()}window.addEventListener("popstate",()=>{Ov="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Ov=t?.replace?"REPLACE":"PUSH",xE())}function Av(){return b.useSyncExternalStore(e=>(eg.add(e),()=>{eg.delete(e)}),()=>location.pathname+location.search)}function c$(){return Ov}function Pn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function si({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function ba(e,t){return typeof e=="function"?e(t):e}function hs(e,t){return n=>{t.setState(r=>({...r,[e]:ba(n,r[e])}))}}function pf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Rn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return qu(t,[...f,...m,...h],e)},He(e.options,Rn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),qu(t,n,e,"center")),He(e.options,Rn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"left")},He(e.options,Rn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"right")},He(e.options,Rn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Rn))}};function qu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Is(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Is(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Is(e);const Dv=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Dv.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Dv.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const zr={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Dv};function Is(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:hs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?zr.includesString:typeof r=="number"?zr.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?zr.equals:Array.isArray(r)?zr.arrIncludes:zr.weakEquals},e.getFilterFn=()=>{var n,r;return pf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:zr[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=ba(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=ba(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,rp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:hs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return rp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return rp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:rp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:hs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Pl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Pl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Pl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},ap=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:ap(),...e}),getDefaultOptions:e=>({onColumnPinningChange:hs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?ap():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:ap())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Bu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ip=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Bu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ip(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:hs("columnSizing",e),onColumnSizingInfoChange:hs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bu.minSize,(r=l??e.columnDef.size)!=null?r:Bu.size),(i=e.columnDef.maxSize)!=null?i:Bu.maxSize)},e.getStart=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),op(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=op(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;op(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ip():(n=e.initialState.columnSizingInfo)!=null?n:ip())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Gu=null;function A$(){if(typeof Gu=="boolean")return Gu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gu=e,Gu}function op(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:hs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Pl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:hs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>zr.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return pf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:zr[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:hs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},tg=0,ng=10,lp=()=>({pageIndex:tg,pageSize:ng}),F$={getInitialState:e=>({...e,pagination:{...lp(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:hs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>ba(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?lp():(i=e.initialState.pagination)!=null?i:lp())},e.setPageIndex=r=>{e.setPagination(i=>{let l=ba(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:tg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?ng:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:ng)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,ba(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=ba(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},cp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:cp(),...e}),getDefaultOptions:e=>({onRowPinningChange:hs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?cp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:cp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:hs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{sg(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return sg(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},sg=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>sg(e,f.id,n,r,i))};function up(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=zv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function zv(e,t){var n;return(n=t[e.id])!=null?n:!1}function rg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(zv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=rg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const ag=/([0-9]+)/gm,U$=(e,t,n)=>RE(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(_a(e.getValue(n)),_a(t.getValue(n))),H$=(e,t,n)=>Lv(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>Lv(_a(e.getValue(n)),_a(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rLv(e.getValue(n),t.getValue(n));function Lv(e,t){return e===t?0:e>t?1:-1}function _a(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(ag).filter(Boolean),r=t.split(ag).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Al={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:hs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Al.datetime;if(typeof l=="string"&&(r=!0,l.split(ag).length>1))return Al.alphanumeric}return r?Al.text:Al.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Al[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=ba(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ig(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var hc=e=>e.type==="checkbox",wa=e=>e instanceof Date,bn=e=>e==null;const $v=e=>typeof e=="object";var Vt=e=>!bn(e)&&!Array.isArray(e)&&$v(e)&&!wa(e),J$=e=>Vt(e)&&e.target?hc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Vt(t)&&t.hasOwnProperty("isPrototypeOf")},gf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(gf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Vt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Gt(e[i]));return r}const mo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",Fv=["__proto__","constructor","prototype"],t8=/^\w*$/;var mc=e=>t8.test(e),Mt=e=>e===void 0;const n8=/[.[\]'"]/;var vf=e=>e.split(n8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Vt(e))return n;const r=mc(t)?[t]:vf(t);if(r.some(l=>Fv.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Ns=e=>typeof e=="function",wt=(e,t,n)=>{let r=-1;const i=mc(t)?[t]:vf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const a8=gf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),og=e=>bn(e)||!$v(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(og(e)||og(t))return Object.is(e,t);if(wa(e)&&wa(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(wa(f)&&wa(h)||(Vt(f)||Array.isArray(f))&&(Vt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Ku=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),dp=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Ul=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Ul(f,t))break}else if(Vt(f)&&Ul(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return wt(i,DE,t[n]),wt(e,n,i),e},xn=e=>Vt(e)&&!Object.keys(e).length,Iv=e=>e.type==="file",kd=e=>{if(!gf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pv=e=>e.type==="radio",Rd=e=>e instanceof RegExp,Uv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||tr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var po=e=>Vt(e)&&!Rd(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Pv(u),L=hc(u),H=M||L,U=(E||Iv(u))&&Mt(u.value)&&Mt(N)||kd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Uv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||tr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Q,message:ae}=wn(h)?{value:!!h,message:h}:po(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Q,ae;const le=po(w),be=po(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Q=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Q,message:ae}=po(x);if(Rd(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Ns(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Vt(j)){let Q={};for(const ae in j){if(!xn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!xn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},ud=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;rFv.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Vt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Kt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if($v(e[n])&&e[n]!==null&&!wa(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Vt(i)&&l){const u=IE(i,l);Vt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Pv(e)||hc(e),fp=e=>kd(e)&&e.isConnected,d8=e=>{for(const t in e)if(Ns(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Vt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function lg(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function cg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},cg(i,t[r],l),HE(t[r])&&lg(t,r)):Mt(i)||(t[r]=!0)}return t}function ri(e,t,n,r){n||(n=cg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Mt(t)||og(n[i])?n[i]=cg(l,Array.isArray(l)?[]:{},u):ri(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&lg(n,i)):nr(l,t[i])?lg(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Iv(t)?t.files:Pv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):hc(t)?zE(e.refs).value:qE(Mt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&wt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Dl=e=>Mt(e)?e:Rd(e)?e.source:Vt(e)?Rd(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(Ns(e.validate))return e.validate.constructor.name===b1;if(Vt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||mc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},g8=(e,t,n)=>!e||!t||e===t||ud(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(ke(e,t)).length&&Kt(e,t);const x8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},hp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Gt(BE),isLoading:Ns(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Vt(t.defaultValues)||Vt(t.values)?Gt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Gt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Ku(t.mode),w=Ku(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=xn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:mo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?wt(n.validatingFields,W,Y):Kt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ri(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const je=W(ke(r,z),de.argA,de.argB);me&&wt(r,z,je)}if(xe&&Array.isArray(ke(n.errors,z))){const je=W(ke(n.errors,z),de.argA,de.argB);me&&wt(n.errors,z,je),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const je=W(ke(n.touchedFields,z),de.argA,de.argB);me&&wt(n.touchedFields,z,je)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else wt(l,z,Y)},H=(z,Y)=>{wt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=mc(z)?[z]:vf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),je=ke(l,z,Mt(W)?ke(i,z):W);Mt(je)||de&&de.defaultChecked||Y?wt(l,z,Y?je:x1(me._f)):D(z,je),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&dp(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,je=!1;const _e={name:z};if(!t.disabled||de===!0){if(!W||de){const Ae=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(je=n.isDirty,n.isDirty=_e.isDirty=!Ae||ee(),xe=je!==_e.isDirty),je=!!ke(n.dirtyFields,z),Ae!==n.isDirty?n.dirtyFields=ri(i,l,void 0,r):Ae?Kt(n.dirtyFields,z):wt(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&je!==!Ae}if(W){const Ae=ke(n.touchedFields,z);Ae||(wt(n.touchedFields,z,W),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ae!==W)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?wt(n.errors,z,W):Kt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!xn(de)||xe){const je={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...je},E.state.next(je)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Vt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):wt(n.errors,W,de):Kt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Vt(W))for(const de in W){const me=W[de];me&&ht(`${hp}.${de}`,{message:wn(me.message)?me.message:"",type:me.type||Ls.validate})}else wn(W)||!W?ht(hp,{message:W||"",type:Ls.validate}):Ye(hp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const je=z[xe];if(je){const{_f:_e,...Ae}=je;if(_e){const Ke=f.array.has(_e.name),Ct=je._f&&h8(je._f),sn=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Ct&&sn&&A([_e.name],!0);const Dt=await v1(je,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,Ke);if(Ct&&sn&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Y)||(!Y&&(ke(Dt,_e.name)?Ke?f1(n.errors,Dt,_e.name):wt(n.errors,_e.name,Dt[_e.name]):Kt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ae)&&await q({context:me,onlyCheckValid:Y,fields:Ae,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!fp(W)):!fp(Y._f.ref))&&ot(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&wt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>i8(z,f,{...u.mount?l:Mt(Y)?i:wn(z)?{[z]:Y}:Y},W,Y),O=z=>$E(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let je=Y;if(xe){const _e=xe._f;_e&&(!_e.disabled&&wt(l,z,qE(Y,_e)),je=kd(_e.ref)&&bn(Y)?"":Y,PE(_e.ref)?[..._e.ref.options].forEach(Ae=>Ae.selected=je.includes(Ae.value)):_e.refs?hc(_e.ref)?_e.refs.forEach(Ae=>{(!Ae.defaultChecked||!Ae.disabled)&&(Array.isArray(je)?Ae.checked=!!je.find(Ke=>Ke===Ae.value):Ae.checked=je===Ae.value||!!je)}):_e.refs.forEach(Ae=>Ae.checked=Ae.value===je):Iv(_e.ref)?_e.ref.value="":(_e.ref.value=je,!_e.ref.type&&!me&&E.state.next({name:z,values:de?l:Gt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,je,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&Se(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const je=Y[xe],_e=z+"."+xe,Ae=ke(r,_e);(f.array.has(z)||Vt(je)||Ae&&!Ae._f)&&!wa(je)?B(_e,je,W,de,me):D(_e,je,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),je=f.array.has(z),_e=de?Y:Gt(Y),Ae=ke(l,z),Ke=nr(Ae,_e);if(Ke||wt(l,z,_e),je)E.array.next({name:z,values:de?l:Gt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Ct=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||Ct?D(z,_e,W,de,me):B(z,_e,W,de,me)}if(!Ke&&!me){const Ct=dp(z,f),sn=de?l:Gt(l);E.state.next({...Ct&&n,name:u.mount||Ct?z:void 0,values:sn})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Ns(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=FE(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=je=>{de=Number.isNaN(je)||wa(je)&&isNaN(je.getTime())||nr(je,ke(l,W,je))};if(me){let je,_e;const Ae=Y.type?x1(me._f):J$(z),Ke=z.type===mo.BLUR||z.type===mo.FOCUS_OUT,Ct=!m8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,sn=Ct||v8(Ke,ke(n.touchedFields,W),n.isSubmitted,w,g),Dt=dp(W,f,Ke);if(wt(l,W,Ae),Ke){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const Et=h[W];Et&&Et(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Ae,Ke),dt=!xn(Le)||Dt;if(!Ke&&E.state.next({name:W,type:z.type,...y?{values:Gt(l)}:{}}),sn)return(!Ct||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?Ke&&T():Ke||T()),dt&&E.state.next({name:W,...Dt?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!Ke&&Dt&&E.state.next({...n}),t.resolver){const{errors:Et}=await le([W]);if(A([W]),xe(Ae),!de){!xn(Le)&&E.state.next(Le);return}const $t=w1(n.errors,r,W),Hn=w1(Et,r,$t.name||W);je=Hn.error,W=Hn.name,_e=xn(Et)}else A([W],!0),je=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Ae),de&&(je?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&Se(me._f.deps),ae(W,_e,je,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},Se=async(z,Y={})=>{let W,de;const me=ud(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=xn(xe),de=z?!me.some(je=>ke(xe,je)):W}else z?(de=(await Promise.all(me.map(async xe=>{const je=ke(r,xe);return await q({fields:je&&je._f?{[xe]:je}:je,eventType:mo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:mo.TRIGGER});if(Y.delayError&&t.delayError&&wn(z)){const xe=ke(n.errors,z);xe?(Kt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Ul(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=IE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:wn(z)?ke(W,z):z.map(de=>ke(W,de))},Me=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ye=z=>{const Y=z?ud(z):void 0;Y?.forEach(W=>Kt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:je,type:_e,...Ae}=me;wt(n.errors,z,{...Ae,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},tt=(z,Y)=>{if(Ns(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},es=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,hr,z.reRenderRoot)){const je={...l};z.callback({values:je,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},es({...z,formState:{...x,...z.formState}})),ot=(z,Y={})=>{for(const W of z?ud(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Kt(r,W),Kt(l,W)),!Y.keepError&&Kt(n.errors,W),!Y.keepDirty&&Kt(n.dirtyFields,W),!Y.keepTouched&&Kt(n.touchedFields,W),!Y.keepIsValidating&&Kt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Kt(i,W);E.state.next({values:Gt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},mn=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},Nt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return wt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?mn({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Dl(Y.min),max:Dl(Y.max),minLength:Dl(Y.minLength),maxLength:Dl(Y.maxLength),pattern:Dl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Y),f.registerName.delete(z),W=ke(r,z);const je=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(je),Ae=W._f.refs||[];if(_e?Ae.find(Ke=>Ke===je):je===W._f.ref)return;wt(r,z,{_f:{...W._f,..._e?{refs:[...Ae.filter(fp),je,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:je.type,name:z}}:{ref:je}}}),X(z,!1,void 0,je)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},un=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Ul(r,we,f.mount),jt=z=>{tr(z)&&(E.state.next({disabled:z}),Ul(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},Lt=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=Gt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:je}=await le();A(),n.errors=xe,me=Gt(je)}else await q({fields:r,eventType:mo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Kt(me,xe);if(Kt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),un(),setTimeout(un);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},ts=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,Gt(ke(i,z))):(I(z,Y.defaultValue),wt(i,z,Gt(Y.defaultValue))),Y.keepTouched||Kt(n.touchedFields,z),Y.keepDirty||(Kt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,Gt(ke(i,z))):ee()),Y.keepError||(Kt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},At=(z,Y={})=>{const W=z?Gt(z):i,de=Gt(W),me=xn(z),xe=de,je=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ri(i,l,void 0,je))]);for(const Ae of Array.from(_e)){const Ke=ke(n.dirtyFields,Ae),Ct=ke(l,Ae),sn=ke(xe,Ae);Ke&&!Mt(Ct)?wt(xe,Ae,Ct):!Ke&&!Mt(sn)&&I(Ae,sn)}}else{if(gf&&Mt(z))for(const _e of f.mount){const Ae=ke(r,_e);if(Ae&&Ae._f){const Ke=Array.isArray(Ae._f.refs)?Ae._f.refs[0]:Ae._f.ref;if(kd(Ke)){const Ct=Ke.closest("form");if(Ct){Ct.reset();break}}}}if(Y.keepFieldsRef)for(const _e of f.mount)I(_e,ke(xe,_e));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?Gt(i):{},Y.keepFieldsRef)for(const _e of f.mount)wt(l,_e,ke(xe,_e))}else l=Gt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?ri(i,l,void 0,je):n.dirtyFields:Y.keepDefaultValues&&z?ri(i,z,void 0,je):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},nn=(z,Y)=>At(Ns(z)?z(l):z,{...t.resetOptions,...Y}),ns=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Ns(me.select)&&me.select()})}},hr=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},Tn={control:{register:Nt,unregister:ot,getFieldState:Me,handleSubmit:Lt,setError:ht,_subscribe:es,_runSchema:le,_updateIsValidating:A,_focusError:un,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:mn,_setErrors:U,_getFieldArray:O,_reset:At,_resetDefaultValues:()=>Ns(t.defaultValues)&&t.defaultValues().then(z=>{nn(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:jt,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Ku(t.mode),w=Ku(t.reValidateMode)}},subscribe:Fe,trigger:Se,register:Nt,handleSubmit:Lt,watch:tt,setValue:I,setValues:re,getValues:ve,reset:nn,resetField:ts,resetDefaultValues:(z,Y={})=>{if(i=Gt(z),!Y.keepDirty){const W=ri(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!xn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ye,unregister:ot,setError:ht,setFocus:ns,getFieldState:Me};return{...Tn,formControl:Tn}}function Vv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Gt(BE),isLoading:Ns(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Ns(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Ns(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},ug=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&ug(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));wt(u,"root",l),wt(n,r,u)}else wt(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Hv=globalThis.__zod_globalConfig;function gi(e){return Hv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function dg(e,t){return typeof t=="bigint"?t.toString():t}function qv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bv(e){return e==null}function Gv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function St(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ma(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=qv(()=>{if(Hv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Jl(e){if(Md(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Md(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function k8(e,t){if(!Jl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ma(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return ji(this,"shape",l),l}});return Ta(e,i)}function R8(e,t){if(!Jl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ji(this,"shape",r),r}});return Ta(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ta(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Ma(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return ji(this,"shape",h),h},checks:[]});return Ta(t,u)}function O8(e,t,n){const r=Ma(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return ji(this,"shape",l),l}});return Ta(t,r)}function wo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Zu(e){return typeof e=="string"?e:e?.message}function vi(e,t,n){const r=e.message?e.message:Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Kv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ec(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zv=pe("$ZodError",XE),xf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new _o;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},L8=bf(xf),wf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},$8=wf(xf),Sf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new _o;return l.issues.length?{success:!1,error:new(e??Zv)(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},F8=Sf(xf),jf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},I8=jf(xf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,i)},U8=e=>(t,n,r)=>bf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},H8=e=>async(t,n,r)=>wf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},B8=e=>(t,n,r)=>Sf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},K8=e=>async(t,n,r)=>jf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Kv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cf=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),Cf.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),Cf.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=yf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${yf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${yf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
+            color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Rn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return qu(t,[...f,...m,...h],e)},He(e.options,Rn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),qu(t,n,e,"center")),He(e.options,Rn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"left")},He(e.options,Rn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"right")},He(e.options,Rn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Rn))}};function qu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Is(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Is(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Is(e);const Dv=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Dv.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Dv.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const zr={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Dv};function Is(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:hs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?zr.includesString:typeof r=="number"?zr.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?zr.equals:Array.isArray(r)?zr.arrIncludes:zr.weakEquals},e.getFilterFn=()=>{var n,r;return pf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:zr[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=ba(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=ba(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,rp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:hs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return rp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return rp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:rp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:hs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Pl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Pl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Pl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},ap=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:ap(),...e}),getDefaultOptions:e=>({onColumnPinningChange:hs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?ap():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:ap())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Bu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ip=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Bu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ip(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:hs("columnSizing",e),onColumnSizingInfoChange:hs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bu.minSize,(r=l??e.columnDef.size)!=null?r:Bu.size),(i=e.columnDef.maxSize)!=null?i:Bu.maxSize)},e.getStart=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),op(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=op(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;op(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ip():(n=e.initialState.columnSizingInfo)!=null?n:ip())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Gu=null;function A$(){if(typeof Gu=="boolean")return Gu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gu=e,Gu}function op(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:hs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Pl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:hs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>zr.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return pf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:zr[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:hs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},tg=0,ng=10,lp=()=>({pageIndex:tg,pageSize:ng}),F$={getInitialState:e=>({...e,pagination:{...lp(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:hs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>ba(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?lp():(i=e.initialState.pagination)!=null?i:lp())},e.setPageIndex=r=>{e.setPagination(i=>{let l=ba(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:tg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?ng:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:ng)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,ba(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=ba(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},cp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:cp(),...e}),getDefaultOptions:e=>({onRowPinningChange:hs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?cp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:cp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:hs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{sg(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return sg(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},sg=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>sg(e,f.id,n,r,i))};function up(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=zv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function zv(e,t){var n;return(n=t[e.id])!=null?n:!1}function rg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(zv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=rg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const ag=/([0-9]+)/gm,U$=(e,t,n)=>RE(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(_a(e.getValue(n)),_a(t.getValue(n))),H$=(e,t,n)=>Lv(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>Lv(_a(e.getValue(n)),_a(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rLv(e.getValue(n),t.getValue(n));function Lv(e,t){return e===t?0:e>t?1:-1}function _a(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(ag).filter(Boolean),r=t.split(ag).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Al={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:hs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Al.datetime;if(typeof l=="string"&&(r=!0,l.split(ag).length>1))return Al.alphanumeric}return r?Al.text:Al.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Al[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=ba(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ig(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var hc=e=>e.type==="checkbox",wa=e=>e instanceof Date,bn=e=>e==null;const $v=e=>typeof e=="object";var Vt=e=>!bn(e)&&!Array.isArray(e)&&$v(e)&&!wa(e),J$=e=>Vt(e)&&e.target?hc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Vt(t)&&t.hasOwnProperty("isPrototypeOf")},gf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(gf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Vt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Gt(e[i]));return r}const mo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",Fv=["__proto__","constructor","prototype"],t8=/^\w*$/;var mc=e=>t8.test(e),Mt=e=>e===void 0;const n8=/[.[\]'"]/;var vf=e=>e.split(n8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Vt(e))return n;const r=mc(t)?[t]:vf(t);if(r.some(l=>Fv.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Ns=e=>typeof e=="function",wt=(e,t,n)=>{let r=-1;const i=mc(t)?[t]:vf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const a8=gf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),og=e=>bn(e)||!$v(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(og(e)||og(t))return Object.is(e,t);if(wa(e)&&wa(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(wa(f)&&wa(h)||(Vt(f)||Array.isArray(f))&&(Vt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Ku=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),dp=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Ul=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Ul(f,t))break}else if(Vt(f)&&Ul(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return wt(i,DE,t[n]),wt(e,n,i),e},xn=e=>Vt(e)&&!Object.keys(e).length,Iv=e=>e.type==="file",kd=e=>{if(!gf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pv=e=>e.type==="radio",Rd=e=>e instanceof RegExp,Uv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||tr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var po=e=>Vt(e)&&!Rd(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Pv(u),L=hc(u),H=M||L,U=(E||Iv(u))&&Mt(u.value)&&Mt(N)||kd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Uv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||tr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Q,message:ae}=wn(h)?{value:!!h,message:h}:po(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Q,ae;const le=po(w),be=po(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Q=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Q,message:ae}=po(x);if(Rd(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Ns(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Vt(j)){let Q={};for(const ae in j){if(!xn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!xn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},ud=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;rFv.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Vt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Kt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if($v(e[n])&&e[n]!==null&&!wa(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Vt(i)&&l){const u=IE(i,l);Vt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Pv(e)||hc(e),fp=e=>kd(e)&&e.isConnected,d8=e=>{for(const t in e)if(Ns(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Vt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function lg(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function cg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},cg(i,t[r],l),HE(t[r])&&lg(t,r)):Mt(i)||(t[r]=!0)}return t}function ri(e,t,n,r){n||(n=cg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Mt(t)||og(n[i])?n[i]=cg(l,Array.isArray(l)?[]:{},u):ri(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&lg(n,i)):nr(l,t[i])?lg(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Iv(t)?t.files:Pv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):hc(t)?zE(e.refs).value:qE(Mt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&wt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Dl=e=>Mt(e)?e:Rd(e)?e.source:Vt(e)?Rd(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(Ns(e.validate))return e.validate.constructor.name===b1;if(Vt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||mc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},g8=(e,t,n)=>!e||!t||e===t||ud(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(ke(e,t)).length&&Kt(e,t);const x8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},hp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Gt(BE),isLoading:Ns(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Vt(t.defaultValues)||Vt(t.values)?Gt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Gt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Ku(t.mode),w=Ku(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=xn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:mo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?wt(n.validatingFields,W,Y):Kt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ri(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const je=W(ke(r,z),de.argA,de.argB);me&&wt(r,z,je)}if(xe&&Array.isArray(ke(n.errors,z))){const je=W(ke(n.errors,z),de.argA,de.argB);me&&wt(n.errors,z,je),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const je=W(ke(n.touchedFields,z),de.argA,de.argB);me&&wt(n.touchedFields,z,je)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else wt(l,z,Y)},H=(z,Y)=>{wt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=mc(z)?[z]:vf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),je=ke(l,z,Mt(W)?ke(i,z):W);Mt(je)||de&&de.defaultChecked||Y?wt(l,z,Y?je:x1(me._f)):D(z,je),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&dp(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,je=!1;const _e={name:z};if(!t.disabled||de===!0){if(!W||de){const Ae=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(je=n.isDirty,n.isDirty=_e.isDirty=!Ae||ee(),xe=je!==_e.isDirty),je=!!ke(n.dirtyFields,z),Ae!==n.isDirty?n.dirtyFields=ri(i,l,void 0,r):Ae?Kt(n.dirtyFields,z):wt(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&je!==!Ae}if(W){const Ae=ke(n.touchedFields,z);Ae||(wt(n.touchedFields,z,W),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ae!==W)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?wt(n.errors,z,W):Kt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!xn(de)||xe){const je={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...je},E.state.next(je)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Vt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):wt(n.errors,W,de):Kt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Vt(W))for(const de in W){const me=W[de];me&&ht(`${hp}.${de}`,{message:wn(me.message)?me.message:"",type:me.type||Ls.validate})}else wn(W)||!W?ht(hp,{message:W||"",type:Ls.validate}):Ye(hp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const je=z[xe];if(je){const{_f:_e,...Ae}=je;if(_e){const Ke=f.array.has(_e.name),Ct=je._f&&h8(je._f),rn=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Ct&&rn&&A([_e.name],!0);const Dt=await v1(je,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,Ke);if(Ct&&rn&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Y)||(!Y&&(ke(Dt,_e.name)?Ke?f1(n.errors,Dt,_e.name):wt(n.errors,_e.name,Dt[_e.name]):Kt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ae)&&await q({context:me,onlyCheckValid:Y,fields:Ae,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!fp(W)):!fp(Y._f.ref))&&ot(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&wt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>i8(z,f,{...u.mount?l:Mt(Y)?i:wn(z)?{[z]:Y}:Y},W,Y),O=z=>$E(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let je=Y;if(xe){const _e=xe._f;_e&&(!_e.disabled&&wt(l,z,qE(Y,_e)),je=kd(_e.ref)&&bn(Y)?"":Y,PE(_e.ref)?[..._e.ref.options].forEach(Ae=>Ae.selected=je.includes(Ae.value)):_e.refs?hc(_e.ref)?_e.refs.forEach(Ae=>{(!Ae.defaultChecked||!Ae.disabled)&&(Array.isArray(je)?Ae.checked=!!je.find(Ke=>Ke===Ae.value):Ae.checked=je===Ae.value||!!je)}):_e.refs.forEach(Ae=>Ae.checked=Ae.value===je):Iv(_e.ref)?_e.ref.value="":(_e.ref.value=je,!_e.ref.type&&!me&&E.state.next({name:z,values:de?l:Gt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,je,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&Se(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const je=Y[xe],_e=z+"."+xe,Ae=ke(r,_e);(f.array.has(z)||Vt(je)||Ae&&!Ae._f)&&!wa(je)?B(_e,je,W,de,me):D(_e,je,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),je=f.array.has(z),_e=de?Y:Gt(Y),Ae=ke(l,z),Ke=nr(Ae,_e);if(Ke||wt(l,z,_e),je)E.array.next({name:z,values:de?l:Gt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Ct=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||Ct?D(z,_e,W,de,me):B(z,_e,W,de,me)}if(!Ke&&!me){const Ct=dp(z,f),rn=de?l:Gt(l);E.state.next({...Ct&&n,name:u.mount||Ct?z:void 0,values:rn})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Ns(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=FE(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=je=>{de=Number.isNaN(je)||wa(je)&&isNaN(je.getTime())||nr(je,ke(l,W,je))};if(me){let je,_e;const Ae=Y.type?x1(me._f):J$(z),Ke=z.type===mo.BLUR||z.type===mo.FOCUS_OUT,Ct=!m8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,rn=Ct||v8(Ke,ke(n.touchedFields,W),n.isSubmitted,w,g),Dt=dp(W,f,Ke);if(wt(l,W,Ae),Ke){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const Et=h[W];Et&&Et(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Ae,Ke),dt=!xn(Le)||Dt;if(!Ke&&E.state.next({name:W,type:z.type,...y?{values:Gt(l)}:{}}),rn)return(!Ct||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?Ke&&T():Ke||T()),dt&&E.state.next({name:W,...Dt?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!Ke&&Dt&&E.state.next({...n}),t.resolver){const{errors:Et}=await le([W]);if(A([W]),xe(Ae),!de){!xn(Le)&&E.state.next(Le);return}const $t=w1(n.errors,r,W),Hn=w1(Et,r,$t.name||W);je=Hn.error,W=Hn.name,_e=xn(Et)}else A([W],!0),je=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Ae),de&&(je?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&Se(me._f.deps),ae(W,_e,je,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},Se=async(z,Y={})=>{let W,de;const me=ud(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=xn(xe),de=z?!me.some(je=>ke(xe,je)):W}else z?(de=(await Promise.all(me.map(async xe=>{const je=ke(r,xe);return await q({fields:je&&je._f?{[xe]:je}:je,eventType:mo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:mo.TRIGGER});if(Y.delayError&&t.delayError&&wn(z)){const xe=ke(n.errors,z);xe?(Kt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Ul(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=IE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:wn(z)?ke(W,z):z.map(de=>ke(W,de))},Me=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ye=z=>{const Y=z?ud(z):void 0;Y?.forEach(W=>Kt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:je,type:_e,...Ae}=me;wt(n.errors,z,{...Ae,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},tt=(z,Y)=>{if(Ns(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},es=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,hr,z.reRenderRoot)){const je={...l};z.callback({values:je,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},es({...z,formState:{...x,...z.formState}})),ot=(z,Y={})=>{for(const W of z?ud(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Kt(r,W),Kt(l,W)),!Y.keepError&&Kt(n.errors,W),!Y.keepDirty&&Kt(n.dirtyFields,W),!Y.keepTouched&&Kt(n.touchedFields,W),!Y.keepIsValidating&&Kt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Kt(i,W);E.state.next({values:Gt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},Yt=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},Nt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return wt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?Yt({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Dl(Y.min),max:Dl(Y.max),minLength:Dl(Y.minLength),maxLength:Dl(Y.maxLength),pattern:Dl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Y),f.registerName.delete(z),W=ke(r,z);const je=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(je),Ae=W._f.refs||[];if(_e?Ae.find(Ke=>Ke===je):je===W._f.ref)return;wt(r,z,{_f:{...W._f,..._e?{refs:[...Ae.filter(fp),je,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:je.type,name:z}}:{ref:je}}}),X(z,!1,void 0,je)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},dn=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Ul(r,we,f.mount),jt=z=>{tr(z)&&(E.state.next({disabled:z}),Ul(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},Lt=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=Gt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:je}=await le();A(),n.errors=xe,me=Gt(je)}else await q({fields:r,eventType:mo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Kt(me,xe);if(Kt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),dn(),setTimeout(dn);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},ts=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,Gt(ke(i,z))):(I(z,Y.defaultValue),wt(i,z,Gt(Y.defaultValue))),Y.keepTouched||Kt(n.touchedFields,z),Y.keepDirty||(Kt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,Gt(ke(i,z))):ee()),Y.keepError||(Kt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},At=(z,Y={})=>{const W=z?Gt(z):i,de=Gt(W),me=xn(z),xe=de,je=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ri(i,l,void 0,je))]);for(const Ae of Array.from(_e)){const Ke=ke(n.dirtyFields,Ae),Ct=ke(l,Ae),rn=ke(xe,Ae);Ke&&!Mt(Ct)?wt(xe,Ae,Ct):!Ke&&!Mt(rn)&&I(Ae,rn)}}else{if(gf&&Mt(z))for(const _e of f.mount){const Ae=ke(r,_e);if(Ae&&Ae._f){const Ke=Array.isArray(Ae._f.refs)?Ae._f.refs[0]:Ae._f.ref;if(kd(Ke)){const Ct=Ke.closest("form");if(Ct){Ct.reset();break}}}}if(Y.keepFieldsRef)for(const _e of f.mount)I(_e,ke(xe,_e));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?Gt(i):{},Y.keepFieldsRef)for(const _e of f.mount)wt(l,_e,ke(xe,_e))}else l=Gt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?ri(i,l,void 0,je):n.dirtyFields:Y.keepDefaultValues&&z?ri(i,z,void 0,je):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},sn=(z,Y)=>At(Ns(z)?z(l):z,{...t.resetOptions,...Y}),ns=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Ns(me.select)&&me.select()})}},hr=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},Tn={control:{register:Nt,unregister:ot,getFieldState:Me,handleSubmit:Lt,setError:ht,_subscribe:es,_runSchema:le,_updateIsValidating:A,_focusError:dn,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:Yt,_setErrors:U,_getFieldArray:O,_reset:At,_resetDefaultValues:()=>Ns(t.defaultValues)&&t.defaultValues().then(z=>{sn(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:jt,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Ku(t.mode),w=Ku(t.reValidateMode)}},subscribe:Fe,trigger:Se,register:Nt,handleSubmit:Lt,watch:tt,setValue:I,setValues:re,getValues:ve,reset:sn,resetField:ts,resetDefaultValues:(z,Y={})=>{if(i=Gt(z),!Y.keepDirty){const W=ri(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!xn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ye,unregister:ot,setError:ht,setFocus:ns,getFieldState:Me};return{...Tn,formControl:Tn}}function Vv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Gt(BE),isLoading:Ns(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Ns(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Ns(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},ug=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&ug(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));wt(u,"root",l),wt(n,r,u)}else wt(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Hv=globalThis.__zod_globalConfig;function gi(e){return Hv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function dg(e,t){return typeof t=="bigint"?t.toString():t}function qv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bv(e){return e==null}function Gv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function St(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ma(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=qv(()=>{if(Hv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Jl(e){if(Md(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Md(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function k8(e,t){if(!Jl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ma(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return ji(this,"shape",l),l}});return Ta(e,i)}function R8(e,t){if(!Jl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ji(this,"shape",r),r}});return Ta(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ta(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Ma(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return ji(this,"shape",h),h},checks:[]});return Ta(t,u)}function O8(e,t,n){const r=Ma(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return ji(this,"shape",l),l}});return Ta(t,r)}function wo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Zu(e){return typeof e=="string"?e:e?.message}function vi(e,t,n){const r=e.message?e.message:Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Kv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ec(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zv=pe("$ZodError",XE),xf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new _o;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},L8=bf(xf),wf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},$8=wf(xf),Sf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new _o;return l.issues.length?{success:!1,error:new(e??Zv)(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},F8=Sf(xf),jf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},I8=jf(xf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,i)},U8=e=>(t,n,r)=>bf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},H8=e=>async(t,n,r)=>wf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},B8=e=>(t,n,r)=>Sf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},K8=e=>async(t,n,r)=>jf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Kv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cf=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),Cf.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),Cf.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=yf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${yf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${yf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
 `).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>`  ${l}`)];return new t(...n,i.join(`
-`))}}const MF={major:4,minor:4,patch:3},en=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=wo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new _o;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=wo(u,w)))});else{if(u.issues.length===w)continue;m||(m=wo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(wo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new _o;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new _o;return h.then(m=>i(m,r,f))}return i(h,r,f)}}St(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Yv=pe("$ZodString",(e,t)=>{en.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ot=pe("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Yv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Ot.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Ot.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Ot.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Ot.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Ot.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Ot.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Ot.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Ot.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Ot.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Ot.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Ot.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Ot.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Ot.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Ot.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Ot.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Ot.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Ot.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Ot.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Ot.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Ot.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Ot.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{en.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{en.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Td(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Td(j,n,w,t,y,g))):Td(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(en.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=qv(()=>n2(t));St(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Md,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Td(_,f,w,m,j,S))):Td(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=qv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(`
+`))}}const MF={major:4,minor:4,patch:3},tn=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=wo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new _o;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=wo(u,w)))});else{if(u.issues.length===w)continue;m||(m=wo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(wo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new _o;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new _o;return h.then(m=>i(m,r,f))}return i(h,r,f)}}St(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Yv=pe("$ZodString",(e,t)=>{tn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ot=pe("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Yv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Ot.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Ot.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Ot.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Ot.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Ot.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Ot.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Ot.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Ot.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Ot.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Ot.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Ot.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Ot.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Ot.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Ot.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Ot.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Ot.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Ot.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Ot.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Ot.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Ot.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Ot.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{tn.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{tn.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Td(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Td(j,n,w,t,y,g))):Td(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(tn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=qv(()=>n2(t));St(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Md,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Td(_,f,w,m,j,S))):Td(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=qv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(`
         if (${T}.issues.length) {
           if (${A} in input) {
             payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
@@ -111,11 +111,11 @@ Error generating stack: `+d.message+`
           }
         }
 
-      `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Md,f=!Hv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!wo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>vi(u,r,gi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{en.init(e,t),St(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),St(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),St(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),St(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Gv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{en.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function fg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Jl(e)&&Jl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=fg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),wo(e))return e;const u=fg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{en.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?yf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new _o;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{en.init(e,t),e._zod.optin="optional",e._zod.optout="optional",St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{en.init(e,t),St(e._zod,"optin",()=>t.innerType._zod.optin),St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)}|null)$`):void 0}),St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{en.init(e,t),St(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{en.init(e,t),e._zod.optin="optional",St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>vi(u,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>vi(l,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{en.init(e,t),St(e._zod,"values",()=>t.in._zod.values),St(e._zod,"optin",()=>t.in._zod.optin),St(e._zod,"optout",()=>t.out._zod.optout),St(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Yu(u,t.in,r)):Yu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Yu(l,t.out,r)):Yu(i,t.out,r)}});function Yu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{en.init(e,t),St(e._zod,"propValues",()=>t.innerType._zod.propValues),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"optin",()=>t.innerType?._zod?.optin),St(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{fr.init(e,t),en.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(ec(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Fl=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Od(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Lo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Lo(t=>t.normalize(e))}function aP(){return Lo(e=>e.trim())}function iP(){return Lo(e=>e.toLowerCase())}function oP(){return Lo(e=>e.toUpperCase())}function lP(){return Lo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(ec(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(ec(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new fr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Fl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Ln(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/
+      `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Md,f=!Hv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!wo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>vi(u,r,gi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{tn.init(e,t),St(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),St(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),St(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),St(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Gv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function fg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Jl(e)&&Jl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=fg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),wo(e))return e;const u=fg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{tn.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?yf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new _o;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{tn.init(e,t),St(e._zod,"optin",()=>t.innerType._zod.optin),St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)}|null)$`):void 0}),St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{tn.init(e,t),St(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>vi(u,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>vi(l,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{tn.init(e,t),St(e._zod,"values",()=>t.in._zod.values),St(e._zod,"optin",()=>t.in._zod.optin),St(e._zod,"optout",()=>t.out._zod.optout),St(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Yu(u,t.in,r)):Yu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Yu(l,t.out,r)):Yu(i,t.out,r)}});function Yu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{tn.init(e,t),St(e._zod,"propValues",()=>t.innerType._zod.propValues),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"optin",()=>t.innerType?._zod?.optin),St(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{fr.init(e,t),tn.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(ec(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Fl=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Od(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Lo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Lo(t=>t.normalize(e))}function aP(){return Lo(e=>e.trim())}function iP(){return Lo(e=>e.toLowerCase())}function oP(){return Lo(e=>e.toUpperCase())}function lP(){return Lo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(ec(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(ec(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new fr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Fl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Ln(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/
 
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ln(r.element,n);if(r.type==="set")return Ln(r.valueType,n);if(r.type==="lazy")return Ln(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ln(r.innerType,n);if(r.type==="intersection")return Ln(r.left,n)||Ln(r.right,n);if(r.type==="record"||r.type==="map")return Ln(r.keyType,n)||Ln(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(r.in,n)||Ln(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Ln(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Ln(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Ln(i,n))return!0;return!!(r.rest&&Ln(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Ad=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function hg(){return hg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(hg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Uv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Qv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Zv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Zv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,dg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,dg,2)}},isEmpty:{get(){return e.issues.length===0}}})},Os=pe("ZodError",HP,{Parent:Error}),qP=bf(Os),BP=wf(Os),GP=Sf(Os),KP=jf(Os),ZP=P8(Os),YP=U8(Os),QP=V8(Os),XP=H8(Os),WP=q8(Os),JP=B8(Os),e9=G8(Os),t9=K8(Os),P1=new WeakMap;function _f(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const tn=pe("ZodType",(e,t)=>(en.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),_f(e,"ZodType",{check(...n){const r=this.def;return this.clone(Ma(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ta(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Lo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Fl.add(r,{description:n}),r},meta(...n){if(n.length===0)return Fl.get(this);const r=this.clone();return Fl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Fl.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Yv.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_f(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Od(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Od(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Yv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Qu,n)),e.uuidv4=n=>e.check(EI(Qu,n)),e.uuidv6=n=>e.check(NI(Qu,n)),e.uuidv7=n=>e.check(kI(Qu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function dd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Qu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,_f(e,"ZodArray",{min(n,r){return this.check(Od(n,r))},nonempty(n){return this.check(Od(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),St(e,"shape",()=>t.shape),_f(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Xv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const mg=pe("ZodEnum",(e,t)=>{uI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new mg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(ec(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(ec(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),tn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:at("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:at("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:at("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:at("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:at("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:at("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ig(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ig(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ig(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Pn($n(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Mn(g.row.original.url).then(w=>Ne(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await Jt("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const nU=Xv({name:dd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=hn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Vv({resolver:Qv(nU),values:{name:e.name}}),{data:m}=rt({queryKey:["invites",e.id],queryFn:()=>We(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=rt({queryKey:["orgShares",e.id],queryFn:()=>We(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await Jt("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await Mn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Mn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=hn(),n=`/api/orgs/${e.id}/apps`,{data:r}=rt({queryKey:["apps",e.id],queryFn:()=>We(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Mn(u),await Wl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Wl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Mn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>Jt("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await Jt("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await Jt("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(w){Ne(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Xv({require_verification:V1(),require_approval:V1()});function oU(){const e=hn(),{data:t,error:n}=rt({queryKey:["admin","policy"],queryFn:()=>We("/api/admin/policy")}),{data:r}=pE(!0),i=Vv({resolver:Qv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:at("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rs({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:at("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ms({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:at("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:at("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:at("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=hn(),n=rt({queryKey:["mcp","grants"],queryFn:()=>We("/api/mcp/grants")}),r=FM({mutationFn:u=>Jt("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(ks,{children:o.jsxs(Rs,{children:[o.jsx(Ms,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(ks,{className:"mcp-grant",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Jv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function ey({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:at("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Es({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:at("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function pg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const Dd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ty(e){try{return localStorage.getItem(e)}catch{return null}}function pc(e,t){try{localStorage.setItem(e,t)}catch{}}const gg=new Set;function ny(){for(const e of gg)e()}function sy(e){return gg.add(e),()=>{gg.delete(e)}}const zd=new Map;function hU(e){let t=zd.get(e);if(t===void 0){const n=Number(ty(Dd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),zd.set(e,t),n>0||pc(Dd(e),String(t))}return t}function mU(e){pc(Dd(e),String(Date.now())),zd.delete(e)}function pU(e){const t=Date.now();zd.set(e,t),pc(Dd(e),String(t)),ny()}function ry(e){return b.useSyncExternalStore(sy,()=>e?hU(e):0)}const vg=new Map,gU=[];function ay(e){let t=vg.get(e);if(!t){try{const n=JSON.parse(ty(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}vg.set(e,t)}return t}function W1(e,t){const n=ay(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];vg.set(e,r),pc(b2(e),JSON.stringify(r)),ny()}function vU(e){return b.useSyncExternalStore(sy,()=>e?ay(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(sy,()=>ty(w2)==="recent"?"recent":"name")}function xU(e){pc(w2,e),ny()}function fd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Xu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ir="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=mp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=mp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=mp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function iy(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function oy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=iy(t);return!e||n===null||!C2(Ps(e),n)?"":`stale · last changed ${oy(n)}`}function E2(e,t=!0){const n=rt({queryKey:["tree",e],queryFn:()=>We(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return rt({queryKey:["heat",e],queryFn:()=>We(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return rt({queryKey:["history",e,"prefix",t,20],queryFn:()=>We(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",Ld=100;function T2(e,t=!0){const n=ry(e),r=e?M2(e):"";return rt({queryKey:["history",r,"since",n],queryFn:()=>We(r+"history?n="+Ld+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=rt({queryKey:["heatDevices",n],queryFn:()=>We(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=rt({queryKey:["comments",e,"open-all"],queryFn:()=>We(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function vo(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},hd=0,A2=null;const yg=new Set;function Ef(e){ur=e;for(const t of yg)t()}function ly(){return b.useSyncExternalStore(e=>(yg.add(e),()=>yg.delete(e)),()=>ur)}function D2(e){e!==ur.query&&Ef({query:e,sel:0})}function xg(){D2("")}function DU(e,t){hd=e,A2=t,ur.sel>=e&&Ef({...ur,sel:Math.max(0,e-1)})}function zU(e){hd!==0&&Ef({...ur,sel:(ur.sel+e+hd)%hd})}function J1(e){e!==ur.sel&&Ef({...ur,sel:e})}function LU(){A2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function gc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],$d=e=>e>=Ld?Ld-1+"+":String(e);function pp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?gc(l.name):void 0,children:o.jsx(ci,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${$d(u)} changes since your last visit`,children:$d(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=Ev(),w=r?.org??null,x=w?Pn(w.manage_url):null,j=r?.billing?Pn(r.billing.url):null,S=Pn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Wv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Jv,{asChild:!0,children:l}),o.jsxs(ey,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Es,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),fs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(_.name),children:o.jsx(ci,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Es,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(pg,{}),n&&t&&o.jsxs(Es,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Es,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(pg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Es,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+vo(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(cf,{delayDuration:300,children:[o.jsx(uf,{asChild:!0,children:f}),o.jsx(df,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=ly();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),Co(),fs())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?Co(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?xg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:xg,children:"esc"}):o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{Co(),fs()},children:Xl?"⌘K":"Ctrl K"})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Xl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(Cv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?$d(n)+" new":void 0,badge:r==="activity"&&n?$d(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.current.name),children:o.jsx(ci,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Lr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:at("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=rt({queryKey:["billing"],queryFn:()=>We(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsxs(Ms,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function md({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:at("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function gp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:at("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:at("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function In(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const bg=280,ZU=Xv({name:dd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:dd().max(bg,`Keep the description under ${bg} characters.`),icon:dd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=In(e.perm,"admin"),l=Vv({resolver:Qv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await Jt("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){Ne(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!In(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:u})}),o.jsxs(Wv,{children:[o.jsx(Jv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(ey,{align:"start",className:"ps-icon-grid",children:[o.jsx(Es,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ci,{})}),Object.keys(Qp).map(m=>o.jsx(Es,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ci,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-name",children:"Name"}),o.jsx(md,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(gp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",bg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Lr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(ks,{id:"ps-devices",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Pn(ln("install",e.id)),children:"Connect a device"})})})]}),In(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(ks,{children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"About"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(ks,{className:"ps-danger",children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"Danger zone"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Wl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await Jt("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(ks,{id:"ps-data",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await Jt("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=hn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:In(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const wg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(wg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=hn(),{data:r,error:i}=kv(e.id),l=In(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Wl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(ks,{className:"ps-people",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await Mn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>Jt("PUT",m,{default:j}),"Default access updated.")},children:wg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>Jt("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:wg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>Jt("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function Nf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ln(r.element,n);if(r.type==="set")return Ln(r.valueType,n);if(r.type==="lazy")return Ln(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ln(r.innerType,n);if(r.type==="intersection")return Ln(r.left,n)||Ln(r.right,n);if(r.type==="record"||r.type==="map")return Ln(r.keyType,n)||Ln(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(r.in,n)||Ln(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Ln(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Ln(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Ln(i,n))return!0;return!!(r.rest&&Ln(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Ad=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function hg(){return hg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(hg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Uv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Qv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Zv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Zv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,dg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,dg,2)}},isEmpty:{get(){return e.issues.length===0}}})},Os=pe("ZodError",HP,{Parent:Error}),qP=bf(Os),BP=wf(Os),GP=Sf(Os),KP=jf(Os),ZP=P8(Os),YP=U8(Os),QP=V8(Os),XP=H8(Os),WP=q8(Os),JP=B8(Os),e9=G8(Os),t9=K8(Os),P1=new WeakMap;function _f(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const nn=pe("ZodType",(e,t)=>(tn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),_f(e,"ZodType",{check(...n){const r=this.def;return this.clone(Ma(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ta(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Lo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Fl.add(r,{description:n}),r},meta(...n){if(n.length===0)return Fl.get(this);const r=this.clone();return Fl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Fl.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Yv.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_f(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Od(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Od(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Yv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Qu,n)),e.uuidv4=n=>e.check(EI(Qu,n)),e.uuidv6=n=>e.check(NI(Qu,n)),e.uuidv7=n=>e.check(kI(Qu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function dd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Qu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,_f(e,"ZodArray",{min(n,r){return this.check(Od(n,r))},nonempty(n){return this.check(Od(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),St(e,"shape",()=>t.shape),_f(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Xv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const mg=pe("ZodEnum",(e,t)=>{uI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new mg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(ec(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(ec(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:at("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:at("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:at("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:at("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:at("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:at("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ig(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ig(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ig(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Pn($n(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Mn(g.row.original.url).then(w=>Ne(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await en("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const nU=Xv({name:dd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Vv({resolver:Qv(nU),values:{name:e.name}}),{data:m}=rt({queryKey:["invites",e.id],queryFn:()=>We(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=rt({queryKey:["orgShares",e.id],queryFn:()=>We(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await en("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await Mn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Mn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await en("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=rt({queryKey:["apps",e.id],queryFn:()=>We(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Mn(u),await Wl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Wl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Mn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>en("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>en("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await en("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await en("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(w){Ne(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Xv({require_verification:V1(),require_approval:V1()});function oU(){const e=mn(),{data:t,error:n}=rt({queryKey:["admin","policy"],queryFn:()=>We("/api/admin/policy")}),{data:r}=pE(!0),i=Vv({resolver:Qv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:at("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rs({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:at("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ms({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:at("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:at("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:at("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=mn(),n=rt({queryKey:["mcp","grants"],queryFn:()=>We("/api/mcp/grants")}),r=FM({mutationFn:u=>en("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(ks,{children:o.jsxs(Rs,{children:[o.jsx(Ms,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(ks,{className:"mcp-grant",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Jv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function ey({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:at("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Es({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:at("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function pg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const Dd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ty(e){try{return localStorage.getItem(e)}catch{return null}}function pc(e,t){try{localStorage.setItem(e,t)}catch{}}const gg=new Set;function ny(){for(const e of gg)e()}function sy(e){return gg.add(e),()=>{gg.delete(e)}}const zd=new Map;function hU(e){let t=zd.get(e);if(t===void 0){const n=Number(ty(Dd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),zd.set(e,t),n>0||pc(Dd(e),String(t))}return t}function mU(e){pc(Dd(e),String(Date.now())),zd.delete(e)}function pU(e){const t=Date.now();zd.set(e,t),pc(Dd(e),String(t)),ny()}function ry(e){return b.useSyncExternalStore(sy,()=>e?hU(e):0)}const vg=new Map,gU=[];function ay(e){let t=vg.get(e);if(!t){try{const n=JSON.parse(ty(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}vg.set(e,t)}return t}function W1(e,t){const n=ay(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];vg.set(e,r),pc(b2(e),JSON.stringify(r)),ny()}function vU(e){return b.useSyncExternalStore(sy,()=>e?ay(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(sy,()=>ty(w2)==="recent"?"recent":"name")}function xU(e){pc(w2,e),ny()}function fd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Xu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ir="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=mp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=mp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=mp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function iy(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function oy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=iy(t);return!e||n===null||!C2(Ps(e),n)?"":`stale · last changed ${oy(n)}`}function E2(e,t=!0){const n=rt({queryKey:["tree",e],queryFn:()=>We(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return rt({queryKey:["heat",e],queryFn:()=>We(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return rt({queryKey:["history",e,"prefix",t,20],queryFn:()=>We(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",Ld=100;function T2(e,t=!0){const n=ry(e),r=e?M2(e):"";return rt({queryKey:["history",r,"since",n],queryFn:()=>We(r+"history?n="+Ld+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=rt({queryKey:["heatDevices",n],queryFn:()=>We(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=rt({queryKey:["comments",e,"open-all"],queryFn:()=>We(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function vo(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},hd=0,A2=null;const yg=new Set;function Ef(e){ur=e;for(const t of yg)t()}function ly(){return b.useSyncExternalStore(e=>(yg.add(e),()=>yg.delete(e)),()=>ur)}function D2(e){e!==ur.query&&Ef({query:e,sel:0})}function xg(){D2("")}function DU(e,t){hd=e,A2=t,ur.sel>=e&&Ef({...ur,sel:Math.max(0,e-1)})}function zU(e){hd!==0&&Ef({...ur,sel:(ur.sel+e+hd)%hd})}function J1(e){e!==ur.sel&&Ef({...ur,sel:e})}function LU(){A2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function gc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],$d=e=>e>=Ld?Ld-1+"+":String(e);function pp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?gc(l.name):void 0,children:o.jsx(ci,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${$d(u)} changes since your last visit`,children:$d(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=Ev(),w=r?.org??null,x=w?Pn(w.manage_url):null,j=r?.billing?Pn(r.billing.url):null,S=Pn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Wv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Jv,{asChild:!0,children:l}),o.jsxs(ey,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Es,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),fs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(_.name),children:o.jsx(ci,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Es,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(pg,{}),n&&t&&o.jsxs(Es,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Es,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(pg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Es,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+vo(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(cf,{delayDuration:300,children:[o.jsx(uf,{asChild:!0,children:f}),o.jsx(df,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=ly();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),Co(),fs())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?Co(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?xg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:xg,children:"esc"}):o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{Co(),fs()},children:Xl?"⌘K":"Ctrl K"})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Xl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(Cv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?$d(n)+" new":void 0,badge:r==="activity"&&n?$d(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.current.name),children:o.jsx(ci,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Lr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:at("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=rt({queryKey:["billing"],queryFn:()=>We(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsxs(Ms,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function md({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:at("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function gp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:at("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:at("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function In(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const bg=280,ZU=Xv({name:dd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:dd().max(bg,`Keep the description under ${bg} characters.`),icon:dd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=In(e.perm,"admin"),l=Vv({resolver:Qv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await en("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){Ne(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!In(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:u})}),o.jsxs(Wv,{children:[o.jsx(Jv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(ey,{align:"start",className:"ps-icon-grid",children:[o.jsx(Es,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ci,{})}),Object.keys(Qp).map(m=>o.jsx(Es,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ci,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-name",children:"Name"}),o.jsx(md,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(gp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",bg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Lr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(ks,{id:"ps-devices",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Pn(cn("install",e.id)),children:"Connect a device"})})})]}),In(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(ks,{children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"About"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(ks,{className:"ps-danger",children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"Danger zone"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Wl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await en("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(ks,{id:"ps-data",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await en("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:In(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const wg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(wg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=mn(),{data:r,error:i}=kv(e.id),l=In(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Wl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>en("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(ks,{className:"ps-people",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await Mn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>en("PUT",m,{default:j}),"Default access updated.")},children:wg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>en("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:wg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>en("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function Nf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
 to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=Nf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive
-bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(tc,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(tc,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function tc({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Mn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(tc,{code:Nf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),We(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await vd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await vd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await We("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=Nf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await We("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await vd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(tc,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(uc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(dc,{className:"modal",showCloseButton:!1,children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function nc(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function kf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Mo(e,t,n){return n?nc(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Hg)||e.status===429||e.status>=500}function cy(e,t,n,r){return rt({queryKey:t,queryFn:()=>kf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function sc(e,t,n){return cy(t?nc(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=rt({queryKey:["frame",e,t],queryFn:()=>We(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=hn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,X)=>{if(!Z)return;const Q=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Q.has(be)?!1:(Q.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,X)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],X=>X&&RU(X,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const X of L.paths)r.invalidateQueries({queryKey:["render",e,X]}),r.invalidateQueries({queryKey:["text",Mo(e,X)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function uy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(`
+bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(tc,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(tc,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function tc({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Mn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(tc,{code:Nf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),We(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await vd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await vd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await We("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=Nf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await We("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await vd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(tc,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(uc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(dc,{className:"modal",showCloseButton:!1,children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function nc(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function kf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Mo(e,t,n){return n?nc(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Hg)||e.status===429||e.status>=500}function cy(e,t,n,r){return rt({queryKey:t,queryFn:()=>kf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function sc(e,t,n){return cy(t?nc(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=rt({queryKey:["frame",e,t],queryFn:()=>We(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=mn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,X)=>{if(!Z)return;const Q=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Q.has(be)?!1:(Q.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,X)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],X=>X&&RU(X,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const X of L.paths)r.invalidateQueries({queryKey:["render",e,X]}),r.invalidateQueries({queryKey:["text",Mo(e,X)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function uy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(`
 `).filter(f=>f.trim()).join(`
 `),t.push(i),i=null)};for(const u of e.split(`
 `)){const f=n+u.length;if(/^\s*(```|~~~)/.test(u))r=!r;else if(!r){const h=/^(#{1,2})\s+(.+?)\s*#*\s*$/.exec(u);h&&(l(n>0?n-1:0),h[1].length===2&&(i={name:h[2],from:n,headingEnd:f,to:f,body:""}))}n=f+1}return l(e.length),t}function H2(e,t){return e.find(n=>t>=n.from&&t<=n.to)}function qB(e,t=90){const n=e.body.split(`
@@ -125,7 +125,7 @@ bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guid
 `).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=hn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DYK0viPg.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-x7yoZJb9.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(un=>{const jt=un.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const mn=uy(P.current),Nt=new Set;for(const un of B.remoteCursors()){const jt=H2(mn,un.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=hn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),mn=Se.current;if(ot.kind==="text"&&mn){const Nt=mn.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;try{await ot.saveNow()}catch{}return ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?ln("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
-`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=hn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?Jt("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):Jt("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>Jt("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await Jt("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=hn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await Jt("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
-`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=ln("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(ln("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(ln("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
-`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=hn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=hn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(ln("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),mn=b.useRef(null),Nt=b.useRef(null),un=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),nn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||nn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,nn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,sn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),dn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),rn=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!rn)return;const ie=rn+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[rn]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!nn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():mn.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",ln("history",ze)),Nn("insights","Insights",ln("dashboard",ze)),Nn("gear","Settings",ln("settings",ze)),Nn("laptop","Connect a device",ln("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(ln("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?ln("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(ln("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:nn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!nn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{nn||(Cp(),gS(f,n,M))},onFocus:()=>{nn||(Cp(),gS(f,n,M))},title:nn?"Stop editing":"Edit this file",onClick:async()=>{if(!nn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&un.current===ie)){un.current=ie;try{const Ee=$n(M,l?.id,L,r.full,!1),ze=window.location.pathname+window.location.search;let Qe=!0;try{Qe=await(ie?.()??Promise.resolve(!0))}catch{}if(!Qe||window.location.pathname+window.location.search!==ze)return;gt(Ee)}finally{un.current===ie&&(un.current=null)}}},children:[!nn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:nn?"Done":"Edit"})]}),nn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:mn,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),rn&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(ln("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:dn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:sn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:dn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),dn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=hn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?ln(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:ln(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:ln(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:ln(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(ln("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,KB as h,xV as i,o as j,BM as k,PB as l,YB as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor--_Kdbq8f.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DEcaIEmO.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
+`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
+`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),Nt=b.useRef(null),dn=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),sn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||sn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,sn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,rn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),an=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!an)return;const ie=an+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[an]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!sn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",cn("history",ze)),Nn("insights","Insights",cn("dashboard",ze)),Nn("gear","Settings",cn("settings",ze)),Nn("laptop","Connect a device",cn("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:sn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!sn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{sn||(Cp(),gS(f,n,M))},onFocus:()=>{sn||(Cp(),gS(f,n,M))},title:sn?"Stop editing":"Edit this file",onClick:async()=>{if(!sn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&dn.current===ie)){dn.current=ie;try{const Ee=$n(M,l?.id,L,r.full,!1),ze=window.location.pathname+window.location.search;let Qe=!0;try{Qe=await(ie?.()??Promise.resolve(!0))}catch{}if(!Qe||window.location.pathname+window.location.search!==ze)return;gt(Ee)}finally{dn.current===ie&&(dn.current=null)}}},children:[!sn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:sn?"Done":"Edit"})]}),sn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),an&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:rn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-BEKa8tPX.js b/internal/webapp/static/assets/sharedfile-BEKa8tPX.js
new file mode 100644
index 00000000..dfafe199
--- /dev/null
+++ b/internal/webapp/static/assets/sharedfile-BEKa8tPX.js
@@ -0,0 +1,17 @@
+import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-COodWbrp.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+`)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[tn]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?cn(e,(n,s)=>Us(n,t[s])):!1;class st{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[tn](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Jr(t,this),t}expect(t){return Jr(t,this),t}}class tr extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ht()};class pc extends st{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends st{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends st{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends st{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):cn(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends st{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&cn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends st{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&cn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends st{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(st);class Tc extends st{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends st{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends st{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>en(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const en=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=en(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(en));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ht()},Jr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
+${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:en(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Pr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Pr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(en(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Pc=e=>{const t=Vc();for(let n=0;n(Bi(e,Pc(t)),e),lu=(e,t=[],n=[])=>Jc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Pi(e)),Wi.forEach(t=>t.print(e))},Ji=(...e)=>{console.warn(...Pi(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Ps{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>jr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return Ze(this.restDecoder)}readBuf(){return lc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(K(t)),this.clientDecoder=new Ln(K(t)),this.leftClockDecoder=new ks(K(t)),this.rightClockDecoder=new ks(K(t)),this.infoDecoder=new Vr(K(t),Ae),this.stringDecoder=new Rl(K(t)),this.parentInfoDecoder=new Vr(K(t),Ae),this.typeRefDecoder=new Ln(K(t)),this.lenDecoder=new Ln(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ze(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ze(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,h=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(u,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)h(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),h=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,h.update])}}else l.pendingStructs=h;const u=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);u&&d?l.pendingDs=Fn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===hn)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new hn),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ht()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ht();l>=0?h=c._length:h=0}return Ca(c,h,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!an(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ht()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Jn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Js(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{so(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new hn;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!an(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Ps{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,I=b-S;I>0&&nn(f,w,S,I)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else u.push(new Ra(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ji("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,hn),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Jt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),h=Ms(c);return Ne(o,h),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Jt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const h=or(l);return Ne(i,h),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let h=i.curr;h!==null;h=i.next())Jt(l,t(h),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,hn),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return an(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Ji("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return rn(e,(s,r)=>{n.push(t(s,r,e))}),n},Pa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Z();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&sn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&sn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new un(s);break;case he:l=new fn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Z(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){rn(this,t)}[Symbol.iterator](){return Pa(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Wt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&sn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
+`;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},Jl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i0)&&Es(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ni(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&si(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,k)=>{f=!0,u[k]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case At:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case xt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case Y:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&vs(u,t),n&&vs(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),Es(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);Es(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{si(r,An(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!1);o.right!==null&&ni(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return dr(this,t)}getAttributes(){return bo(this)}_write(t){t.writeTypeRef(kh)}}const th=e=>new Oe;class Cs{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Cs(this,t)}querySelector(t){t=t.toUpperCase();const s=new Cs(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Cs(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){is(this,t,new sh(this,n,t))}toString(){return wo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),rn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Bn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Ct("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return po(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return mo(this,t)}slice(t=0,n=this.length){return go(this,t,n)}forEach(t){rn(this,t)}_write(t){t.writeTypeRef(bh)}}const eh=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Hl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return dr(this,t)}hasAttribute(t){return _o(this,t)}getAttributes(t){return t?Wa(this,t):bo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return rn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(Sh),t.writeKey(this.nodeName)}}const nh=e=>new Re(e.readKey());class sh extends ss{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class jn extends Le{constructor(t){super(),this.hookName=t}_copy(){return new jn(this.hookName)}clone(){const t=new jn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(_h),t.writeKey(this.hookName)}}const rh=e=>new jn(e.readKey());class Hn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Hn}clone(){const t=new Hn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Eh)}}const ih=e=>new Hn;class gr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw yt()}mergeWith(t){return!1}write(t,n,s){throw yt()}integrate(t,n){throw yt()}}const oh=0;class pt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),lo(t.doc.store,this)}write(t,n){t.writeInfo(oh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class un{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new un(this.content)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const lh=e=>new un(e.readBuf());class on{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new on(this.len)}splice(t){const n=new on(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){nn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ch=e=>new on(e.readLen()),Io=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class fn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new fn(Io(this.doc.guid,this.opts))}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const ah=e=>new fn(Io(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const hh=e=>new ue(e.readJSON());class Y{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Y(this.key,this.value)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const uh=e=>new Y(e.readKey(),e.readJSON());class Pn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Pn(this.arr)}splice(t){const n=new Pn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const ph=e=>new At(e.readString()),wh=[qa,Ga,th,nh,eh,rh,ih],mh=0,yh=1,kh=2,Sh=3,bh=4,_h=5,Eh=6;class xt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new xt(this.type._copy())}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Ch=e=>new xt(wh[e.readTypeRef()](e)),Fs=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},pr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Jn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ri=(e,t)=>Hs(e,n=>an(n.deletions,t)),To=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return rt(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||To(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=rt(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||an(s,u.right.id)||ri(i.undoStack,u.right.id)||ri(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=rt(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=J(l,c),k=D(c,p),b=new v(k,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=k,pr(b,!0),b.integrate(e,0),b};class v extends gr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Ur:0}set marker(t){(this.info&ms)>0!==t&&(this.info^=ms)}get marker(){return(this.info&ms)>0}get keep(){return(this.info&Rr)>0}set keep(t){this.keep!==t&&(this.info^=Rr)}get countable(){return(this.info&Ur)>0}get deleted(){return(this.info&ws)>0}set deleted(t){this.deleted!==t&&(this.info^=ws)}markDeleted(){this.info|=ws}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=J(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=J(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=J(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pt||this.right&&this.right.constructor===pt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===pt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Gr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),nn(t.deleteSet,this.id.client,this.id.clock,this.length),Kr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw ht();this.content.gc(t),n?Ta(t,this,new pt(this.id,this.length)):this.content=new on(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&qn|(s===null?0:at)|(r===null?0:Nt)|(i===null?0:Xe);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=ro(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):ht();i!==null&&t.writeString(i)}this.content.write(t,n)}}const xo=(e,t)=>Dh[t&qn](e),Dh=[()=>{ht()},ch,fh,lh,ph,hh,uh,Ch,gh,ah,()=>{ht()}],Ah=10;class wt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){ht()}write(t,n){t.writeInfo(Ah),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";Lo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lo[Oo]=!0;const Ro=new Map;class Ih{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:oc(n.newValue||"")}),$l(this._onChange)}postMessage(t){wi.setItem(this.room,ic(tc(t)))}close(){Fl(this._onChange)}}const Th=typeof BroadcastChannel>"u"?Ih:BroadcastChannel,wr=e=>It(Ro,e,()=>{const t=zt(),n=new Th(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),xh=(e,t)=>(wr(e).subs.add(t),t),Lh=(e,t)=>{const n=wr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Ro.delete(e)),s},me=(e,t,n=null)=>{const s=wr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Uo=0,mr=1,Mo=2,Bs=(e,t)=>{_(e,Uo);const n=Sa(t);P(e,n)},vo=(e,t,n)=>{_(e,mr),P(e,to(t,n))},Oh=(e,t,n)=>vo(t,n,K(e)),No=(e,t,n,s)=>{try{Zi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Rh=(e,t)=>{_(e,Mo),P(e,t)},Uh=No,Mh=(e,t,n,s,r)=>{const i=C(e);switch(i){case Uo:Oh(e,t,n);break;case mr:No(e,n,s,r);break;case Mo:Uh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},vh=0,Nh=(e,t,n)=>{C(e)===vh&&n(t,Yt(e))},Ds=3e4;class $o extends sl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Gt();this.getLocalState()!==null&&Ds/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Ds<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&yr(this,s,"timeout")},kt(Ds/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Gt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const yr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Ge=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Kt(t),r=Gt(),i=[],o=[],l=[],c=[],h=C(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Fh=e=>Pl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,Fo=3,Ce=1,Bh=2,dn=[];dn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Mh(t,e,n.doc,n);s&&i===mr&&!n.synced&&(n.synced=!0)};dn[Fo]=(e,t,n,s,r)=>{_(e,Ce),P(e,Ge(n.awareness,Array.from(n.awareness.getStates().keys())))};dn[Ce]=(e,t,n,s,r)=>{$h(n.awareness,K(t),n)};dn[Bh]=(e,t,n,s,r)=>{Nh(t,n.doc,(i,o)=>Vh(n,o))};const ii=3e4,Vh=(e,t)=>console.warn(`Permission denied to access ${e.url}.
+${t}`),Bo=(e,t,n)=>{const s=Kt(t),r=Q(),i=C(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},jh=e=>!(e.code>=4400&&e.code<4500),Vs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,yr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Vo,Js(rl(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Vo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt();const s=Bo(e,new Uint8Array(n.data),!0);Ws(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Vs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Bs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),P(s,Ge(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},As=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Hh extends Ps{constructor(t,n,s,{connect:r=!0,awareness:i=new $o(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=jh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=dn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Bs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const k=Bo(this,new Uint8Array(d),!1);Ws(k)>1&&me(this.bcChannel,B(k),this)}},this._updateHandler=(d,p)=>{if(p!==this){const k=Q();_(k,ne),Rh(k,d),As(this,B(k))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:k},b)=>{const w=d.concat(p).concat(k),S=Q();_(S,Ce),P(S,Ge(i,w)),As(this,B(S))},this._exitHandler=()=>{yr(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ii{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Aa(_a(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Hh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=to(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===oi||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,I=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let R;w===0?R=0:L===-w||L!==w&&S[L-1+w-1]=r&&N>=i){a=w;break}}h.push(I)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],I=f-d,L=I===-w||I!==w&&S[I-1+w-1]F&&d>Qt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let k=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],I=u[w+1];(S>k||I>b)&&p.push({aS:n+k,aE:n+S,bS:n+b,bE:n+I}),k=S+1,b=I+1}return(ki.startsWith(o)&&(o===""||o.endsWith(`
+`)||i[o.length]===`
+`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Gh(e,t)<=0?e+t:t+e:null}function Yn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=_t(e,s),l=_t(t,s),c=_t(n,s),h=Et(o,i),a=[...Ue(h,Et(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,Et(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,I)=>{let L="",R=S;for(const N of b)N.side===w&&(L+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return L+u(o,R,I)};let d="",p=0,k=0;for(;kF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const L=f(b,0,w,S),R=f(b,1,w,S);if(L===R){d+=L;continue}if(w===S){const F=Xh(L,R,s!==Is,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===Is)return null;const N=s===Wn?Yn(u(o,w,S),L,R,Is):Yn(u(o,w,S),L,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(`
+`)?e:e+`
+`;function jo(e,t,n,s){let r=t.endsWith(`
+`);return r===e.endsWith(`
+`)&&(r=n.endsWith(`
+`)),s===""||r===s.endsWith(`
+`)?s:r?s+`
+`:s.slice(0,-1)}function Kh(e,t,n){const s=Yn(se(e),se(t),se(n),qt);return s===null?{ok:!1}:{ok:!0,text:jo(e,t,n,s)}}function du(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Yn(se(e),se(t),se(n),qt,!0)??se(n);return jo(e,t,n,s)}function Qh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(`
+`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Zh(e,t,n,s){const r=Kh(t,n,s);return!r.ok||n===s||n===t||s===t||Qh(e,r.text)?r:{ok:!1}}function li(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,qt),i=_t(t,qt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;I>=55296&&I<=56319&&w--;const L=S>0?p.charCodeAt(p.length-S):0;L>=56320&&L<=57343&&S--,b+=w,p=p.slice(w,p.length-S),k=k.slice(w,k.length-S),(p.length||k.length)&&s.push({index:b,deleteCount:p.length,insertText:k}),h=f,a=d}}function In(e,t,n){const s=new Map,r=Et(_t(t,qt),s),i=Ue(Et(_t(e,qt),s),r),o=Ue(r,Et(_t(n,qt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(`
+`);return!(l(t)!==l(e)&&l(n)!==l(t))}function qe(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ci=700,pe=[2e3,4e3,8e3,15e3],ai=2e3,eu=4,nu=64,su=8,ru=32e3,iu=32;function gu(e){const t=(g,m,y)=>Zh(e.path,g,m,y);let n=e.seed,s=e.baseSha;const r=(g,m)=>{n=g,i=m,lt(m);const y=Bt.lastIndexOf(g);y>=0?Bt.splice(0,y+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const m=[];for(let y=g;y!==null&&m.length<4;y=y.prev)y.sent!==y.from&&!m.includes(y.sent)&&m.push(y.sent);return m.length?m:void 0},l=(g,m=tt)=>{const y=o(m);return i&&i===s&&n.length>ru?{base:s,text:g,...y?{prior_sent:y}:{}}:{base:s,base_text:n,text:g,...y?{prior_sent:y}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,k=!1,b=!1,w=!1,S=null,I=null,L="",R=0;const N=(g=Date.now())=>{const m=Math.max(g,R+1e3);return R=m,Qo(e.path,e.who||"browser",new Date(m))},F=new Map;let Qt=0,St=!1,ut=null,Fe=0,os=!1,tt=null,ft=!1;const Bt=[],kr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>iu&&Bt.shift())};let Lt=!1,Be=null,Zt=0;const Ve=()=>{Lt=!1,Be=null},ls=g=>{Zt===g&&Ve()};let et=0,ot=0,gn=null,Vt=null,pn=!1,jt=null,Ot=null,je=!1,te=null,dt=null;const $=g=>e.onState?.(g),wn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ht=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let mn=null,cs=0;const He=()=>{clearTimeout(mn??void 0),mn=null},yn=g=>{if(!(g instanceof nt?g.status>=500||g.status===429:!0)||f||a)return;He();const y=pe[Math.min(cs,pe.length-1)];cs++,mn=setTimeout(()=>{mn=null,!f&&!a&&Pe()},y)},Sr=()=>{He(),cs=0},kn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},ci)},Rt=g=>{if(f)return p=g,!0;const m=O();if(m===g)return!0;const y=li(m,g);if(Dr())return x.applySplices(y),!0;if(!e.soloApply)return!1;for(const A of y)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(k)return b?Promise.resolve():Je();if(Vt)return pn=!0,Vt;const g=(async()=>{try{for(;jt;)await jt;await Ho()}finally{Vt=null}})();return Vt=g,g},Ho=async()=>{let g=0;for(;;){if(pn=!1,V||a||w)return;const m=O();if(m===n&&!ft){$("clean");return}if($("saving"),e.onWriting?.(),St){if(S!==null&&I===m){if(await Sn(m,L)==="stop")return;continue}St=!1}const y=c||h?await Po(m):await Wo(m);if(y==="stop")return;if(y==="rebased"){if(++g>eu){await Sn(O(),s??"");return}continue}if(!pn){$(O()===n&&!ft?"clean":"dirty");return}}};let mt=!1;const Po=async g=>{Ot=g,je=!1;let m;try{m=await En(wn(e.path),g,s,mt)}catch(y){return Ot=null,y instanceof nt&&y.status===422&&qe(y)?(mt=!1,ee(g),"stop"):y instanceof nt&&y.status===409?await as(n,!1)?"rebased":"stop":($("error"),yn(y),"stop")}return Ot=null,mt=!1,Sr(),m.merged?await as(g,!0)?"rebased":"stop":(je||r(g,m.sha),e.onSaved?.(g),"done")},as=async(g,m)=>{let y;try{y=await Lr(Or(e.apiBase,e.path))}catch(U){return $("error"),O()!==n&&yn(U),!1}if(y.kind!=="text")return $("error"),!1;const A=O(),E=t(g,y.text,A);return!E.ok||!Rt(E.text)?(m&<(y.sha),await Sn(A,y.sha??"")==="rebased"):(r(y.text,y.sha),m&&e.onSaved?.(y.text),!0)},Jo=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let m=null;for(let y=tt;y!==null;y=y.prev)if(y.sent!==y.from&&In(y.from,y.sent,g.text)){m=y;break}if(tt=null,m){ft=!0;const y=t(m.sent,g.text,O());y.ok&&Rt(y.text)?(n=g.text,i=void 0,lt(g.sha)):(n=m.sent,i=void 0)}},Wo=async g=>{Ot=g,je=!1;let m;const y=tt;try{tt={sent:g,from:n,prev:y},m=await Pt(Ht,{...l(g,y),...mt?{confirm_shrink:!0}:{}})}catch(E){if(Ot=null,E instanceof nt&&[400,401,403,404,405,409,413].includes(E.status)&&(tt=y),E instanceof nt&&(E.status===404||E.status===405))return h=!0,"rebased";if(E instanceof nt&&E.status===422&&qe(E))return mt=!1,ee(g),"stop";if(E instanceof nt&&E.status===409&&!a){let U={};try{U=JSON.parse(E.body)}catch{}const H=typeof U.text=="string"?U.text:null;if(H!==null){const X=t(n,H,O());if(X.ok&&Rt(X.text))return n=H,i=void 0,lt(U.sha),"rebased"}return Sn(O(),U.sha??"")}return $(a?"dirty":"error"),yn(E),"stop"}if(Ot=null,mt=!1,Sr(),m.update&&x.applyRemoteUpdate(m.update),tt=null,ft=!1,a)return"stop";const A=t(g,m.text,O());return A.ok&&Rt(A.text)&&(je||r(m.text,m.sha)),e.onSaved?.(m.text),"done"};let V=null;const ee=g=>{V||f||!e.onShrinkRefused||($("error"),V={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const m=et,y=Zt;try{const A=await Pt(Ht,{update:x.encodeState(),base:s,confirm_shrink:!0});r(A.text,A.sha),hs(m,y);const E=!Lt&&ot>=et;$(E?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&ot{if(!f)try{const m=await Lr(Or(e.apiBase,e.path));if(f||m.kind!=="text")return;if(r(m.text,m.sha),Rt(m.text),V=null,a&&!u){if(await fe(!1),f)return;$(ot>=et&&!Lt?"clean":"dirty");return}ot=et,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{V=null}}},e.onShrinkRefused(V))};let gt=null;const Yo=()=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{const g=O();xr(de(n),de(g))&&ee(g)},ci)},br=async(g,m,y=N())=>{const A=++Qt;let E=y;for(let U=1;;U++){const H=E;F.set(H,g);try{return await En(wn(H),g,void 0,!1,!1,!1,!0),A===Qt&&!a&&(n=g,i=void 0,m&&(s=m),$("clean")),e.onConflictCopy?.(H),null}catch(X){if(X instanceof nt&&X.status===409&&U{const E=(U,H)=>{En(wn(U),m,void 0,!1,!0,!0,!0).then(X=>A?.(X.parked??U),X=>{if(X instanceof nt&&X.status===409&&H{(S===null||I!==g)&&(S=N(),I=g);const y=S;L=m,St=!0;const A=await br(g,m,y);return f?"stop":A?(yn(A.err),"stop"):(St=!1,I===g&&(S=null,I=null,L=""),O()!==g?"rebased":"stop")},hs=(g,m)=>{ot=Math.max(ot,g),ls(m),!(f||u)&&(d=et-ot,e.onPending?.(d))},qo=()=>{f||u||V||dt||(dt=setTimeout(()=>{dt=null,!u&&!f&&fe(!1)},ai))},fe=g=>{if(clearTimeout(dt??void 0),dt=null,g){if(ot>=et)return Promise.resolve();const y=et,A=Zt;return Pt(Ht,{update:x.encodeState(),base:s},!0).then(E=>{lt(E.sha),hs(y,A)})}if(gn)return gn;const m=(async()=>{try{for(;!u&&!f&&!V&&ot{k=!1,S=null,I=null,Fe=0,clearTimeout(ut??void 0),ut=null,ft=!1,a=!0,kr(x.text.toString()),g?.(),os&&(os=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ut??void 0),ut=null,te&&clearTimeout(te),te=null,Vt||jt){w=!0;try{for(;Vt||jt;)await(Vt??jt)}finally{w=!1}if(f||a)return;if(!u){O()!==n&&kn();return}}if(tt!==null&&!h){let H;w=!0;try{H=await Pt(Ht,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ut=setTimeout(()=>{ut=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Jo(H),!u){(O()!==n||ft)&&kn();return}}const g=e.soloText?.();if(g===void 0||g===n)return us();const m=x.text.toString(),y=t(n,m,g);if(y.ok)return us(()=>x.applySplices(li(m,y.text)));k=!0,(S===null||I!==g)&&(S=N(),I=g),b=!0;let A;try{A=await br(g,s??"",S)}finally{b=!1}if(f)return;if(!A)return e.soloText?.()!==g?(S=null,I=null,Je()):us(()=>{n=x.text.toString()});const E=A.err;if(E instanceof nt&&!(E.status>=500||E.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ut=setTimeout(()=>{ut=null,Je()},U)},x=new Ph(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(dt&&clearTimeout(dt),dt=null,He(),a||Je(),ot=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):os=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),Er=(g,m)=>{const y=a?x.text.toString():null;if(y!==null&&kr(y),!x.isRemote(m?.origin)){if($("dirty"),a){Lt=!0,Be=y,Zt+=1,u||(et+=1,d=et-ot,e.onPending?.(d),clearTimeout(dt??void 0),dt=setTimeout(()=>{dt=null,!u&&!f&&fe(!1)},ai)),Yo();return}kn()}};x.text.observe(Er);const Cr=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Cr),Wh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const O=()=>p!==null?p:Dr()?x.text.toString():e.soloText?.()??"",Dr=()=>a||c&&x.text.length>0,lt=g=>{g&&(s=g)},zo=(g,m,y)=>{if(y?.held)return r(g,m),"same";if(g===n||g===Ot)return lt(m),"same";const A=O();if(g===A)return r(g,m),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||In(U,g,A)?(r(g,m),Lt&&(Be===null||g===Be||In(U,Be,g))&&(Ve(),$("clean")),"same"):A!==n||x.peerCount()>0?"blocked":(r(g,m),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const E=t(n,g,A);return E.ok?(Ot!==null&&(je=!0),r(g,m),Rt(E.text),E.text!==g?kn():Ot===null&&$("clean"),E.text===A?"same":"merged"):"blocked"},bn=()=>f?!1:a?u?Lt:otmt||!e.onShrinkRefused||!xr(de(n),de(O()))?!1:(clearTimeout(gt??void 0),gt=null,ee(O()),!0),Xo=async()=>{const g=Zt;$("saving");try{const m=await Pt(Ht,{update:x.encodeState()});return f?!1:(m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),ls(g),$(Lt?"dirty":"clean"),e.onSaved?.(n),!0)}catch(m){return f||m instanceof nt&&m.status===422&&qe(m)&&(clearTimeout(gt??void 0),gt=null,ee(O()),V)||$(Lt?"dirty":"clean"),!1}};let We=null;const Ko=()=>{if(We)return Vt&&(pn=!0),We;if(f||V)return Promise.resolve(!1);if(!bn())return Promise.resolve(!0);const m=(async()=>{for(;!f&&!V&&bn();){if(Go())return!1;if(a){if(u){if(!await Xo())return!1;continue}if(await fe(!1),f||V||!u&&ot{We===m&&(We=null)});return We=m,m};let Ut=null;const _n=g=>()=>{Ut===g&&(Ut=null)},Ar=(g,m)=>{if(V)return;if(a){const T=!u&&d>0;if(!T&&!(u&&Lt))return;const j="room\0"+x.text.toString();if(Ut===j)return;Ut=j;const Mt=Zt;(T?fe(!0):Pt(Ht,{update:x.encodeState()},!0).then(gs=>lt(gs.sha))).then(()=>ls(Mt),_n(j));return}if(k||St){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let j=S!==null&&I===g?S:null;for(const[Mt,ct]of F)j===null&&ct===g&&(j=Mt);j??=N(),_r(j,g,T);return}if(g===n&&!ft)return;const y="text\0"+g;if(Ut===y)return;if((c||h)&&!m){Pe();return}Ut=y;const A=n,E=!(c||h),U=tt,H={sent:g,from:A,prev:U};E&&(tt=H);const X=T=>{if(E&&T instanceof nt&&[400,401,403,404,405,409,413].includes(T.status)&&tt===H&&(tt=U),T instanceof nt&&T.status===422&&qe(T)){_n(y)(),f||(clearTimeout(gt??void 0),gt=null,ee(O()));return}if(!(T instanceof nt&&T.status===409))return _n(y)();let j={};try{const ct=JSON.parse(T.body);ct&&typeof ct=="object"&&(j=ct)}catch{}if(typeof j.text=="string"&&(j.text===g||In(A,g,j.text))){if(!f&&!a){const ct=t(g,j.text,O());ct.ok&&Rt(ct.text)&&(n=j.text,i=void 0,typeof j.sha=="string"&<(j.sha))}return}if(!g.trim())return;St=!0;let Mt=S!==null&&I===g?S:null;for(const[ct,gs]of F)Mt===null&&gs===g&&(Mt=ct);Mt??=N(),S=Mt,I=g,_r(Mt,g,y,ct=>{St=!1,e.onConflictCopy?.(ct)})},Ye=(T,j)=>{n=g,i=void 0,lt(j),!f&&O()===g&&$("clean"),e.onConflictCopy?.(T)};let fs;E?fs=Pt(Ht,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(mt=!1,tt===H&&(tt=null),ft=!1,T.parked)return Ye(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){lt(T.sha);return}const j=t(g,T.text,O());j.ok&&Rt(j.text)&&(r(T.text,T.sha),O()===n&&$("clean")),e.onSaved?.(T.text)},X):fs=En(wn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return Ye(T.parked,T.sha);if(T.merged){f?lt(T.sha):as(g,!0);return}r(g,T.sha),!f&&O()===n&&$("clean"),e.onSaved?.(g)},X);const ds=fs.then(()=>{},()=>{});jt=ds,ds.then(()=>{jt===ds&&(jt=null)})},Ir=()=>{f||Ar(O(),!0)},Tr=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ir),window.addEventListener("pageshow",Tr)),{collab:x,current:O,merge:zo,rebase:lt,saveNow:Ko,askingShrink:()=>V!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ir),window.removeEventListener("pageshow",Tr)),clearTimeout(te??void 0),clearTimeout(gt??void 0),He(),clearTimeout(ut??void 0),ut=null;const g=O();f=!0,p=g,V?e.onShrinkWithdrawn?.(V):Ar(g,!1),clearTimeout(dt??void 0),x.awareness.off("change",Cr),x.text.unobserve(Er),x.destroy()}}}export{he as D,ci as S,fu as U,hu as a,_a as b,Aa as c,li as d,uu as e,Js as f,ae as g,lu as h,vt as i,du as m,gu as o,au as r,cu as t};
diff --git a/internal/webapp/static/assets/sharedfile-Bq16w-Wl.js b/internal/webapp/static/assets/sharedfile-Bq16w-Wl.js
deleted file mode 100644
index f52a64e2..00000000
--- a/internal/webapp/static/assets/sharedfile-Bq16w-Wl.js
+++ /dev/null
@@ -1,17 +0,0 @@
-import{H as et,h as Tr,i as de,k as bn,l as Ht,m as Go,f as xr,e as Or}from"./index-CCNmuVia.js";const rt=()=>new Map,Is=e=>{const t=rt();return e.forEach((n,s)=>{t.set(s,n)}),t},At=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Xo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},Ko=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},qt=()=>new Set,gs=e=>e[e.length-1],Qo=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}class tl{constructor(){this._observers=rt()}on(t,n){At(this._observers,t,qt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||rt()).values()).forEach(s=>s(...n))}destroy(){this._observers=rt()}}const yt=Math.floor,An=Math.abs,Ps=(e,t)=>ee>t?e:t,el=Math.pow,ai=e=>e!==0?e<0:1/e<0,Lr=1,Rr=2,ps=4,ws=8,Ge=32,Nt=64,ct=128,Wn=31,Ts=63,re=127,nl=2147483647,On=Number.MAX_SAFE_INTEGER,Ur=Number.MIN_SAFE_INTEGER,sl=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&yt(e)===e),hi=String.fromCharCode,rl=e=>e.toLowerCase(),il=/^\s*/g,ol=e=>e.replace(il,""),ll=/([A-Z])/g,Mr=(e,t)=>ol(e.replace(ll,n=>`${t}${rl(n)}`)),cl=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rXe.encode(e),hl=Xe?al:cl;let qe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});qe&&qe.decode(new Uint8Array).length===1&&(qe=null);const ul=(e,t)=>Zo(t,()=>e).join("");class on{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new on,Js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Js(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xs=q,_=(e,t)=>{for(;t>re;)q(e,ct|re&t),t=yt(t/128);q(e,re&t)},Ws=(e,t)=>{const n=ai(t);for(n&&(t=-t),q(e,(t>Ts?ct:0)|(n?Nt:0)|Ts&t),t=yt(t/64);t>0;)q(e,(t>re?ct:0)|re&t),t=yt(t/128)},Os=new Uint8Array(3e4),dl=Os.length/3,gl=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),Yn(e,t)},Ys=(e,t)=>{fl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},wl=(e,t)=>Ys(e,4).setFloat32(0,t,!1),ml=(e,t)=>Ys(e,8).setFloat64(0,t,!1),yl=(e,t)=>Ys(e,8).setBigInt64(0,t,!1),vr=new DataView(new ArrayBuffer(4)),kl=e=>(vr.setFloat32(0,e),vr.getFloat32(0)===e),Ke=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":sl(t)&&An(t)<=nl?(q(e,125),Ws(e,t)):kl(t)?(q(e,124),wl(e,t)):(q(e,123),ml(e,t));break;case"bigint":q(e,122),yl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const $r=e=>{e.count>0&&(Ws(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class In{constructor(){this.encoder=new on,this.s=0,this.count=0}write(t){this.s===t?this.count++:($r(this),this.count=1,this.s=t)}toUint8Array(){return $r(this),B(this.encoder)}}const Fr=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ws(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ms{constructor(){this.encoder=new on,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Fr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}class Sl{constructor(){this.sarr=[],this.s="",this.lensE=new In}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new on;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),Yn(t,this.lensE.toUint8Array()),B(t)}}const Et=e=>new Error(e),mt=()=>{throw Et("Method unimplemented")},at=()=>{throw Et("Unexpected case")},ui=Et("Unexpected end of array"),fi=Et("Integer out of Range");class qn{constructor(t){this.arr=t,this.pos=0}}const Xt=e=>new qn(e),bl=e=>e.pos!==e.arr.length,_l=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>_l(e,E(e)),Ae=e=>e.arr[e.pos++],E=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posOn)throw fi}throw ui},qs=e=>{let t=e.arr[e.pos++],n=t&Ts,s=64;const r=(t&Nt)>0?-1:1;if((t&ct)===0)return r*n;const i=e.arr.length;for(;e.posOn)throw fi}throw ui},El=e=>{let t=E(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Cl=e=>qe.decode(K(e)),Wt=qe?Cl:El,zs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Dl=e=>zs(e,4).getFloat32(0,!1),Al=e=>zs(e,8).getFloat64(0,!1),Il=e=>zs(e,8).getBigInt64(0,!1),Tl=[e=>{},e=>null,qs,Dl,Al,Il,e=>!1,e=>!0,Wt,e=>{const t=E(e),n={};for(let s=0;s{const t=E(e),n=[];for(let s=0;sTl[127-Ae(e)](e);class Br extends qn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),bl(this)?this.count=E(this)+1:this.count=-1),this.count--,this.s}}class Tn extends qn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qs(this);const t=ai(this.s);this.count=1,t&&(this.s=-this.s,this.count=E(this)+2)}return this.count--,this.s}}class ys extends qn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qs(this),n=t&1;this.diff=yt(t/2),this.count=1,n&&(this.count=E(this)+2)}return this.s+=this.diff,this.count--,this.s}}class xl{constructor(t){this.decoder=new Tn(t),this.str=Wt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ol=crypto.getRandomValues.bind(crypto),di=()=>Ol(new Uint32Array(1))[0],Ll="10000000-1000-4000-8000"+-1e11,Rl=()=>Ll.replace(/[018]/g,e=>(e^di()&15>>e/4).toString(16)),zt=Date.now,Vr=e=>new Promise(e);Promise.all.bind(Promise);const jr=e=>e===void 0?null:e;class Ul{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let gi=new Ul,Gs=!0;try{typeof localStorage<"u"&&localStorage&&(gi=localStorage,Gs=!1)}catch{}const pi=gi,Ml=e=>Gs||addEventListener("storage",e),vl=e=>Gs||removeEventListener("storage",e),Ze=Symbol("Equality"),wi=(e,t)=>e===t||!!e?.[Ze]?.(t)||!1,Nl=e=>typeof e=="object",$l=Object.assign,Fl=Object.keys,Bl=(e,t)=>{for(const n in e)t(e[n],n)},Vl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Ln=e=>Fl(e).length,jl=e=>{for(const t in e)return!1;return!0},ln=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Xs=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hl=(e,t)=>e===t||Ln(e)===Ln(t)&&ln(e,(n,s)=>(n!==void 0||Xs(t,s))&&wi(t[s],n)),Pl=Object.freeze,mi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&mi(e[t])}return Pl(e)},Ks=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Ze]!=null)return e[Ze](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var yi={};const Gt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ki=typeof window<"u"&&typeof document<"u"&&!Gt;let St;const Yl=()=>{if(St===void 0)if(Gt){St=rt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");St.set(`--${Mr(t,"-")}`,n),St.set(`-${Mr(t,"-")}`,n)}})):St=rt();return St},Ls=e=>Yl().has(e),Rn=e=>jr(Gt?yi[e.toUpperCase().replaceAll("-","_")]:pi.getItem(e)),Si=e=>Ls("--"+e)||Rn(e)!==null,ql=Si("production"),zl=Gt&&Wl(yi.FORCE_COLOR,["true","1","2"]),Gl=zl||!Ls("--no-colors")&&!Si("no-color")&&(!Gt||process.stdout.isTTY)&&(!Gt||Ls("--color")||Rn("COLORTERM")!==null||(Rn("TERM")||"").includes("color")),bi=e=>new Uint8Array(e),Xl=(e,t,n)=>new Uint8Array(e,t,n),Kl=e=>new Uint8Array(e),Ql=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),tc=e=>{const t=atob(e),n=bi(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Xl(t.buffer,t.byteOffset,t.byteLength)},nc=ki?Ql:Zl,sc=ki?tc:ec,rc=e=>{const t=bi(e.byteLength);return t.set(e),t};class ic{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new ic(e,t),oc=(e,t)=>e.forEach(n=>t(n.left,n.right)),Hr=e=>e.next()>=.5,ks=(e,t,n)=>yt(e.next()*(n+1-t)+t),_i=(e,t,n)=>yt(e.next()*(n+1-t)+t),Qs=(e,t,n)=>_i(e,t,n),lc=e=>hi(Qs(e,97,122)),cc=(e,t=0,n=20)=>{const s=Qs(e,t,n);let r="";for(let i=0;it[Qs(e,0,t.length-1)],ac=Symbol("0schema");class hc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(ul(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
-`)}}const Rs=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Ze]?wi(e,t):De(e)?Vs(e,n=>js(t,s=>Rs(n,s))):Nl(e)?ln(e,(n,s)=>Rs(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Rs(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[ac](){return!0}[Ze](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){mt()}get nullable(){return Me(this,Qn)}get optional(){return new Di(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class Zs extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const J=(e,t=null)=>new Zs(e,t);J(Zs);class tr extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new tr(e);J(tr);class zn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Gn=(...e)=>new zn(e),Ei=J(zn),uc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Ci=e=>{if(Ie.check(e))return[uc(e)];if(Ei.check(e))return e.shape.map(t=>t+"");if(Mi.check(e))return["[+-]?\\d+.?\\d*"];if(vi.check(e))return[".*"];if(Un.check(e))return e.shape.map(Ci).flat(1);at()};class fc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Ci).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}J(fc);const dc=Symbol("optional");class Di extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[dc](){return!0}}const gc=J(Di);class pc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}J(pc);class Xn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Xn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):ln(this.shape,(s,r)=>{const i=this._isPartial&&!Xs(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const wc=e=>new Xn(e),mc=J(Xn),yc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ai extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&ln(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ii=(e,t)=>new Ai(e,t),kc=J(Ai);class Ti extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&ln(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Sc=(...e)=>new Ti(e);J(Ti);class xi extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new er(t)}check(t,n){const s=De(t)&&Vs(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new xi(e),bc=J(xi),_c=G(e=>De(e));class Li extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ec=(e,t=null)=>new Li(e,t);J(Li);const Cc=Ec(nt);class Dc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Sc(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const Ac=J(Dc),Ic=G(e=>typeof e=="function");class Tc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=Vs(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}J(Tc,e=>e.shape.length>0);class er extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>Un.check(t))>=0?Me(...e.map(t=>tn(t)).map(t=>Un.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new er(e),Un=J(er),Ri=()=>!0,Mn=G(Ri),xc=J(tr,e=>e.shape===Ri),nr=G(e=>typeof e=="bigint"),Oc=G(e=>e===nr),Ui=G(e=>typeof e=="symbol");G(e=>e===Ui);const Se=G(e=>typeof e=="number"),Mi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),vi=G(e=>e===Ie),Kn=G(e=>typeof e=="boolean"),Lc=G(e=>e===Kn),Ni=Gn(void 0);J(zn,e=>e.shape.length===1&&e.shape[0]===void 0);Gn(void 0);const Qn=Gn(null),Rc=J(zn,e=>e.shape.length===1&&e.shape[0]===null);J(Uint8Array);J(Zs,e=>e.shape===Uint8Array);const Uc=Me(Se,Ie,Qn,Ni,nr,Kn,Ui);(()=>{const e=Oi(Mn),t=Ii(Ie,Mn),n=Me(Se,Ie,Qn,Kn,e,t);return e.shape=n,t.shape.values=n,n})();const tn=e=>{if(Cc.check(e))return e;if(yc.check(e)){const t={};for(const n in e)t[n]=tn(e[n]);return wc(t)}else{if(_c.check(e))return Me(...e.map(tn));if(Uc.check(e))return Gn(e);if(Ic.check(e))return J(e)}at()},Pr=ql?()=>{}:(e,t)=>{const n=new hc;if(!t.check(e,n))throw Et(`Expected value to be of type ${t.constructor.name}.
-${n.toString()}`)};class Mc{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:tn(t),h:n}),this}else(t){return this.if(Mn,t)}done(){return(t,n)=>{for(let s=0;snew Mc(e),$i=vc(Mn).if(Mi,(e,t)=>ks(t,Ur,On)).if(vi,(e,t)=>cc(t)).if(Lc,(e,t)=>Hr(t)).if(Oc,(e,t)=>BigInt(ks(t,Ur,On))).if(Un,(e,t)=>ge(t,Ss(t,e.shape))).if(mc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(gc.check(r)){if(Hr(t))continue;r=r.shape}n[s]=$i(r,t)}return n}).if(bc,(e,t)=>{const n=[],s=_i(t,0,42);for(let r=0;rSs(t,e.shape)).if(Rc,(e,t)=>null).if(Ac,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(xc,(e,t)=>ge(t,Ss(t,[Se,Ie,Qn,Ni,nr,Kn,Oi(Se),Ii(Me("a","b","c"),Se)]))).if(kc,(e,t)=>{const n={},s=ks(t,0,3);for(let r=0;r$i(tn(t),e),It=typeof document<"u"?document:{},Nc=e=>It.createElement(e),$c=()=>It.createDocumentFragment();G(e=>e.nodeType===Yc);const Fc=e=>It.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Bc=(e,t)=>(oc(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Vc=e=>{const t=$c();for(let n=0;n(Fi(e,Vc(t)),e),ru=(e,t=[],n=[])=>jc(Bc(Nc(e),t),n);G(e=>e.nodeType===Pc);const iu=Fc;G(e=>e.nodeType===Jc);const Hc=e=>Xo(e,(t,n)=>`${n}:${t};`).join(""),Fi=(e,t)=>e.appendChild(t),Pc=It.ELEMENT_NODE,Jc=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const Wc=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const Yc=It.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===Wc);const Ft=Symbol,Bi=Ft(),Vi=Ft(),qc=Ft(),zc=Ft(),Gc=Ft(),ji=Ft(),Xc=Ft(),sr=Ft(),Kc=Ft(),Qc=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=rt();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Hi(e)),Ji.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Hi(e)),e.unshift(sr),Ji.forEach(t=>t.print(e))},Ji=qt(),Wi=e=>({[Symbol.iterator](){return this},next:e}),na=(e,t)=>Wi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),bs=(e,t)=>Wi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class Zn{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=yt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&sa(n,t.clock)!==null},rr=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new Zn(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{At(e.clients,t,()=>[]).push(new Zn(n,s))},ra=()=>new ve,ia=e=>{const t=ra();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=E(e.restDecoder);for(let s=0;s0){const o=At(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=E(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},Yi=di;class he extends Hs{constructor({guid:t=Rl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new io,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>Vr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=At(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Le)}getMap(t=""){return this.get(t,Oe)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return E(this.restDecoder)}readDsLen(){return E(this.restDecoder)}}class zi extends qi{readLeftID(){return D(E(this.restDecoder),E(this.restDecoder))}readRightID(){return D(E(this.restDecoder),E(this.restDecoder))}readClient(){return E(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Wt(this.restDecoder)}readParentInfo(){return E(this.restDecoder)===1}readTypeRef(){return E(this.restDecoder)}readLen(){return E(this.restDecoder)}readAny(){return Qe(this.restDecoder)}readBuf(){return rc(K(this.restDecoder))}readJSON(){return JSON.parse(Wt(this.restDecoder))}readKey(){return Wt(this.restDecoder)}}class oa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=E(this.restDecoder),this.dsCurrVal}readDsLen(){const t=E(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends oa{constructor(t){super(t),this.keys=[],E(t),this.keyClockDecoder=new ys(K(t)),this.clientDecoder=new Tn(K(t)),this.leftClockDecoder=new ys(K(t)),this.rightClockDecoder=new ys(K(t)),this.infoDecoder=new Br(K(t),Ae),this.stringDecoder=new xl(K(t)),this.parentInfoDecoder=new Br(K(t),Ae),this.typeRefDecoder=new Tn(K(t)),this.lenDecoder=new Tn(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Qe(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Qe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Ct(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{P(t,i)>r&&s.set(i,r)}),ts(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{la(e,t.clients.get(r),r,i)})},ca=(e,t)=>{const n=rt(),s=E(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new io,c=new Map,h=(d,p)=>{const y=c.get(d);(y==null||y>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,y=n.get(p);y?(y.i--,l.clients.set(p,y.refs.slice(y.i)),n.delete(p),y.i=0,y.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==gt){const p=At(u,a.id.client,()=>P(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const y=a.getMissing(e,t);if(y!==null){s.push(a);const b=n.get(y)||{refs:[],i:0};if(b.refs.length===b.i)h(y,P(t,y)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return or(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},ha=(e,t)=>or(e,t.doc.store,t.beforeState),ua=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ca(s,o),h=aa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Nn([a.update,h.update])}}else l.pendingStructs=h;const u=Jr(s,r,l);if(l.pendingDs){const f=new xe(Xt(l.pendingDs));E(f.restDecoder);const d=Jr(f,r,l);u&&d?l.pendingDs=Nn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Ki(r.doc,f)}},n,!1),Ki=(e,t,n,s=xe)=>{const r=Xt(t);ua(r,e,n,new s(r))},Qi=(e,t,n)=>Ki(e,t,n,zi),fa=(e,t,n=new Map)=>{or(e,t.store,n),Ne(e,ia(t.store))},da=(e,t=new Uint8Array([0]),n=new oe)=>{const s=to(t);fa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ua(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===an)return La(r.map((i,o)=>o===0?i:va(i)));if(n.constructor===oe)return Nn(r)}return r[0]},Zi=(e,t)=>da(e,t,new an),ga=e=>{const t=new Map,n=E(e.restDecoder);for(let s=0;sga(new qi(Xt(e))),eo=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),pa=(e,t)=>eo(e,ts(t.store)),wa=(e,t=new Xi)=>(e instanceof Map?eo(t,e):pa(t,e),t.toUint8Array()),ma=e=>wa(e,new Gi);class ya{constructor(){this.l=[]}}const Wr=()=>new ya,Yr=(e,t)=>e.l.push(t),qr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},no=(e,t,n)=>Ks(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),so=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw at()},vn=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class ro{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const ou=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},ka=e=>new ro(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Sa{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const ba=(e,t,n=0)=>new Sa(e,t,n),_n=(e,t,n)=>{let s=null,r=null;return e._item===null?r=so(e):s=D(e._item.id.client,e._item.id.clock),new ro(s,r,t,n)},lu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return _n(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return _n(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return _n(e,s.lastId,n);s=s.right}return _n(e,null,n)},_a=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Ea=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(P(s,r.client)<=r.clock)return null;const a=n?$s(s,r):_a(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(P(s,i.client)<=i.clock)return null;const{item:a}=n?$s(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof Tt)c=a.content.type;else return null}else throw at();l>=0?h=c._length:h=0}return ba(c,h,e.assoc)},cu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!cn(t.ds,e.id),Ms=(e,t)=>{const n=At(e.meta,Ms,qt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class io{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},P=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw at()}n.push(t)},Ct=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=yt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Ct(n,t.clock)]},_e=Ca,vs=(e,t,n)=>{const s=Ct(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[vs(e,n,t.clock)]},zr=(e,t,n)=>{const s=t.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==dt&&s.splice(r+1,0,Hn(e,i,n.clock-i.id.clock+1)),i},Da=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Ct(s,t.id.clock)]=n},lo=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=vs(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!Ko(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(rr(t.deleteSet),ha(e,t),Ne(e,t.deleteSet),!0),Xr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(e.changed,t,qt).add(n)},xn=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},Ia=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Ct(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Ct(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+xn(r,c)}})},co=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{no(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Ga(n)})}),Ks(l,[])}finally{s.gc&&Ia(i,r,s.gcFilter),Ta(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Ct(d,f),1);for(let y=d.length-1;y>=p;)y-=1+xn(d,y)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Ct(d,f);p+11||p>0&&xn(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ea(sr,Bi,"[yjs] ",Vi,ji,"Changed the client-id because another client seems to be using it."),s.clientID=Yi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new an;Gr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Gr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):co(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new Aa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&co(r,0)}}return o};class xa{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Kr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||vn(r,s))&&gr(s,!1)})},Qr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:y}=$s(c,d.id);y>0&&(p=st(l,D(p.id.client,p.id.clock+y))),d=p}!d.deleted&&i.some(p=>p===l.doc||vn(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||vn(p,d))&&!cn(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=Io(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class au extends Hs{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&en(f,w,S,A)});const d=zt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Us([b.deletions,c.deleteSet]),b.insertions=Us([b.insertions,f])}else u.push(new xa(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||vn(w,b))&&gr(b,!0)});const y=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",y):this.emit("stack-item-updated",y)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Kr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Kr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Qr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Qr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Oa(e){const t=E(e.restDecoder);for(let n=0;nNn(e,zi,an),Ra=(e,t)=>{if(e.constructor===dt){const{client:n,clock:s}=e.id;return new dt(D(n,s+t),e.length-t)}else if(e.constructor===gt){const{client:n,clock:s}=e.id;return new gt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Nn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Xt(a)));let r=s.map(a=>new lr(a,!0)),i=null;const o=new n,l=new cr(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===gt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===gt?i.struct.length-=p:f=Ra(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==gt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),ar(l);const c=s.map(a=>ir(a)),h=Us(c);return Ne(o,h),o.toUint8Array()},Ua=(e,t,n=xe,s=oe)=>{const r=to(t),i=new s,o=new cr(i),l=new n(Xt(e)),c=new lr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===gt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}ar(o);const h=ir(l);return Ne(i,h),i.toUint8Array()},ao=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ao(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{ao(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Xt(e)),i=new lr(r,!1),o=new s,l=new cr(o);for(let h=i.curr;h!==null;h=i.next())Pt(l,t(h),0);ar(l);const c=ir(r);return Ne(o,c),o.toUint8Array()},va=e=>Ma(e,Jl,xe,an),Zr="You must not compute changes after the event-handler fired.";class es{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Na(this.currentTarget,this.target))}deletes(t){return cn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=gs(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=gs(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=gs(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(Zr);const n=this.target,s=qt(),r=qt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Na=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},ho=80;let hr=0;class $a{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=hr++}}const Fa=e=>{e.timestamp=hr++},uo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=hr++},Ba=(e,t,n)=>{if(e.length>=ho){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>An(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&An(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},ss=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;At(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wr(),this._dEH=Wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw mt()}clone(){throw mt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){Yr(this._eH,t)}observeDeep(t){Yr(this._dEH,t)}unobserve(t){qr(this._eH,t)}unobserveDeep(t){qr(this._dEH,t)}toJSON(){}}const fo=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},go=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return sn(e,(s,r)=>{n.push(t(s,r,e))}),n},Va=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wo=(e,t)=>{e.doc??Z();const n=ns(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new hn(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,P(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new Tt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},mo=()=>Et("Length exceeded!"),yo=(e,t,n,s)=>{if(n>t._length)throw mo();if(n===0)return t._searchMarker&&nn(t._searchMarker,n,s.length),$n(e,t,null,s);const r=n,i=ns(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return $n(e,t,r,n)},ko=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=ns(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw mo();t._searchMarker&&nn(t._searchMarker,r,-i+s)},Fn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},ur=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new hn(s);break;case he:l=new un(s);break;default:if(s instanceof z)l=new Tt(s);else throw new Error("Unexpected content type")}new v(D(o,P(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},fr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},So=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},bo=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Ha=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},En=e=>(e.doc??Z(),na(e._map.entries(),t=>!t[1].deleted));class Pa extends es{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),ss(this,t,new Pa(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return wo(this,t)}toArray(){return go(this)}slice(t=0,n=this.length){return fo(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return po(this,t)}forEach(t){sn(this,t)}[Symbol.iterator](){return Va(this)}_write(t){t.writeTypeRef(gh)}}const Ja=e=>new Ee;class Wa extends es{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Oe extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Oe}clone(){const t=new Oe;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){ss(this,t,new Wa(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...En(this)].length}keys(){return bs(En(this),t=>t[0])}values(){return bs(En(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return bs(En(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return fr(this,t)}has(t){return bo(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Fn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ph)}}const Ya=e=>new Oe,Jt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Hl(e,t);class Ns{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===W?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ti=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===W?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?ns(t,n):null;if(i){const o=new Ns(i.p.left,i.p,i.index,r);return ti(e,o,n-i.index)}else{const o=new Ns(null,t._start,0,r);return ti(e,o,n)}},_o=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===W&&Jt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,P(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new W(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Eo=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===W&&Jt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Co=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Jt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,P(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new W(l,c)),n.right.integrate(e,0),n.forward()}}return o},_s=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r),c=s.constructor===String?new Dt(s):s instanceof z?new Tt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&nn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,P(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),_o(e,t,n,l)},ei=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Eo(n,r);const l=Co(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===W));){if(!n.right.deleted)switch(n.right.content.constructor){case W:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Jt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
-`;n.right=new v(D(o,P(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dt(c)),n.right.integrate(e,0),n.forward()}_o(e,t,n,l)},Do=(e,t,n,s,r)=>{let i=t;const o=rt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===W){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===W){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},qa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===W){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},za=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=rt();const o=Is(i);for(;r;)r.deleted===!1&&(r.content.constructor===W?$e(o,r.content):(t+=Do(n,s,r,i,o),i=Is(o),s=r)),r=r.right}),t},Ga=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&lo(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===W&&o.constructor!==dt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof dt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===W?t.add(i):qa(s,r)});for(const r of t)za(r)})},ni=(e,t,n)=>{const s=n,r=Is(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Tt:case ue:case Dt:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,y)=>{p!==null&&(d.attributes[y]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},jl(c)||(d.attributes=$l({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case Tt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case Dt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case W:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const y=r.get(d)??null;Jt(y,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Jt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const y=r.get(d)??null;Jt(y,p)||(l==="retain"&&f(),c[d]=y)}else if(!o.deleted){i.set(d,p);const y=c[d];y!==void 0&&(Jt(y,p)?y!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Le extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Le}clone(){const t=new Le;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Xa(this,t,n);ss(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Dt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new Ns(null,this._start,0,new Map);for(let i=0;i0)&&_s(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ei(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&ni(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,y)=>{f=!0,u[y]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case Dt:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case Tt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case W:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&Ms(u,t),n&&Ms(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),_s(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!s);_s(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{ni(r,Cn(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=Cn(i,this,t,!1);o.right!==null&&ei(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return fr(this,t)}getAttributes(){return So(this)}_write(t){t.writeTypeRef(wh)}}const Ka=e=>new Le;class Es{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Es(this,t)}querySelector(t){t=t.toUpperCase();const s=new Es(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Es(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){ss(this,t,new th(this,n,t))}toString(){return po(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),sn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{yo(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;$n(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Et("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return go(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return wo(this,t)}slice(t=0,n=this.length){return fo(this,t,n)}forEach(t){sn(this,t)}_write(t){t.writeTypeRef(yh)}}const Qa=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Bl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Fn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{ur(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return fr(this,t)}hasAttribute(t){return bo(this,t)}getAttributes(t){return t?Ha(this,t):So(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return sn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(mh),t.writeKey(this.nodeName)}}const Za=e=>new Re(e.readKey());class th extends es{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Bn extends Oe{constructor(t){super(),this.hookName=t}_copy(){return new Bn(this.hookName)}clone(){const t=new Bn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(kh),t.writeKey(this.hookName)}}const eh=e=>new Bn(e.readKey());class Vn extends Le{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Vn}clone(){const t=new Vn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sh)}}const nh=e=>new Vn;class dr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw mt()}mergeWith(t){return!1}write(t,n,s){throw mt()}integrate(t,n){throw mt()}}const sh=0;class dt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),oo(t.doc.store,this)}write(t,n){t.writeInfo(sh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class hn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new hn(this.content)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const rh=e=>new hn(e.readBuf());class rn{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rn(this.len)}splice(t){const n=new rn(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){en(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ih=e=>new rn(e.readLen()),Ao=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class un{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new un(Ao(this.doc.guid,this.opts))}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const oh=e=>new un(Ao(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const lh=e=>new ue(e.readJSON());class W{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new W(this.key,this.value)}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ch=e=>new W(e.readKey(),e.readJSON());class jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new jn(this.arr)}splice(t){const n=new jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const fh=e=>new Dt(e.readString()),dh=[Ja,Ya,Ka,Za,Qa,eh,nh],gh=0,ph=1,wh=2,mh=3,yh=4,kh=5,Sh=6;class Tt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Tt(this.type._copy())}splice(t){throw mt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const bh=e=>new Tt(dh[e.readTypeRef()](e)),$s=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Hn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},si=(e,t)=>js(e,n=>cn(n.deletions,t)),Io=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return st(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||Io(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=st(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:st(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||cn(s,u.right.id)||si(i.undoStack,u.right.id)||si(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=st(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=P(l,c),y=D(c,p),b=new v(y,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=y,gr(b,!0),b.integrate(e,0),b};class v extends dr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Rr:0}set marker(t){(this.info&ws)>0!==t&&(this.info^=ws)}get marker(){return(this.info&ws)>0}get keep(){return(this.info&Lr)>0}set keep(t){this.keep!==t&&(this.info^=Lr)}get countable(){return(this.info&Rr)>0}get deleted(){return(this.info&ps)>0}set deleted(t){this.deleted!==t&&(this.info^=ps)}markDeleted(){this.info|=ps}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=P(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=P(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=P(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=st(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===dt||this.right&&this.right.constructor===dt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===dt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=zr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),en(t.deleteSet,this.id.client,this.id.clock,this.length),Xr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw at();this.content.gc(t),n?Da(t,this,new dt(this.id,this.length)):this.content=new rn(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&Wn|(s===null?0:ct)|(r===null?0:Nt)|(i===null?0:Ge);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=so(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):at();i!==null&&t.writeString(i)}this.content.write(t,n)}}const To=(e,t)=>_h[t&Wn](e),_h=[()=>{at()},ih,ah,rh,fh,lh,ch,bh,uh,oh,()=>{at()}],Eh=10;class gt extends dr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){at()}write(t,n){t.writeInfo(Eh),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const xo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";xo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");xo[Oo]=!0;const Lo=new Map;class Ch{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:sc(n.newValue||"")}),Ml(this._onChange)}postMessage(t){pi.setItem(this.room,nc(Kl(t)))}close(){vl(this._onChange)}}const Dh=typeof BroadcastChannel>"u"?Ch:BroadcastChannel,pr=e=>At(Lo,e,()=>{const t=qt(),n=new Dh(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),Ah=(e,t)=>(pr(e).subs.add(t),t),Ih=(e,t)=>{const n=pr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Lo.delete(e)),s},me=(e,t,n=null)=>{const s=pr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Ro=0,wr=1,Uo=2,Fs=(e,t)=>{_(e,Ro);const n=ma(t);H(e,n)},Mo=(e,t,n)=>{_(e,wr),H(e,Zi(t,n))},Th=(e,t,n)=>Mo(t,n,K(e)),vo=(e,t,n,s)=>{try{Qi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},xh=(e,t)=>{_(e,Uo),H(e,t)},Oh=vo,Lh=(e,t,n,s,r)=>{const i=E(e);switch(i){case Ro:Th(e,t,n);break;case wr:vo(e,n,s,r);break;case Uo:Oh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rh=0,Uh=(e,t,n)=>{E(e)===Rh&&n(t,Wt(e))},Cs=3e4;class No extends tl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=zt();this.getLocalState()!==null&&Cs/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Cs<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&mr(this,s,"timeout")},yt(Cs/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:zt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const mr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},ze=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Xt(t),r=zt(),i=[],o=[],l=[],c=[],h=E(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},vh=e=>Vl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,$o=3,Ce=1,Nh=2,fn=[];fn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Lh(t,e,n.doc,n);s&&i===wr&&!n.synced&&(n.synced=!0)};fn[$o]=(e,t,n,s,r)=>{_(e,Ce),H(e,ze(n.awareness,Array.from(n.awareness.getStates().keys())))};fn[Ce]=(e,t,n,s,r)=>{Mh(n.awareness,K(t),n)};fn[Nh]=(e,t,n,s,r)=>{Uh(t,n.doc,(i,o)=>$h(n,o))};const ri=3e4,$h=(e,t)=>console.warn(`Permission denied to access ${e.url}.
-${t}`),Fo=(e,t,n)=>{const s=Xt(t),r=Q(),i=E(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},Fh=e=>!(e.code>=4400&&e.code<4500),Bs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,mr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Bo,Ps(el(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Bo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt();const s=Fo(e,new Uint8Array(n.data),!0);Js(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Bs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=zt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Fs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),H(s,ze(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},Ds=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Bh extends Hs{constructor(t,n,s,{connect:r=!0,awareness:i=new No(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=Fh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=fn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Fs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const y=Fo(this,new Uint8Array(d),!1);Js(y)>1&&me(this.bcChannel,B(y),this)}},this._updateHandler=(d,p)=>{if(p!==this){const y=Q();_(y,ne),xh(y,d),Ds(this,B(y))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:y},b)=>{const w=d.concat(p).concat(y),S=Q();_(S,Ce),H(S,ze(i,w)),Ds(this,B(S))},this._exitHandler=()=>{mr(this.awareness,[s.clientID],"app closed")},Gt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ri{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Ea(ka(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Bh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=Zi(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===ii||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let R;w===0?R=0:O===-w||O!==w&&S[O-1+w-1]=r&&N>=i){a=w;break}}h.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Kt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let y=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],A=u[w+1];(S>y||A>b)&&p.push({aS:n+y,aE:n+S,bS:n+b,bE:n+A}),y=S+1,b=A+1}return(yi.startsWith(o)&&(o===""||o.endsWith(`
-`)||i[o.length]===`
-`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Yh(e,t)<=0?e+t:t+e:null}function Jn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=bt(e,s),l=bt(t,s),c=bt(n,s),h=_t(o,i),a=[...Ue(h,_t(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,_t(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",R=S;for(const N of b)N.side===w&&(O+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return O+u(o,R,A)};let d="",p=0,y=0;for(;yF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),R=f(b,1,w,S);if(O===R){d+=O;continue}if(w===S){const F=qh(O,R,s!==As,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===As)return null;const N=s===Pn?Jn(u(o,w,S),O,R,As):Jn(u(o,w,S),O,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(`
-`)?e:e+`
-`;function Vo(e,t,n,s){let r=t.endsWith(`
-`);return r===e.endsWith(`
-`)&&(r=n.endsWith(`
-`)),s===""||r===s.endsWith(`
-`)?s:r?s+`
-`:s.slice(0,-1)}function zh(e,t,n){const s=Jn(se(e),se(t),se(n),Yt);return s===null?{ok:!1}:{ok:!0,text:Vo(e,t,n,s)}}function hu(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Jn(se(e),se(t),se(n),Yt,!0)??se(n);return Vo(e,t,n,s)}function Gh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(`
-`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Xh(e,t,n,s){const r=zh(t,n,s);return!r.ok||n===s||n===t||s===t||Gh(e,r.text)?r:{ok:!1}}function oi(e,t){if(e===t)return[];const n=[],s=new Map,r=bt(e,Yt),i=bt(t,Yt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),y=y.slice(w,y.length-S),(p.length||y.length)&&s.push({index:b,deleteCount:p.length,insertText:y}),h=f,a=d}}function Dn(e,t,n){const s=new Map,r=_t(bt(t,Yt),s),i=Ue(_t(bt(e,Yt),s),r),o=Ue(r,_t(bt(n,Yt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(`
-`);return!(l(t)!==l(e)&&l(n)!==l(t))}function Ye(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const li=700,pe=[2e3,4e3,8e3,15e3],ci=2e3,Qh=4,Zh=64,tu=8,eu=32e3,nu=32;function uu(e){const t=(g,k,m)=>Xh(e.path,g,k,m);let n=e.seed,s=e.baseSha;const r=(g,k)=>{n=g,i=k,ot(k);const m=Bt.lastIndexOf(g);m>=0?Bt.splice(0,m+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const k=[];for(let m=g;m!==null&&k.length<4;m=m.prev)m.sent!==m.from&&!k.includes(m.sent)&&k.push(m.sent);return k.length?k:void 0},l=(g,k=tt)=>{const m=o(k);return i&&i===s&&n.length>eu?{base:s,text:g,...m?{prior_sent:m}:{}}:{base:s,base_text:n,text:g,...m?{prior_sent:m}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,y=!1,b=!1,w=!1,S=null,A=null,O="",R=0;const N=(g=Date.now())=>{const k=Math.max(g,R+1e3);return R=k,Go(e.path,e.who||"browser",new Date(k))},F=new Map;let Kt=0,xt=!1,ht=null,Fe=0,rs=!1,tt=null,Ot=!1;const Bt=[],yr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>nu&&Bt.shift())};let kt=!1,Be=null,Qt=0;const Ve=()=>{kt=!1,Be=null},is=g=>{Qt===g&&Ve()};let it=0,pt=0,dn=null,Zt=null,os=!1,Vt=null,Lt=null,je=!1,te=null,ut=null;const $=g=>e.onState?.(g),gn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),jt=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let pn=null,ls=0;const He=()=>{clearTimeout(pn??void 0),pn=null},wn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const m=pe[Math.min(ls,pe.length-1)];ls++,pn=setTimeout(()=>{pn=null,!f&&!a&&Pe()},m)},kr=()=>{He(),ls=0},mn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},li)},Rt=g=>{if(f)return p=g,!0;const k=L();if(k===g)return!0;const m=oi(k,g);if(Cr())return x.applySplices(m),!0;if(!e.soloApply)return!1;for(const I of m)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(y)return b?Promise.resolve():Je();if(Zt)return os=!0,Zt;const g=(async()=>{try{for(;Vt;)await Vt;await jo()}finally{Zt=null}})();return Zt=g,g},jo=async()=>{let g=0;for(;;){if(os=!1,Y||a||w)return;const k=L();if(k===n&&!Ot){$("clean");return}if($("saving"),e.onWriting?.(),xt){if(S!==null&&A===k){if(await yn(k,O)==="stop")return;continue}xt=!1}const m=c||h?await Ho(k):await Jo(k);if(m==="stop")return;if(m==="rebased"){if(++g>Qh){await yn(L(),s??"");return}continue}if(!os){$(L()===n&&!Ot?"clean":"dirty");return}}};let wt=!1;const Ho=async g=>{Lt=g,je=!1;let k;try{k=await bn(gn(e.path),g,s,wt)}catch(m){return Lt=null,m instanceof et&&m.status===422&&Ye(m)?(wt=!1,ee(g),"stop"):m instanceof et&&m.status===409?await cs(n,!1)?"rebased":"stop":($("error"),wn(m),"stop")}return Lt=null,wt=!1,kr(),k.merged?await cs(g,!0)?"rebased":"stop":(je||r(g,k.sha),e.onSaved?.(g),"done")},cs=async(g,k)=>{let m;try{m=await xr(Or(e.apiBase,e.path))}catch(U){return $("error"),L()!==n&&wn(U),!1}if(m.kind!=="text")return $("error"),!1;const I=L(),C=t(g,m.text,I);return!C.ok||!Rt(C.text)?(k&&ot(m.sha),await yn(I,m.sha??"")==="rebased"):(r(m.text,m.sha),k&&e.onSaved?.(m.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let k=null;for(let m=tt;m!==null;m=m.prev)if(m.sent!==m.from&&Dn(m.from,m.sent,g.text)){k=m;break}if(tt=null,k){Ot=!0;const m=t(k.sent,g.text,L());m.ok&&Rt(m.text)?(n=g.text,i=void 0,ot(g.sha)):(n=k.sent,i=void 0)}},Jo=async g=>{Lt=g,je=!1;let k;const m=tt;try{tt={sent:g,from:n,prev:m},k=await Ht(jt,{...l(g,m),...wt?{confirm_shrink:!0}:{}})}catch(C){if(Lt=null,C instanceof et&&[400,401,403,404,405,409,413].includes(C.status)&&(tt=m),C instanceof et&&(C.status===404||C.status===405))return h=!0,"rebased";if(C instanceof et&&C.status===422&&Ye(C))return wt=!1,ee(g),"stop";if(C instanceof et&&C.status===409&&!a){let U={};try{U=JSON.parse(C.body)}catch{}const j=typeof U.text=="string"?U.text:null;if(j!==null){const X=t(n,j,L());if(X.ok&&Rt(X.text))return n=j,i=void 0,ot(U.sha),"rebased"}return yn(L(),U.sha??"")}return $(a?"dirty":"error"),wn(C),"stop"}if(Lt=null,wt=!1,kr(),k.update&&x.applyRemoteUpdate(k.update),tt=null,Ot=!1,a)return"stop";const I=t(g,k.text,L());return I.ok&&Rt(I.text)&&(je||r(k.text,k.sha)),e.onSaved?.(k.text),"done"};let Y=null;const ee=g=>{Y||f||!e.onShrinkRefused||($("error"),Y={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const k=it,m=Qt;try{const I=await Ht(jt,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),as(k,m);const C=!kt&&pt>=it;$(C?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&pt{if(!f)try{const k=await xr(Or(e.apiBase,e.path));if(f||k.kind!=="text")return;if(r(k.text,k.sha),Rt(k.text),Y=null,a&&!u){if(await fe(!1),f)return;$(pt>=it&&!kt?"clean":"dirty");return}pt=it,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{Y=null}}},e.onShrinkRefused(Y))};let ft=null;const Wo=()=>{ft&&clearTimeout(ft),ft=setTimeout(()=>{const g=L();Tr(de(n),de(g))&&ee(g)},li)},Sr=async(g,k,m=N())=>{const I=++Kt;let C=m;for(let U=1;;U++){const j=C;F.set(j,g);try{return await bn(gn(j),g,void 0,!1,!1,!1,!0),I===Kt&&!a&&(n=g,i=void 0,k&&(s=k),$("clean")),e.onConflictCopy?.(j),null}catch(X){if(X instanceof et&&X.status===409&&U{const C=(U,j)=>{bn(gn(U),k,void 0,!1,!0,!0,!0).then(X=>I?.(X.parked??U),X=>{if(X instanceof et&&X.status===409&&j{(S===null||A!==g)&&(S=N(),A=g);const m=S;O=k,xt=!0;const I=await Sr(g,k,m);return f?"stop":I?(wn(I.err),"stop"):(xt=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},as=(g,k)=>{pt=Math.max(pt,g),is(k),!(f||u)&&(d=it-pt,e.onPending?.(d))},Yo=()=>{f||u||Y||ut||(ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci))},fe=g=>{if(clearTimeout(ut??void 0),ut=null,g){if(pt>=it)return Promise.resolve();const m=it,I=Qt;return Ht(jt,{update:x.encodeState(),base:s},!0).then(C=>{ot(C.sha),as(m,I)})}if(dn)return dn;const k=(async()=>{try{for(;!u&&!f&&!Y&&pt{y=!1,S=null,A=null,Fe=0,clearTimeout(ht??void 0),ht=null,Ot=!1,a=!0,yr(x.text.toString()),g?.(),rs&&(rs=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ht??void 0),ht=null,te&&clearTimeout(te),te=null,Zt||Vt){w=!0;try{for(;Zt||Vt;)await(Zt??Vt)}finally{w=!1}if(f||a)return;if(!u){L()!==n&&mn();return}}if(tt!==null&&!h){let j;w=!0;try{j=await Ht(jt,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Po(j),!u){(L()!==n||Ot)&&mn();return}}const g=e.soloText?.();if(g===void 0||g===n)return hs();const k=x.text.toString(),m=t(n,k,g);if(m.ok)return hs(()=>x.applySplices(oi(k,m.text)));y=!0,(S===null||A!==g)&&(S=N(),A=g),b=!0;let I;try{I=await Sr(g,s??"",S)}finally{b=!1}if(f)return;if(!I)return e.soloText?.()!==g?(S=null,A=null,Je()):hs(()=>{n=x.text.toString()});const C=I.err;if(C instanceof et&&!(C.status>=500||C.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ht=setTimeout(()=>{ht=null,Je()},U)},x=new Vh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(ut&&clearTimeout(ut),ut=null,He(),a||Je(),pt=it,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):rs=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),_r=(g,k)=>{const m=a?x.text.toString():null;if(m!==null&&yr(m),!x.isRemote(k?.origin)){if($("dirty"),a){kt=!0,Be=m,Qt+=1,u||(it+=1,d=it-pt,e.onPending?.(d),clearTimeout(ut??void 0),ut=setTimeout(()=>{ut=null,!u&&!f&&fe(!1)},ci)),Wo();return}mn()}};x.text.observe(_r);const Er=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Er),Hh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Cr()?x.text.toString():e.soloText?.()??"",Cr=()=>a||c&&x.text.length>0,ot=g=>{g&&(s=g)},qo=(g,k,m)=>{if(m?.held)return r(g,k),"same";if(g===n||g===Lt)return ot(k),"same";const I=L();if(g===I)return r(g,k),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||Dn(U,g,I)?(r(g,k),kt&&(Be===null||g===Be||Dn(U,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,k),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const C=t(n,g,I);return C.ok?(Lt!==null&&(je=!0),r(g,k),Rt(C.text),C.text!==g?mn():Lt===null&&$("clean"),C.text===I?"same":"merged"):"blocked"};let kn=null;const zo=()=>{if(!f){if(Y)return Promise.resolve();if((a?u?kt:d>0:L()!==n)&&!wt&&e.onShrinkRefused&&Tr(de(n),de(L())))return clearTimeout(ft??void 0),ft=null,ee(L()),Promise.resolve()}if(!a)return Pe();if(f)return Promise.resolve();if(!u)return d>0?fe(!1):Promise.resolve();if(!kt)return Promise.resolve();if(kn)return kn;const g=Qt;$("saving");const k=(async()=>{try{const m=await Ht(jt,{update:x.encodeState()});if(f)return;m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),is(g),$(kt?"dirty":"clean"),e.onSaved?.(n)}catch(m){if(f||m instanceof et&&m.status===422&&Ye(m)&&(clearTimeout(ft??void 0),ft=null,ee(L()),Y))return;$(kt?"dirty":"clean")}finally{kn=null}})();return kn=k,k};let Ut=null;const Sn=g=>()=>{Ut===g&&(Ut=null)},Dr=(g,k)=>{if(Y)return;if(a){const T=!u&&d>0;if(!T&&!(u&&kt))return;const V="room\0"+x.text.toString();if(Ut===V)return;Ut=V;const Mt=Qt;(T?fe(!0):Ht(jt,{update:x.encodeState()},!0).then(ds=>ot(ds.sha))).then(()=>is(Mt),Sn(V));return}if(y||xt){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let V=S!==null&&A===g?S:null;for(const[Mt,lt]of F)V===null&<===g&&(V=Mt);V??=N(),br(V,g,T);return}if(g===n&&!Ot)return;const m="text\0"+g;if(Ut===m)return;if((c||h)&&!k){Pe();return}Ut=m;const I=n,C=!(c||h),U=tt,j={sent:g,from:I,prev:U};C&&(tt=j);const X=T=>{if(C&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&tt===j&&(tt=U),T instanceof et&&T.status===422&&Ye(T)){Sn(m)(),f||(clearTimeout(ft??void 0),ft=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return Sn(m)();let V={};try{const lt=JSON.parse(T.body);lt&&typeof lt=="object"&&(V=lt)}catch{}if(typeof V.text=="string"&&(V.text===g||Dn(I,g,V.text))){if(!f&&!a){const lt=t(g,V.text,L());lt.ok&&Rt(lt.text)&&(n=V.text,i=void 0,typeof V.sha=="string"&&ot(V.sha))}return}if(!g.trim())return;xt=!0;let Mt=S!==null&&A===g?S:null;for(const[lt,ds]of F)Mt===null&&ds===g&&(Mt=lt);Mt??=N(),S=Mt,A=g,br(Mt,g,m,lt=>{xt=!1,e.onConflictCopy?.(lt)})},We=(T,V)=>{n=g,i=void 0,ot(V),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let us;C?us=Ht(jt,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(wt=!1,tt===j&&(tt=null),Ot=!1,T.parked)return We(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ot(T.sha);return}const V=t(g,T.text,L());V.ok&&Rt(V.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},X):us=bn(gn(e.path),g,s,wt,!0,!0).then(T=>{if(wt=!1,T.parked)return We(T.parked,T.sha);if(T.merged){f?ot(T.sha):cs(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},X);const fs=us.then(()=>{},()=>{});Vt=fs,fs.then(()=>{Vt===fs&&(Vt=null)})},Ar=()=>{f||Dr(L(),!0)},Ir=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ar),window.addEventListener("pageshow",Ir)),{collab:x,current:L,merge:qo,rebase:ot,saveNow:zo,askingShrink:()=>Y!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ar),window.removeEventListener("pageshow",Ir)),clearTimeout(te??void 0),clearTimeout(ft??void 0),He(),clearTimeout(ht??void 0),ht=null;const g=L();f=!0,p=g,Y?e.onShrinkWithdrawn?.(Y):Dr(g,!1),clearTimeout(ut??void 0),x.awareness.off("change",Er),x.text.unobserve(_r),x.destroy()}}}export{he as D,li as S,au as U,lu as a,ka as b,Ea as c,oi as d,cu as e,Ps as f,ae as g,ru as h,vt as i,hu as m,uu as o,ou as r,iu as t};
diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html
index 70d04ab7..715523ef 100644
--- a/internal/webapp/static/index.html
+++ b/internal/webapp/static/index.html
@@ -9,7 +9,7 @@
 
 BearDrive
 
-  
+  
   
   
   

From 647e5fb23d403f78173aee4da2a94d4887be30d3 Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Wed, 11 Nov 2026 23:26:26 +0900
Subject: [PATCH 11/34] fix(webapp): drain VisualEdit iframe patches via
 bd-edit:flush ACK before saveNow

---
 architecture/webapp-frontend.md               |   4 +-
 .../frontend/src/components/VisualEdit.tsx    |  75 ++++++++--
 internal/webapp/frontend/src/inline-edit.ts   |  15 +-
 .../webapp/frontend/src/lib/frameflush.ts     |  75 ++++++++++
 .../src/lib/sharedfile_restore.test.ts        | 135 ++++++++++++++++++
 ...{Editor--_Kdbq8f.js => Editor-vslxZvKp.js} |   2 +-
 .../static/assets/VisualEdit-DEcaIEmO.js      |   1 -
 .../static/assets/VisualEdit-ZWfN9slK.js      |   1 +
 .../{index-COodWbrp.js => index-C9ixuBUD.js}  |   4 +-
 ...ile-BEKa8tPX.js => sharedfile-CNg6aQyd.js} |   2 +-
 internal/webapp/static/index.html             |   2 +-
 internal/webapp/static/inline-edit.js         |  26 ++--
 12 files changed, 309 insertions(+), 33 deletions(-)
 create mode 100644 internal/webapp/frontend/src/lib/frameflush.ts
 rename internal/webapp/static/assets/{Editor--_Kdbq8f.js => Editor-vslxZvKp.js} (99%)
 delete mode 100644 internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
 create mode 100644 internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
 rename internal/webapp/static/assets/{index-COodWbrp.js => index-C9ixuBUD.js} (99%)
 rename internal/webapp/static/assets/{sharedfile-BEKa8tPX.js => sharedfile-CNg6aQyd.js} (99%)

diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md
index 7218825e..56723eec 100644
--- a/architecture/webapp-frontend.md
+++ b/architecture/webapp-frontend.md
@@ -190,6 +190,7 @@ classDiagram
         +collab.ts CollabDoc peerCount isRemote onStalled encodeState applySplices applyRemoteUpdate (y-websocket to the hub-held document; stop only when there is no room route)
         +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once)
         +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them)
+        +frameflush.ts frameChannel FrameChannel (FIFO queue of iframe messages; drain posts bd-edit:flush and waits for bd-edit:flushed)
         +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink
         +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room)
         +sharedfile.ts rebase (the head sha moved because a co-editor saved)
@@ -233,6 +234,7 @@ classDiagram
     components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand)
     note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain 
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
     note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow (Promise<boolean>) + askingShrink, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation"
+    note for lib "frameflush.ts is VisualEdit's side of the iframe's postMessage stream. frameChannel handles every message strictly in arrival order, each after the one before it finishes (anchoring is async), so an edit typed just before Done cannot still be queued when the save looks at the buffer. Before VisualEdit's saveNow, drain() posts bd-edit:flush with an id; inline-edit.ts posts any edit it still holds and then answers bd-edit:flushed with that id on the same channel, so once the answer is handled every earlier patch is in the document. A drain waits as long as the frame is there to answer, never on a timer, and gives up only when the frame is gone or the editor closes"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
@@ -244,7 +246,7 @@ classDiagram
     shareMermaid --> lib : renderMermaid
     inlineComment --> lib : anchor.ts (no app imports)
     components --> lib : rangeFor describe hitTest (Comments)
-    components --> lib : merge3PreferRight diffSplices (VisualEdit), saveNow askingShrink (FileView flush)
+    components --> lib : merge3PreferRight diffSplices frameChannel (VisualEdit), saveNow askingShrink (FileView flush)
     Browser ..> components : Done awaits FileView's flushRef
     lib --> api : syncCollab putText keepalive (sharedfile)
     components ..> inlineComment : postMessage via the ?comment=1 iframe
diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx
index be7642f1..6a441252 100644
--- a/internal/webapp/frontend/src/components/VisualEdit.tsx
+++ b/internal/webapp/frontend/src/components/VisualEdit.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
 import * as Y from "yjs";
 import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile";
 import { diffSplices, merge3PreferRight } from "../lib/merge3";
+import { frameChannel } from "../lib/frameflush";
 import { type CollabStatus } from "../lib/collab";
 import { askShrink, withdrawShrink } from "./ShrinkDialog";
 
@@ -26,12 +27,14 @@ import { askShrink, withdrawShrink } from "./ShrinkDialog";
    and somebody typing markup in the source editor are in one room, and a
    patch from either merges with the other. */
 
-// What the injected script sends up. It can send nothing else, and this
-// component sends nothing down.
+// What the injected script sends up. The one thing sent down is a flush
+// request (lib/frameflush.ts), answered by `bd-edit:flushed` after every patch
+// the frame held.
 type Ready = { type: "bd-edit:ready"; hash: string; len: number; ranges: Span[] };
 type Patch = { type: "bd-edit:patch"; start: number; end: number; html: string };
 type Clobbered = { type: "bd-edit:clobbered" };
-type FromFrame = Ready | Patch | Clobbered;
+type Flushed = { type: "bd-edit:flushed"; id: number };
+type FromFrame = Ready | Patch | Clobbered | Flushed;
 
 type Span = { start: number; end: number };
 
@@ -235,7 +238,43 @@ export function VisualEdit({
         });
       },
     }));
-    if (handle) handle.current = file;
+    /* Messages from the frame, handled one at a time in arrival order; Done's
+       save first drains them (frame.current answers a flush only after every
+       patch it posted before), so a word typed just before Done is in the
+       document — and in its save, shrink check and failure — before the save
+       decides whether the editor may close. */
+    const channel = frameChannel();
+    let frameReady = false;
+    const drainFrame = async () => {
+      const el = frame.current;
+      const win = el?.contentWindow;
+      if (!el || !win) return;
+      // A frame that reloads or is replaced cannot answer: stop waiting then.
+      let reloaded = false;
+      const onLoad = () => {
+        reloaded = true;
+      };
+      el.addEventListener("load", onLoad);
+      try {
+        await channel.drain(
+          (m) => win.postMessage(m, "*"),
+          () => !frameReady || reloaded || frame.current !== el || el.contentWindow !== win,
+        );
+      } finally {
+        el.removeEventListener("load", onLoad);
+      }
+      // Saving now: the idle save the last patch armed has nothing left to do.
+      clearTimeout(stageTimer);
+      stageTimer = undefined;
+    };
+    const exposed: SharedFile = {
+      ...file,
+      saveNow: async () => {
+        await drainFrame();
+        return file.saveNow();
+      },
+    };
+    if (handle) handle.current = exposed;
 
     /* Ranges are held as RELATIVE positions, not offsets.
 
@@ -320,13 +359,11 @@ export function VisualEdit({
     let srcLen = -1;
     let anchored = false;
 
-    const onMessage = async (e: MessageEvent) => {
-      // The iframe is sandboxed WITHOUT allow-same-origin, so its origin is
-      // the string "null" and checking it proves nothing. Identity has to come
-      // from the window itself.
-      if (!frame.current || e.source !== frame.current.contentWindow) return;
-      const msg = e.data as FromFrame;
-      if (!msg || typeof msg !== "object") return;
+    const handleMessage = async (msg: FromFrame) => {
+      if (msg.type === "bd-edit:flushed") {
+        channel.flushed(msg.id);
+        return;
+      }
 
       if (msg.type === "bd-edit:clobbered") {
         setWarning(
@@ -339,11 +376,13 @@ export function VisualEdit({
         ranges = msg.ranges;
         srcHash = msg.hash;
         srcLen = msg.len;
+        frameReady = true;
         await anchorRanges(); // no-op until the document is seeded too
         return;
       }
 
       if (msg.type !== "bd-edit:patch") return;
+      if (!anchored) await anchorRanges();
       const a = anchors.get(key(msg));
       if (!a) return; // a range from a render this side has already replaced
       if (stageDoc) {
@@ -427,6 +466,16 @@ export function VisualEdit({
         diffSplices(live, want).map((s) => ({ ...s, index: s.index + from.index })),
       );
     };
+    const onMessage = (e: MessageEvent) => {
+      // The iframe is sandboxed WITHOUT allow-same-origin, so its origin is
+      // the string "null" and checking it proves nothing. Identity has to come
+      // from the window itself — checked as the message arrives, since the
+      // frame may be replaced before its turn in the queue comes.
+      if (!frame.current || e.source !== frame.current.contentWindow) return;
+      const msg = e.data as FromFrame;
+      if (!msg || typeof msg !== "object") return;
+      channel.enqueue(() => handleMessage(msg));
+    };
 
     // The document filling in is itself a reason to try anchoring again: the
     // relay may seed AFTER onReady fires, and a peer's first update is the
@@ -436,7 +485,9 @@ export function VisualEdit({
 
     window.addEventListener("message", onMessage);
     return () => {
-      if (handle?.current === file) handle.current = null;
+      if (handle?.current === exposed) handle.current = null;
+      frameReady = false;
+      channel.close();
       clearTimeout(retryTimer);
       clearTimeout(stuckTimer);
       clearTimeout(stageTimer);
diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts
index 9b60966a..6b900a5f 100644
--- a/internal/webapp/frontend/src/inline-edit.ts
+++ b/internal/webapp/frontend/src/inline-edit.ts
@@ -5,7 +5,9 @@
    (server.go's serveEditable). A reader never downloads an editor, and the
    iframe keeps exactly the sandbox it always had — no allow-same-origin — so
    nothing here can reach the hub's session. It talks to the app by postMessage
-   and accepts nothing back.
+   and accepts one thing back: `bd-edit:flush` (with a numeric id), which posts
+   any edit still held here and answers `bd-edit:flushed` with that id, so the
+   app's Done saves only after every patch before the answer has landed.
 
    Three things had to be true at once, and they decided the design:
 
@@ -385,3 +387,14 @@ send({
 document.documentElement.setAttribute("data-bd-ready", "");
 
 window.addEventListener("beforeunload", unmount);
+
+/* Done in the app: post what the open editor holds, then answer. The answer
+   follows every patch on the same channel, so once the app has handled it, it
+   has handled them all. Only the app (the parent window) may ask. */
+window.addEventListener("message", (e) => {
+  if (e.source !== window.parent) return;
+  const msg = e.data as { type?: unknown; id?: unknown } | null;
+  if (!msg || msg.type !== "bd-edit:flush" || typeof msg.id !== "number") return;
+  flush();
+  send({ type: "bd-edit:flushed", id: msg.id });
+});
diff --git a/internal/webapp/frontend/src/lib/frameflush.ts b/internal/webapp/frontend/src/lib/frameflush.ts
new file mode 100644
index 00000000..9cfe2b4c
--- /dev/null
+++ b/internal/webapp/frontend/src/lib/frameflush.ts
@@ -0,0 +1,75 @@
+/* The visual editor's side of the iframe's message stream, in order.
+
+   Edits reach the app from the sandboxed iframe as postMessage, which is
+   asynchronous: a word typed just before Done may still be in the queue when
+   Done asks the file to save, and a save that sees a clean buffer answers at
+   once — the editor closed, and the word never met the save (or the shrink
+   check, or the failure) that would have kept it open.
+
+   So every message is handled strictly in arrival order, each after the one
+   before it has finished (anchoring is async), and draining asks the frame to
+   post what it holds and answer `bd-edit:flushed`. The frame sends that answer
+   after its last patch on the same channel, so by the time it is handled here
+   every patch before it has been spliced into the document. */
+
+export type FlushRequest = { type: "bd-edit:flush"; id: number };
+
+export type FrameChannel = {
+  /** Handle one message, after every message before it has been handled. */
+  enqueue(handle: () => unknown): void;
+  /** The frame answered flush request `id` (called from a queued handler). */
+  flushed(id: number): void;
+  /** Ask the frame for everything it holds and wait until it has been
+      handled. Waits as long as the frame is there to answer — never on a
+      timer — and gives up only once `gone()` says it cannot. */
+  drain(post: (msg: FlushRequest) => void, gone: () => boolean): Promise;
+  /** The editor is going: nothing waits on the frame any more. */
+  close(): void;
+};
+
+// How often a drain checks that the frame it asked is still there to answer.
+const GONE_POLL_MS = 50;
+
+export function frameChannel(): FrameChannel {
+  let queue: Promise = Promise.resolve();
+  const waiting = new Map void>();
+  let seq = 0;
+  let closed = false;
+  const settled = () => queue.then(() => {});
+  return {
+    enqueue(handle) {
+      // A handler that throws must not stall every message after it.
+      queue = queue.then(handle).catch(() => {});
+    },
+    flushed(id) {
+      waiting.get(id)?.();
+      waiting.delete(id);
+    },
+    async drain(post, gone) {
+      await settled();
+      if (closed || gone()) return;
+      const id = ++seq;
+      let poll: ReturnType | undefined;
+      const answered = new Promise((resolve) => {
+        waiting.set(id, resolve);
+        poll = setInterval(() => {
+          if (!closed && !gone()) return;
+          waiting.delete(id);
+          resolve();
+        }, GONE_POLL_MS);
+      });
+      try {
+        post({ type: "bd-edit:flush", id });
+        await answered;
+      } finally {
+        clearInterval(poll);
+      }
+      await settled();
+    },
+    close() {
+      closed = true;
+      for (const resolve of waiting.values()) resolve();
+      waiting.clear();
+    },
+  };
+}
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index a022ac28..c73f8436 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -54,6 +54,7 @@ const { CollabDoc } = await import("./collab.ts");
 const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts");
 const { parseConflict } = await import("./conflict.ts");
 const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts");
+const { frameChannel } = await import("./frameflush.ts");
 
 /* toEqual's semantics: a property that is undefined is a property that is
    absent. Only plain objects and arrays are rebuilt; anything else (a
@@ -2476,3 +2477,137 @@ for (const keepAnswer of [200, 503]) {
     }
   });
 }
+
+/* VisualEdit's Done: the iframe's last patch may still be in the postMessage
+   queue when Done asks the file to save. Saving then sees a clean buffer and
+   answers true, and the editor closes before the shrink check or the failure
+   that patch would meet. Draining first — flush request, the frame posts what
+   it holds, then `bd-edit:flushed` on the same channel — puts the patch in
+   the document before the save decides. `frame` stands in for the iframe:
+   `deliver` is a message arriving on window "message", later, in order. */
+function frameHarness(answer: (body: string) => Response) {
+  const puts: string[] = [];
+  globalThis.fetch = (async (_url: RequestInfo | URL, init?: RequestInit) => {
+    puts.push(String(init?.body));
+    return answer(String(init?.body));
+  }) as typeof fetch;
+  const state = { buffer: "a\nb\nc\n" };
+  const asks: ShrinkAsk[] = [];
+  let solo = false;
+  const file = openSharedFile({
+    apiBase: "/api/",
+    path: "page.html",
+    seed: "a\nb\nc\n",
+    baseSha: "sha-a",
+    me: { name: "t", colour: "oklch(0.7 0.1 200)" },
+    onReady: () => {},
+    onSolo: () => {
+      solo = true;
+    },
+    onShrinkRefused: (a) => asks.push(a),
+    soloText: () => state.buffer,
+    soloApply: (e) => {
+      state.buffer = state.buffer.slice(0, e.from) + e.insert + state.buffer.slice(e.to);
+    },
+  });
+  const channel = frameChannel();
+  type Msg = { type: "patch"; text: string } | { type: "flushed"; id: number };
+  // window "message" delivery: a later task, in posting order.
+  const deliver = (msg: Msg) =>
+    setImmediate(() =>
+      channel.enqueue(async () => {
+        await Promise.resolve(); // anchoring is async; order must still hold
+        if (msg.type === "patch") state.buffer = msg.text;
+        else channel.flushed(msg.id);
+      }),
+    );
+  const frame = { gone: false, answers: true, flushes: 0 };
+  const post = (m: { type: "bd-edit:flush"; id: number }) => {
+    frame.flushes++;
+    if (frame.answers) deliver({ type: "flushed", id: m.id });
+  };
+  // VisualEdit's exposed saveNow.
+  const saveNow = async () => {
+    await channel.drain(post, () => frame.gone);
+    return file.saveNow();
+  };
+  const ready = () => waitFor(() => assert.equal(solo, true));
+  return { file, state, asks, puts, channel, deliver, frame, saveNow, ready };
+}
+
+test("Done drains the frame's queued patch before saving: a sharp shrink in it asks", async () => {
+  const h = frameHarness(() => new Response(JSON.stringify({ sha: "sha-b" }), { status: 200 }));
+  try {
+    await h.ready();
+    // The user deleted the page and clicked Done at once: the patch is still
+    // on its way when Done runs.
+    h.deliver({ type: "patch", text: "" });
+    assert.equal(await h.saveNow(), false);
+    assert.equal(h.frame.flushes, 1);
+    assert.equal(h.state.buffer, "");
+    assert.equal(h.file.askingShrink(), true);
+    assert.equal(h.asks.length, 1);
+    same(h.puts, []); // asked before anything was sent
+  } finally {
+    h.channel.close();
+    h.file.destroy();
+  }
+});
+
+test("Done drains the frame's queued patch before saving: a failed save keeps the editor", async () => {
+  const h = frameHarness(() => new Response("unavailable", { status: 503 }));
+  try {
+    await h.ready();
+    h.deliver({ type: "patch", text: "a\nb\nc\nd\n" });
+    assert.equal(await h.saveNow(), false); // the patch met the 503
+    same(h.puts, ["a\nb\nc\nd\n"]);
+  } finally {
+    h.channel.close();
+    h.file.destroy();
+    await settle();
+  }
+});
+
+test("Done's drain lands every queued patch in order, then saves once", async () => {
+  const h = frameHarness((body) => new Response(JSON.stringify({ sha: "sha-" + body.length }), { status: 200 }));
+  try {
+    await h.ready();
+    h.deliver({ type: "patch", text: "a\nb\nc\nd\n" });
+    h.deliver({ type: "patch", text: "a\nb\nc\nd\ne\n" });
+    assert.equal(await h.saveNow(), true);
+    same(h.puts, ["a\nb\nc\nd\ne\n"]);
+    // Nothing held, nothing owed: the next Done answers without a request.
+    assert.equal(await h.saveNow(), true);
+    assert.equal(h.frame.flushes, 2);
+    same(h.puts, ["a\nb\nc\nd\ne\n"]);
+  } finally {
+    h.channel.close();
+    h.file.destroy();
+  }
+});
+
+/* A frame that never answers — reloaded, replaced, never ready — is not
+   waited on: the drain checks it is still there and stops once it is not.
+   One that is there is waited on, with no timer to leave on. */
+test("Done's drain waits on a live frame and stops once the frame is gone", async () => {
+  fakeTimers();
+  const h = frameHarness(() => new Response(JSON.stringify({ sha: "sha-b" }), { status: 200 }));
+  try {
+    await h.ready();
+    h.frame.answers = false;
+    let result: boolean | null = null;
+    void h.saveNow().then((r) => {
+      result = r;
+    });
+    await advance(60_000);
+    assert.equal(result, null); // still there: still waited on
+    h.frame.gone = true;
+    await advance(50);
+    assert.equal(result, true); // gone: nothing it held can arrive; clean
+    same(h.puts, []);
+  } finally {
+    h.channel.close();
+    h.file.destroy();
+    realTimers();
+  }
+});
diff --git a/internal/webapp/static/assets/Editor--_Kdbq8f.js b/internal/webapp/static/assets/Editor-vslxZvKp.js
similarity index 99%
rename from internal/webapp/static/assets/Editor--_Kdbq8f.js
rename to internal/webapp/static/assets/Editor-vslxZvKp.js
index 73e33284..438fcfe4 100644
--- a/internal/webapp/static/assets/Editor--_Kdbq8f.js
+++ b/internal/webapp/static/assets/Editor-vslxZvKp.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-COodWbrp.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BEKa8tPX.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-C9ixuBUD.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CNg6aQyd.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-DEcaIEmO.js b/internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
deleted file mode 100644
index e92ffff0..00000000
--- a/internal/webapp/static/assets/VisualEdit-DEcaIEmO.js
+++ /dev/null
@@ -1 +0,0 @@
-import{r as i,j as y,w as ge,a as me}from"./index-COodWbrp.js";import{o as pe,D as he,c as T,a as C,m as oe,d as se}from"./sharedfile-BEKa8tPX.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";async function be(E){if(!globalThis.crypto?.subtle)return null;try{const k=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(E));return[...new Uint8Array(k)].map(m=>m.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ee({apiBase:E,fileURL:k,path:m,initial:ie,me:H,onStateChange:M,onCollab:G,onPeers:I,onConflictCopy:_,baseSha:j,onSaved:V,onWriting:Y,onRendered:q,handle:W}){const F=i.useRef(null),[z,ce]=i.useState(null),[ae,J]=i.useState(!1),[le,K]=i.useState(!1),O=i.useRef(0),[Q,p]=i.useState(0),l=i.useRef({onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_});l.current={onStateChange:M,onCollab:G,onPeers:I,onSaved:V,onWriting:Y,onRendered:q,onConflictCopy:_};const A=i.useRef(ie),L=i.useRef(H);L.current=H;const U=i.useRef(j);U.current=j;const X=i.useRef(null);return i.useEffect(()=>{X.current?.rebase(j)},[j]),i.useEffect(()=>{let h=null,v=!1,o=null,b;const de=700;J(!1),K(!1);const ue=setTimeout(()=>{!x&&O.current<1&&(O.current++,p(e=>e+1))},11e3),fe=setTimeout(()=>K(!0),24e3),s=X.current=pe({apiBase:E,path:m,seed:A.current,baseSha:U.current,who:L.current?.name,me:L.current,onConflictCopy:e=>l.current.onConflictCopy?.(e),onShrinkRefused:e=>me(m,e),onShrinkWithdrawn:ge,onReady:()=>{if(clearTimeout(b),b=void 0,o){const e=o;o=null;const n=e.getText("body").toString(),r=s.collab.text.toString();if(x&&n===r)for(const[a,t]of d){const u=T(t.from,e),g=T(t.to,e);u&&g&&d.set(a,{from:C(s.collab.text,u.index),to:C(s.collab.text,g.index),span:t.span,orig:t.orig})}else d.clear(),x=!1,n!==r&&p(a=>a+1);e.destroy()}v=!0,w()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,A.current),v=!0,w()},onStalled:()=>{v||o||(o=new he,o.getText("body").insert(0,A.current),v=!0,w())},onState:e=>l.current.onStateChange?.(e),onCollab:e=>l.current.onCollab?.(e),onPeers:e=>l.current.onPeers?.(e),onSaved:e=>l.current.onSaved?.(e),onWriting:()=>l.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():A.current,soloApply:({from:e,to:n,insert:r})=>{o&&o.transact(()=>{const a=o.getText("body");n>e&&a.delete(e,n-e),r&&a.insert(e,r)})}});W&&(W.current=s);const d=new Map,Z=e=>e.start+","+e.end,w=async()=>{if(x||!h||!v)return;const e=o?o.getText("body"):s.collab.text,n=e.toString();if(!n)return;if(h.some(t=>t.end>n.length||t.start>t.end)){h=null,p(t=>t+1);return}const r=await be(n);if(r!==null?r!==$:P>=0&&n.length!==P){h=null,p(t=>t+1);return}d.clear();for(const t of h)d.set(Z(t),{from:C(e,t.start),to:C(e,t.end),span:t.end-t.start,orig:n.slice(t.start,t.end)});x=!0,J(!0),l.current.onRendered?.()};let $="",P=-1,x=!1;const B=async e=>{if(!F.current||e.source!==F.current.contentWindow)return;const n=e.data;if(!n||typeof n!="object")return;if(n.type==="bd-edit:clobbered"){ce("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(n.type==="bd-edit:ready"){h=n.ranges,$=n.hash,P=n.len,await w();return}if(n.type!=="bd-edit:patch")return;const r=d.get(Z(n));if(!r)return;if(o){const c=T(r.from,o),S=T(r.to,o);if(!c||!S||c.index>S.index)return;const R=o.getText("body"),xe=S.index-c.index;if(c.index===0&&S.index===R.length&&r.spanr.span*4+256){d.clear(),x=!1,p(f=>f+1);return}const N=R.toString().slice(c.index,S.index),re=oe(r.orig,N,n.html);if(r.orig=n.html,N===re)return;o.transact(()=>{for(const f of se(N,re))f.deleteCount>0&&R.delete(c.index+f.index,f.deleteCount),f.insertText&&R.insert(c.index+f.index,f.insertText)}),l.current.onStateChange?.("dirty"),clearTimeout(b),b=setTimeout(()=>{s.saveNow()},de);return}const a=s.collab.doc,t=T(r.from,a),u=T(r.to,a);if(!t||!u||t.index>u.index)return;const g=s.collab.text,te=u.index-t.index;if(t.index===0&&u.index===g.length&&r.spanr.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:te,stamped:r.span,docLength:g.length}),d.clear(),x=!1,p(c=>c+1);return}const D=g.toString().slice(t.index,u.index),ne=oe(r.orig,D,n.html);r.orig=n.html,D!==ne&&s.collab.applySplices(se(D,ne).map(c=>({...c,index:c.index+t.index})))},ee=()=>{w()};return s.collab.text.observe(ee),window.addEventListener("message",B),()=>{W?.current===s&&(W.current=null),clearTimeout(ue),clearTimeout(fe),clearTimeout(b),s.collab.text.unobserve(ee),setTimeout(()=>{window.removeEventListener("message",B),clearTimeout(b),s.destroy(),o?.destroy()},300)}},[E,m,Q]),y.jsxs(y.Fragment,{children:[z&&y.jsx("div",{id:"edit-clobbered",className:"banner",children:z}),le&&!ae&&y.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",y.jsx("b",{children:"Edit source"}),"."]}),y.jsx("iframe",{ref:F,className:"htmlview",sandbox:"allow-scripts",src:k+(k.includes("?")?"&":"?")+"edit=1",title:m},Q)]})}export{Ee as VisualEdit};
diff --git a/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js b/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
new file mode 100644
index 00000000..6251887f
--- /dev/null
+++ b/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
@@ -0,0 +1 @@
+import{r as a,j as R,w as ye,a as we}from"./index-C9ixuBUD.js";import{o as be,D as ve,c as E,a as _,m as ae,d as ce}from"./sharedfile-CNg6aQyd.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Te=50;function Se(){let f=Promise.resolve();const l=new Map;let x=0,k=!1;const L=()=>f.then(()=>{});return{enqueue(d){f=f.then(d).catch(()=>{})},flushed(d){l.get(d)?.(),l.delete(d)},async drain(d,j){if(await L(),k||j())return;const w=++x;let W;const b=new Promise(P=>{l.set(w,P),W=setInterval(()=>{!k&&!j()||(l.delete(w),P())},Te)});try{d({type:"bd-edit:flush",id:w}),await b}finally{clearInterval(W)}await L()},close(){k=!0;for(const d of l.values())d();l.clear()}}}async function Re(f){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(f));return[...new Uint8Array(l)].map(x=>x.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ce({apiBase:f,fileURL:l,path:x,initial:k,me:L,onStateChange:d,onCollab:j,onPeers:w,onConflictCopy:W,baseSha:b,onSaved:P,onWriting:z,onRendered:J,handle:q}){const C=a.useRef(null),[K,le]=a.useState(null),[de,Q]=a.useState(!1),[ue,U]=a.useState(!1),X=a.useRef(0),[Z,v]=a.useState(0),u=a.useRef({onStateChange:d,onCollab:j,onPeers:w,onSaved:P,onWriting:z,onRendered:J,onConflictCopy:W});u.current={onStateChange:d,onCollab:j,onPeers:w,onSaved:P,onWriting:z,onRendered:J,onConflictCopy:W};const D=a.useRef(k),G=a.useRef(L);G.current=L;const $=a.useRef(b);$.current=b;const B=a.useRef(null);return a.useEffect(()=>{B.current?.rebase(b)},[b]),a.useEffect(()=>{let T=null,M=!1,r=null,h;const fe=700;Q(!1),U(!1);const xe=setTimeout(()=>{!p&&X.current<1&&(X.current++,v(e=>e+1))},11e3),he=setTimeout(()=>U(!0),24e3),s=B.current=be({apiBase:f,path:x,seed:D.current,baseSha:$.current,who:G.current?.name,me:G.current,onConflictCopy:e=>u.current.onConflictCopy?.(e),onShrinkRefused:e=>we(x,e),onShrinkWithdrawn:ye,onReady:()=>{if(clearTimeout(h),h=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(p&&t===i)for(const[o,n]of m){const y=E(n.from,e),N=E(n.to,e);y&&N&&m.set(o,{from:_(s.collab.text,y.index),to:_(s.collab.text,N.index),span:n.span,orig:n.orig})}else m.clear(),p=!1,t!==i&&v(o=>o+1);e.destroy()}M=!0,S()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,D.current),M=!0,S()},onStalled:()=>{M||r||(r=new ve,r.getText("body").insert(0,D.current),M=!0,S())},onState:e=>u.current.onStateChange?.(e),onCollab:e=>u.current.onCollab?.(e),onPeers:e=>u.current.onPeers?.(e),onSaved:e=>u.current.onSaved?.(e),onWriting:()=>u.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():D.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),I=Se();let H=!1;const me=async()=>{const e=C.current,t=e?.contentWindow;if(!e||!t)return;let i=!1;const o=()=>{i=!0};e.addEventListener("load",o);try{await I.drain(n=>t.postMessage(n,"*"),()=>!H||i||C.current!==e||e.contentWindow!==t)}finally{e.removeEventListener("load",o)}clearTimeout(h),h=void 0},ee={...s,saveNow:async()=>(await me(),s.saveNow())};q&&(q.current=ee);const m=new Map,te=e=>e.start+","+e.end,S=async()=>{if(p||!T||!M)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(T.some(n=>n.end>t.length||n.start>n.end)){T=null,v(n=>n+1);return}const i=await Re(t);if(i!==null?i!==ne:O>=0&&t.length!==O){T=null,v(n=>n+1);return}m.clear();for(const n of T)m.set(te(n),{from:_(e,n.start),to:_(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});p=!0,Q(!0),u.current.onRendered?.()};let ne="",O=-1,p=!1;const pe=async e=>{if(e.type==="bd-edit:flushed"){I.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){le("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){T=e.ranges,ne=e.hash,O=e.len,H=!0,await S();return}if(e.type!=="bd-edit:patch")return;p||await S();const t=m.get(te(e));if(!t)return;if(r){const c=E(t.from,r),A=E(t.to,r);if(!c||!A||c.index>A.index)return;const F=r.getText("body"),ge=A.index-c.index;if(c.index===0&&A.index===F.length&&t.spant.span*4+256){m.clear(),p=!1,v(g=>g+1);return}const Y=F.toString().slice(c.index,A.index),ie=ae(t.orig,Y,e.html);if(t.orig=e.html,Y===ie)return;r.transact(()=>{for(const g of ce(Y,ie))g.deleteCount>0&&F.delete(c.index+g.index,g.deleteCount),g.insertText&&F.insert(c.index+g.index,g.insertText)}),u.current.onStateChange?.("dirty"),clearTimeout(h),h=setTimeout(()=>{s.saveNow()},fe);return}const i=s.collab.doc,o=E(t.from,i),n=E(t.to,i);if(!o||!n||o.index>n.index)return;const y=s.collab.text,N=n.index-o.index;if(o.index===0&&n.index===y.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:y.length}),m.clear(),p=!1,v(c=>c+1);return}const V=y.toString().slice(o.index,n.index),se=ae(t.orig,V,e.html);t.orig=e.html,V!==se&&s.collab.applySplices(ce(V,se).map(c=>({...c,index:c.index+o.index})))},re=e=>{if(!C.current||e.source!==C.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||I.enqueue(()=>pe(t))},oe=()=>{S()};return s.collab.text.observe(oe),window.addEventListener("message",re),()=>{q?.current===ee&&(q.current=null),H=!1,I.close(),clearTimeout(xe),clearTimeout(he),clearTimeout(h),s.collab.text.unobserve(oe),setTimeout(()=>{window.removeEventListener("message",re),clearTimeout(h),s.destroy(),r?.destroy()},300)}},[f,x,Z]),R.jsxs(R.Fragment,{children:[K&&R.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),ue&&!de&&R.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",R.jsx("b",{children:"Edit source"}),"."]}),R.jsx("iframe",{ref:C,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:x},Z)]})}export{Ce as VisualEdit};
diff --git a/internal/webapp/static/assets/index-COodWbrp.js b/internal/webapp/static/assets/index-C9ixuBUD.js
similarity index 99%
rename from internal/webapp/static/assets/index-COodWbrp.js
rename to internal/webapp/static/assets/index-C9ixuBUD.js
index f716c5fb..35a83cf9 100644
--- a/internal/webapp/static/assets/index-COodWbrp.js
+++ b/internal/webapp/static/assets/index-C9ixuBUD.js
@@ -1,4 +1,4 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor--_Kdbq8f.js","assets/sharedfile-BEKa8tPX.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DEcaIEmO.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-vslxZvKp.js","assets/sharedfile-CNg6aQyd.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-ZWfN9slK.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor--_Kdbq8f.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DEcaIEmO.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-vslxZvKp.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-ZWfN9slK.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
 `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
 `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
 `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),Nt=b.useRef(null),dn=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),sn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||sn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,sn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,rn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),an=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!an)return;const ie=an+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[an]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!sn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",cn("history",ze)),Nn("insights","Insights",cn("dashboard",ze)),Nn("gear","Settings",cn("settings",ze)),Nn("laptop","Connect a device",cn("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:sn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!sn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{sn||(Cp(),gS(f,n,M))},onFocus:()=>{sn||(Cp(),gS(f,n,M))},title:sn?"Stop editing":"Edit this file",onClick:async()=>{if(!sn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&dn.current===ie)){dn.current=ie;try{const Ee=$n(M,l?.id,L,r.full,!1),ze=window.location.pathname+window.location.search;let Qe=!0;try{Qe=await(ie?.()??Promise.resolve(!0))}catch{}if(!Qe||window.location.pathname+window.location.search!==ze)return;gt(Ee)}finally{dn.current===ie&&(dn.current=null)}}},children:[!sn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:sn?"Done":"Edit"})]}),sn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),an&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:rn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-BEKa8tPX.js b/internal/webapp/static/assets/sharedfile-CNg6aQyd.js
similarity index 99%
rename from internal/webapp/static/assets/sharedfile-BEKa8tPX.js
rename to internal/webapp/static/assets/sharedfile-CNg6aQyd.js
index dfafe199..1cf25f65 100644
--- a/internal/webapp/static/assets/sharedfile-BEKa8tPX.js
+++ b/internal/webapp/static/assets/sharedfile-CNg6aQyd.js
@@ -1,4 +1,4 @@
-import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-COodWbrp.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-C9ixuBUD.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
 `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[tn]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?cn(e,(n,s)=>Us(n,t[s])):!1;class st{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[tn](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Jr(t,this),t}expect(t){return Jr(t,this),t}}class tr extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ht()};class pc extends st{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends st{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends st{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends st{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):cn(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends st{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&cn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends st{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&cn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends st{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(st);class Tc extends st{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends st{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends st{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>en(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const en=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=en(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(en));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ht()},Jr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
 ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:en(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Pr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Pr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(en(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Pc=e=>{const t=Vc();for(let n=0;n(Bi(e,Pc(t)),e),lu=(e,t=[],n=[])=>Jc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Pi(e)),Wi.forEach(t=>t.print(e))},Ji=(...e)=>{console.warn(...Pi(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Ps{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>jr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return Ze(this.restDecoder)}readBuf(){return lc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(K(t)),this.clientDecoder=new Ln(K(t)),this.leftClockDecoder=new ks(K(t)),this.rightClockDecoder=new ks(K(t)),this.infoDecoder=new Vr(K(t),Ae),this.stringDecoder=new Rl(K(t)),this.parentInfoDecoder=new Vr(K(t),Ae),this.typeRefDecoder=new Ln(K(t)),this.lenDecoder=new Ln(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ze(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ze(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,h=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(u,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)h(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),h=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,h.update])}}else l.pendingStructs=h;const u=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);u&&d?l.pendingDs=Fn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===hn)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new hn),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ht()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ht();l>=0?h=c._length:h=0}return Ca(c,h,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!an(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ht()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Jn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Js(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{so(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new hn;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!an(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Ps{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,I=b-S;I>0&&nn(f,w,S,I)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else u.push(new Ra(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ji("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,hn),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Jt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),h=Ms(c);return Ne(o,h),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Jt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const h=or(l);return Ne(i,h),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let h=i.curr;h!==null;h=i.next())Jt(l,t(h),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,hn),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return an(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Ji("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return rn(e,(s,r)=>{n.push(t(s,r,e))}),n},Pa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Z();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&sn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&sn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new un(s);break;case he:l=new fn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Z(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){rn(this,t)}[Symbol.iterator](){return Pa(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Wt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&sn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
 `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},Jl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})()
 BearDrive
 
-  
+  
   
   
   
diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js
index 3171af32..e8cc6669 100644
--- a/internal/webapp/static/inline-edit.js
+++ b/internal/webapp/static/inline-edit.js
@@ -1,21 +1,21 @@
-(function(){"use strict";var Tr=Object.defineProperty,ll=(n,e)=>{let t={};for(var r in n)Tr(t,r,{get:n[r],enumerable:!0});return Tr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Or(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Dr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?zt(t+1,s):zt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class dt extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Ir(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Ar(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Ar(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Ar(s.content,e-i-1,t-i-1)))}function Ir(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Ir(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function al(n,e,t){if(t.openStart>n.depth)throw new dt("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new dt("Inconsistent open depths");return Rr(n,e,t,0)}function Rr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function ht(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&xn(n,e,i+1),o=r.depth>i&&xn(t,r,i+1),l=[];return ht(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(vr(s,o),Pe(Be(s,Pr(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,Lt(n,e,i+1)),l),ht(e,t,i,l),o&&Pe(Be(o,Lt(t,r,i+1)),l)),ht(r,null,i,l),new b(l)}function Lt(n,e,t){let r=[];if(ht(null,n,t,r),n.depth>t){let i=xn(n,e,t+1);Pe(Be(i,Lt(n,e,t+1)),r)}return ht(e,null,t,r),new b(r)}function cl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class pt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Vt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new pt(t,r,s)}static resolveCached(e,t){let r=Br.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),zr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class $t extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):zr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new $t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new $t(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function zr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new hl(e,t);if(r.next==null)return Fe.empty;let i=Fr(r);r.next&&r.err("Unexpected trailing text");let s=xl(kl(i));return Sl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
-`)}}Fe.empty=new Fe(!0);class hl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Fr(n){let e=[];do e.push(pl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function pl(n){let e=[];do e.push(ml(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function ml(n){let e=bl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=gl(n,e);else break;return e}function Lr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function gl(n,e){let t=Lr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Lr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function yl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function bl(n){if(n.eat("(")){let e=Fr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=yl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function kl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:jr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new nl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Ml(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Cl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ml(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Wt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Hr(e,i.attrs),this.excluded=null;let s=Wr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,jr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Wt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Kr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=qr.compile(this.spec.nodes,this),this.marks=Wt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?_r(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:_r(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof qr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new $t(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function _r(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function wl(n){return n.tag!=null}function Tl(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(wl(i))this.tags.push(i);else if(Tl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Xr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Xr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=Qr(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=Qr(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Ur={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Ol={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Gr={ol:!0,ul:!0},mt=1,Sn=2,gt=4;function Yr(n,e,t){return e!=null?(e?mt:0)|(e==="full"?Sn:0):n&&n.whitespace=="pre"?mt|Sn:t&~gt}class jt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o>?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&mt)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Ur.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Xr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Yr(null,t.preserveWhitespace,0)|(r?gt:0);i?s=new jt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new jt(null,null,E.none,!0,null,o):s=new jt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Sn?"full":this.localPreserveWS||(i.options&mt)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
-`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):Zr(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new jt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=mt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Nl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Gr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function El(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function Qr(n){let e={};for(let t in n)e[t]=n[t];return e}function Zr(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Ht(Jt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Ht(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ei(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ei(e.marks)}}function ei(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Jt(n){return n.document||window.document}const ti=new WeakMap;function Dl(n){let e=ti.get(n);return e===void 0&&ti.set(n,e=Al(n)),e}function Al(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Ht(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ni=65535,ri=Math.pow(2,16);function Il(n,e){return n+e*ri}function ii(n){return n&ni}function Rl(n){return(n-(n&ni))/ri}const si=1,oi=2,qt=4,li=8;class Mn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&li)>0}get deletedBefore(){return(this.delInfo&(si|qt))>0}get deletedAfter(){return(this.delInfo&(oi|qt))>0}get deletedAcross(){return(this.delInfo&qt)>0}}class Y{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&Y.empty)return Y.empty}recover(e){let t=0,r=ii(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Il(l/3,e-a),m=e==a?oi:e==u?si:qt;return(t<0?e!=a:e!=u)&&(m|=li),new Mn(h,m,p)}i+=f-c}return r?e+i:new Mn(e+i,0,null)}touches(e,t){let r=0,i=ii(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new yt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(wn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Tn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function vl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Pl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Wt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function On(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Bl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function Ze(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function $l(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Wl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&ui(n,o,l,s),On(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&fi(n,o,l,s),!1}})}function fi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function ui(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
-`))}})}function Wl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Jl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return di(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Hl(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&di(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function ql(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);ui(n,f.node(),f.before(),l)}o.inlineContent&&On(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);fi(n,f.node(),f.before(),n.steps.length)}return n}function Kl(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function _t(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return hi(i,s,r)?new R(e,t,r):new Ul(i,s,r).fit()}function hi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Ul{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=pi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return gi(e,-1)<=t?!1:(this.unplaced.size>1&&gi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=pi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(bt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(bt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(mi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=kt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=Nn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=kt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=kt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=kt(this.placed,this.frontier.length,t))}}function bt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(bt(n.firstChild.content,e-1,t)))}function kt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(kt(n.lastChild.content,e-1,t)))}function pi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,mi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function Nn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Gl(t,s.content,o)?l:null}function Gl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Yl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function yi(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Ql(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Kl(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function Zl(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=bi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function bi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class et extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return Y.empty}invert(e){return new et(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new et(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new et(t.pos,t.attr,t.value)}}W.jsonID("attr",et);class xt extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return Y.empty}invert(e){return new xt(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new xt(t.attr,t.value)}}W.jsonID("docAttr",xt);let tt=class extends Error{};tt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},tt.prototype=Object.create(Error.prototype),tt.prototype.constructor=tt,tt.prototype.name="TransformError";class ki{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new yt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new tt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=_t(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Xl(this,e,t,r),this}replaceRangeWith(e,t,r){return Ql(this,e,t,r),this}deleteRange(e,t){return Zl(this,e,t),this}lift(e,t){return zl(this,e,t),this}join(e,t=1){return ql(this,e,t),this}wrap(e,t){return Vl(this,e,t),this}setBlockType(e,t=e,r,i=null){return $l(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new et(e,t,r)),this}setDocAttribute(e,t){return this.step(new xt(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Jl(this,e,t,r),this}addMark(e,t,r){return vl(this,e,t,r),this}removeMark(e,t,r){return Pl(this,e,t,r),this}clearIncompatible(e,t,r){return On(this,e,t,r),this}}const En=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ea(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?nt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):nt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return nt(e,e,0,0,1)||new U(e)}static atEnd(e){return nt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=En[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in En)throw new RangeError("Duplicate use of selection JSON ID "+e);return En[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ea{constructor(e,t){this.$from=e,this.$to=t}}let xi=!1;function Si(n){!xi&&!n.parent.inlineContent&&(xi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Si(e),Si(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Ut(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=nt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Mi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ci=1,Gt=2,wi=4;class na extends ki{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Gt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Gt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Gt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=wi,this}get scrolledIntoView(){return(this.updated&wi)>0}}function Ti(n,e){return!e||!n?n:n.bind(e)}class St{constructor(e,t,r){this.name=e,this.init=Ti(t.init,r),this.apply=Ti(t.apply,r)}}const ra=[new St("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new St("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new St("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new St("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class An{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ra.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new St(r.key,r.spec.state,r))})}}class rt{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new An(e.schema,e.plugins),s=new rt(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Oi(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Oi(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Oi(e.props,this,this.props),this.key=e.key?e.key.key:Ni("plugin")}getState(e){return e[this.key]}}const In=Object.create(null);function Ni(n){return n in In?n+"$"+ ++In[n]:(In[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ni(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ei=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Di(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ai=(n,e,t)=>{let r=Di(n,t);if(!r)return!1;let i=Rn(r);if(!i){let o=r.blockRange(),l=o&&Ze(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if($i(n,i,e,-1))return!0;if(r.parent.content.size==0&&(it(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=_t(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},ia=(n,e,t)=>{let r=Di(n,t);if(!r)return!1;let i=Rn(r);return i?Ii(n,i,e):!1},sa=(n,e,t)=>{let r=vi(n,t);if(!r)return!1;let i=vn(r);return i?Ii(n,i,e):!1};function Ii(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=_t(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function it(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Ri=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Rn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Rn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function vi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=vi(n,t);if(!r)return!1;let i=vn(r);if(!i)return!1;let s=i.nodeAfter;if($i(n,i,e,1))return!0;if(r.parent.content.size==0&&(it(s,"start")||x.isSelectable(s))){let o=_t(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=Kt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},la=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=Kt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},aa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&Ze(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},zi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
-`).scrollIntoView()),!0)};function Pn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Pn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Li=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Pn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&Ze(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ca(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Pn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const fa=ca(),ua=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},da=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ha(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function $i(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ha(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&Ze(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&it(s,"start",!0)&&it(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Wi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const ji=Wi(-1),Ji=Wi(1);function pa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&ai(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Hi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function qi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ma(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Vt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Sa(e,t,n,s):Ma(e,t,s):!0:!1}}function Sa(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ca(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},st=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Fn=null;const me=function(n,e,t){let r=Fn||(Fn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},wa=function(){Fn=null},We=function(n,e,t,r){return t&&(Ui(n,e,t,r,-1)||Ui(n,e,t,r,1))},Ta=/^(img|br|input|textarea|hr)$/i;function Ui(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:X(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Mt(n)||Ta.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?X(n):0}else return!1}}function X(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Oa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=X(n)}else if(n.parentNode&&!Mt(n))e=L(n),n=n.parentNode;else return null}}function Na(n,e){for(;;){if(n.nodeType==3&&e2),Z=ot||(ce?/Mac/.test(ce.platform):!1),Qi=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),Ct=!!Gi&&"webkitFontSmoothing"in Gi.documentElement.style,Ia=Ct?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Ra(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function va(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function Zi(n,e,t){if(!jn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=st(o);continue}let l=o,a=l==s.body,c=a?Ra(s):va(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:st(o)}}function Pa(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:es(n.dom)}}function es(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=st(r));return e}function Ba({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ts(t,r==0?0:r-e)}function ts(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Fa(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:ns(t,i)}function Fa(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Wn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function La(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function $a(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function rs(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Ct&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=$a(n,r,i,e))}l==null&&(l=Va(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function jn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,wt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Jn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,X(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return wt(we(c,1),!1)}if(s==null&&i=0)}function wt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Jn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ss(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ja(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return ss(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=is(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ha=/[\u0590-\u08ac]/;function qa(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ha.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:ss(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let ls=null,as=null,cs=!1;function Ka(n,e,t){return ls==e&&as==t?cs:(ls=e,as=t,cs=t=="up"||t=="down"?Ja(n,e,t):qa(n,e,t))}const ee=0,fs=1,Je=2,se=3;class Tt{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=ee,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof hs){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof us&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:fs,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:fs;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==ee&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class _a extends Tt{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Tt{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=ee){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=qn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=gs(f,r,t),c?a=new Ua(e,t,r,i,f,u||null,d,c):t.isText?new Xt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==ee&&e.eq(this.node)&&Qt(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Ya(this,o&&o.node,e);Za(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),ps(this.contentDOM,this.children,e),ot&&ec(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=tc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new _a(this,s,t,i);e.input.compositionNodes.push(o),this.children=qn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=ee}updateOuterDeco(e){if(Qt(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ms(this.dom,this.nodeDOM,Hn(this.outerDeco,this.node,t),Hn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ds(n,e,t,r,i){gs(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Xt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=ee&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=ee||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=ee,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Xt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class hs extends Tt{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==ee&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ua extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function ps(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Qa(n,e){return n.type.side-e.type.side}function Za(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ec(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function tc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function qn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Kn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Yt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Ea(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!bs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function rc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function Ms(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Cs(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Cs(n)}function Cs(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Un(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function ws(n){return n.editable&&!n.hasFocus()?!1:Ts(n)}function Ts(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function ic(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Gn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Os(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Gn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(Z&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):Ct?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Gn(n.state,e);return i?Ne(n,i):!1}}}function Zt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Nt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function at(n,e){return e<0?sc(n):oc(n)}function sc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Q&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Nt(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Ns(t))break;{let l=t.previousSibling;for(;l&&Nt(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=Zt(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Yn(n,t,r):i&&Yn(n,i,s)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=Zt(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function Es(n,e){let t=n.state.doc.resolve(e);if(!(V||Qi)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ds(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||Z&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Gn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function As(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Is(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function cc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Is(n,r,"true"),setTimeout(()=>Is(n,r,"false"),20)}return!1}function fc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function uc(n,e){let t=e.keyCode,r=fc(e);if(t==8||Z&&t==72&&r=="c")return As(n,-1)||at(n,-1);if(t==46&&!e.shiftKey||Z&&t==68&&r=="c")return As(n,1)||at(n,1);if(t==13||t==27)return!0;if(t==37||Z&&t==66&&r=="c"){let i=t==37?Es(n,n.state.selection.from)=="ltr"?-1:1:-1;return Os(n,i,r)||at(n,i)}else if(t==39||Z&&t==70&&r=="c"){let i=t==39?Es(n,n.state.selection.from)=="ltr"?1:-1:1;return Os(n,i,r)||at(n,i)}else{if(t==38||Z&&t==80&&r=="c")return Ds(n,-1,r)||at(n,-1);if(t==40||Z&&t==78&&r=="c")return cc(n)||Ds(n,1,r)||at(n,1);if(r==(Z?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Xn(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=Ls(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Fs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
+(function(){"use strict";var Or=Object.defineProperty,ll=(n,e)=>{let t={};for(var r in n)Or(t,r,{get:n[r],enumerable:!0});return Or(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Nr(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ar(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?zt(t+1,s):zt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class dt extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Rr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Ir(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Ir(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Ir(s.content,e-i-1,t-i-1)))}function Rr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Rr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function al(n,e,t){if(t.openStart>n.depth)throw new dt("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new dt("Inconsistent open depths");return vr(n,e,t,0)}function vr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function ht(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Sn(n,e,i+1),o=r.depth>i&&Sn(t,r,i+1),l=[];return ht(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Pr(s,o),Pe(Be(s,Br(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,Lt(n,e,i+1)),l),ht(e,t,i,l),o&&Pe(Be(o,Lt(t,r,i+1)),l)),ht(r,null,i,l),new b(l)}function Lt(n,e,t){let r=[];if(ht(null,n,t,r),n.depth>t){let i=Sn(n,e,t+1);Pe(Be(i,Lt(n,e,t+1)),r)}return ht(e,null,t,r),new b(r)}function cl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class pt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Vt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new pt(t,r,s)}static resolveCached(e,t){let r=zr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Fr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class $t extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Fr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new $t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new $t(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Fr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new hl(e,t);if(r.next==null)return Fe.empty;let i=Lr(r);r.next&&r.err("Unexpected trailing text");let s=xl(kl(i));return Sl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
+`)}}Fe.empty=new Fe(!0);class hl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Lr(n){let e=[];do e.push(pl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function pl(n){let e=[];do e.push(ml(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function ml(n){let e=bl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=gl(n,e);else break;return e}function Vr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function gl(n,e){let t=Vr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Vr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function yl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function bl(n){if(n.eat("(")){let e=Lr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=yl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function kl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Jr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new nl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Ml(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Cl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ml(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Wt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=qr(e,i.attrs),this.excluded=null;let s=jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Jr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Wt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class _r{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Kr.compile(this.spec.nodes,this),this.marks=Wt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Ur(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Ur(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Kr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new $t(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Ur(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function wl(n){return n.tag!=null}function Tl(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(wl(i))this.tags.push(i);else if(Tl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Qr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Qr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=Zr(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=Zr(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Gr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Ol={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Yr={ol:!0,ul:!0},mt=1,Mn=2,gt=4;function Xr(n,e,t){return e!=null?(e?mt:0)|(e==="full"?Mn:0):n&&n.whitespace=="pre"?mt|Mn:t&~gt}class jt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o>?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&mt)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Gr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Qr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Xr(null,t.preserveWhitespace,0)|(r?gt:0);i?s=new jt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new jt(null,null,E.none,!0,null,o):s=new jt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Mn?"full":this.localPreserveWS||(i.options&mt)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
+`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ei(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new jt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=mt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Nl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Yr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function El(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function Zr(n){let e={};for(let t in n)e[t]=n[t];return e}function ei(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Ht(Jt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Ht(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ti(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ti(e.marks)}}function ti(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Jt(n){return n.document||window.document}const ni=new WeakMap;function Dl(n){let e=ni.get(n);return e===void 0&&ni.set(n,e=Al(n)),e}function Al(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Ht(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ri=65535,ii=Math.pow(2,16);function Il(n,e){return n+e*ii}function si(n){return n&ri}function Rl(n){return(n-(n&ri))/ii}const oi=1,li=2,qt=4,ai=8;class Cn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ai)>0}get deletedBefore(){return(this.delInfo&(oi|qt))>0}get deletedAfter(){return(this.delInfo&(li|qt))>0}get deletedAcross(){return(this.delInfo&qt)>0}}class Y{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&Y.empty)return Y.empty}recover(e){let t=0,r=si(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Il(l/3,e-a),m=e==a?li:e==u?oi:qt;return(t<0?e!=a:e!=u)&&(m|=ai),new Cn(h,m,p)}i+=f-c}return r?e+i:new Cn(e+i,0,null)}touches(e,t){let r=0,i=si(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new yt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Tn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function On(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function vl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Pl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Wt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function Nn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Bl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function Ze(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function $l(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Wl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&di(n,o,l,s),Nn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&ui(n,o,l,s),!1}})}function ui(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
+`))}})}function Wl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Jl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return hi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Hl(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&hi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function ql(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);di(n,f.node(),f.before(),l)}o.inlineContent&&Nn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);ui(n,f.node(),f.before(),n.steps.length)}return n}function Kl(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function _t(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return pi(i,s,r)?new R(e,t,r):new Ul(i,s,r).fit()}function pi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Ul{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=mi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return yi(e,-1)<=t?!1:(this.unplaced.size>1&&yi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=mi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(bt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(bt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(gi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=kt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=En(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=kt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=kt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=kt(this.placed,this.frontier.length,t))}}function bt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(bt(n.firstChild.content,e-1,t)))}function kt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(kt(n.lastChild.content,e-1,t)))}function mi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,gi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function En(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Gl(t,s.content,o)?l:null}function Gl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Yl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function bi(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Ql(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Kl(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function Zl(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=ki(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function ki(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class et extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return Y.empty}invert(e){return new et(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new et(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new et(t.pos,t.attr,t.value)}}W.jsonID("attr",et);class xt extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return Y.empty}invert(e){return new xt(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new xt(t.attr,t.value)}}W.jsonID("docAttr",xt);let tt=class extends Error{};tt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},tt.prototype=Object.create(Error.prototype),tt.prototype.constructor=tt,tt.prototype.name="TransformError";class xi{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new yt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new tt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=_t(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Xl(this,e,t,r),this}replaceRangeWith(e,t,r){return Ql(this,e,t,r),this}deleteRange(e,t){return Zl(this,e,t),this}lift(e,t){return zl(this,e,t),this}join(e,t=1){return ql(this,e,t),this}wrap(e,t){return Vl(this,e,t),this}setBlockType(e,t=e,r,i=null){return $l(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new et(e,t,r)),this}setDocAttribute(e,t){return this.step(new xt(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Jl(this,e,t,r),this}addMark(e,t,r){return vl(this,e,t,r),this}removeMark(e,t,r){return Pl(this,e,t,r),this}clearIncompatible(e,t,r){return Nn(this,e,t,r),this}}const Dn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ea(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?nt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):nt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return nt(e,e,0,0,1)||new U(e)}static atEnd(e){return nt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Dn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Dn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Dn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ea{constructor(e,t){this.$from=e,this.$to=t}}let Si=!1;function Mi(n){!Si&&!n.parent.inlineContent&&(Si=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Mi(e),Mi(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Ut(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=nt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ci(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const wi=1,Gt=2,Ti=4;class na extends xi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Gt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Gt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Gt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ti,this}get scrolledIntoView(){return(this.updated&Ti)>0}}function Oi(n,e){return!e||!n?n:n.bind(e)}class St{constructor(e,t,r){this.name=e,this.init=Oi(t.init,r),this.apply=Oi(t.apply,r)}}const ra=[new St("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new St("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new St("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new St("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class In{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ra.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new St(r.key,r.spec.state,r))})}}class rt{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new In(e.schema,e.plugins),s=new rt(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ni(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ni(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ni(e.props,this,this.props),this.key=e.key?e.key.key:Ei("plugin")}getState(e){return e[this.key]}}const Rn=Object.create(null);function Ei(n){return n in Rn?n+"$"+ ++Rn[n]:(Rn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ei(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Di=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ai(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ii=(n,e,t)=>{let r=Ai(n,t);if(!r)return!1;let i=vn(r);if(!i){let o=r.blockRange(),l=o&&Ze(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Wi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(it(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=_t(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},ia=(n,e,t)=>{let r=Ai(n,t);if(!r)return!1;let i=vn(r);return i?Ri(n,i,e):!1},sa=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=Pn(r);return i?Ri(n,i,e):!1};function Ri(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=_t(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function it(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const vi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=vn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function vn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Pi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Pi(n,t);if(!r)return!1;let i=Pn(r);if(!i)return!1;let s=i.nodeAfter;if(Wi(n,i,e,1))return!0;if(r.parent.content.size==0&&(it(s,"start")||x.isSelectable(s))){let o=_t(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=Kt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},la=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=Kt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},aa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&Ze(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Fi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
+`).scrollIntoView()),!0)};function Bn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Bn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Vi=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Bn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&Ze(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ca(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Bn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const fa=ca(),ua=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},da=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ha(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Wi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ha(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&Ze(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&it(s,"start",!0)&&it(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ji=ji(-1),Hi=ji(1);function pa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&ci(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function qi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Ki(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ma(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Vt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Sa(e,t,n,s):Ma(e,t,s):!0:!1}}function Sa(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ca(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},st=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Ln=null;const me=function(n,e,t){let r=Ln||(Ln=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},wa=function(){Ln=null},We=function(n,e,t,r){return t&&(Gi(n,e,t,r,-1)||Gi(n,e,t,r,1))},Ta=/^(img|br|input|textarea|hr)$/i;function Gi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:X(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Mt(n)||Ta.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?X(n):0}else return!1}}function X(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Oa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=X(n)}else if(n.parentNode&&!Mt(n))e=L(n),n=n.parentNode;else return null}}function Na(n,e){for(;;){if(n.nodeType==3&&e2),Z=ot||(ce?/Mac/.test(ce.platform):!1),Zi=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),Ct=!!Yi&&"webkitFontSmoothing"in Yi.documentElement.style,Ia=Ct?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Ra(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function va(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function es(n,e,t){if(!Jn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=st(o);continue}let l=o,a=l==s.body,c=a?Ra(s):va(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:st(o)}}function Pa(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ts(n.dom)}}function ts(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=st(r));return e}function Ba({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ns(t,r==0?0:r-e)}function ns(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Fa(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:rs(t,i)}function Fa(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function jn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function La(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function $a(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function is(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Ct&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=$a(n,r,i,e))}l==null&&(l=Va(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Jn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,wt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Hn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,X(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return wt(we(c,1),!1)}if(s==null&&i=0)}function wt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Hn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ls(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ja(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return ls(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ss(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ha=/[\u0590-\u08ac]/;function qa(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ha.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:ls(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let as=null,cs=null,fs=!1;function Ka(n,e,t){return as==e&&cs==t?fs:(as=e,cs=t,fs=t=="up"||t=="down"?Ja(n,e,t):qa(n,e,t))}const ee=0,us=1,Je=2,se=3;class Tt{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=ee,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ps){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ds&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:us,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:us;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==ee&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class _a extends Tt{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Tt{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=ee){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Kn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=ys(f,r,t),c?a=new Ua(e,t,r,i,f,u||null,d,c):t.isText?new Xt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==ee&&e.eq(this.node)&&Qt(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Ya(this,o&&o.node,e);Za(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),ms(this.contentDOM,this.children,e),ot&&ec(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=tc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new _a(this,s,t,i);e.input.compositionNodes.push(o),this.children=Kn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=ee}updateOuterDeco(e){if(Qt(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=gs(this.dom,this.nodeDOM,qn(this.outerDeco,this.node,t),qn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function hs(n,e,t,r,i){ys(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Xt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=ee&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=ee||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=ee,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Xt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ps extends Tt{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==ee&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ua extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function ms(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Qa(n,e){return n.type.side-e.type.side}function Za(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ec(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function tc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Kn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function _n(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Yt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Ea(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!ks(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function rc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function Cs(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(ws(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else ws(n)}function ws(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Gn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Ts(n){return n.editable&&!n.hasFocus()?!1:Os(n)}function Os(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function ic(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Yn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Ns(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Yn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(Z&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):Ct?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Yn(n.state,e);return i?Ne(n,i):!1}}}function Zt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Nt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function at(n,e){return e<0?sc(n):oc(n)}function sc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Q&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Nt(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Es(t))break;{let l=t.previousSibling;for(;l&&Nt(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=Zt(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Xn(n,t,r):i&&Xn(n,i,s)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=Zt(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function Ds(n,e){let t=n.state.doc.resolve(e);if(!(V||Zi)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function As(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||Z&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Yn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Is(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Rs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function cc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Rs(n,r,"true"),setTimeout(()=>Rs(n,r,"false"),20)}return!1}function fc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function uc(n,e){let t=e.keyCode,r=fc(e);if(t==8||Z&&t==72&&r=="c")return Is(n,-1)||at(n,-1);if(t==46&&!e.shiftKey||Z&&t==68&&r=="c")return Is(n,1)||at(n,1);if(t==13||t==27)return!0;if(t==37||Z&&t==66&&r=="c"){let i=t==37?Ds(n,n.state.selection.from)=="ltr"?-1:1:-1;return Ns(n,i,r)||at(n,i)}else if(t==39||Z&&t==70&&r=="c"){let i=t==39?Ds(n,n.state.selection.from)=="ltr"?1:-1:1;return Ns(n,i,r)||at(n,i)}else{if(t==38||Z&&t==80&&r=="c")return As(n,-1,r)||at(n,-1);if(t==40||Z&&t==78&&r=="c")return cc(n)||As(n,1,r)||at(n,1);if(r==(Z?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Qn(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=Vs(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ls[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
 
-`);return{dom:a,text:d,slice:e}}function Rs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,`
-`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=mc(t),Ct&&gc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!dc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=yc(zs(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(hc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const dc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function hc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Ps(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Bs(o[o.length-1],s.length));let f=vs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function vs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Ps(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function zs(n,e,t){return et})}return Et.createHTML(n)}function mc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Ls(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Fs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=pc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},bc={touchstart:!0,touchmove:!0};class kc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function xc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Mc(n,r)&&!er(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},bc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),Zn(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Sc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function Zn(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>er(n,r))})}function er(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Mc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Cc(n,e){!er(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!js(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),ot&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||uc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(js(n)||!t.charCode||t.ctrlKey&&!t.altKey||Z&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function Dt(n){return{left:n.clientX,top:n.clientY}}function wc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function tr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function At(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Tc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(At(n,new x(t)),!0):!1}function Oc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(At(n,x.create(n.state.doc,i)),!0):!1}function Nc(n,e,t,r,i){return tr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Oc(n,t):Tc(n,t))}function Ec(n,e,t,r){return tr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Dc(n,e,t,r){return tr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ac(n,t,r)}function Ac(n,e,t){if(t.button!=0)return!1;let r=Vs(n,e,!0),i=n.state.doc;return r?(At(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new Rc(n,r)),!0):!1}function Vs(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function nr(n){return en(n)}const $s=Z?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=nr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&wc(t,n.input.lastClick)&&!t[$s]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(Dt(t));o&&(s=="singleClick"?n.input.mouseDown=new Ic(n,o,t,!!r):(s=="doubleClick"?Ec:Dc)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class Ws{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Ic extends Ws{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[$s],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Q&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(Dt(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Nc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(At(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Rc extends Ws{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(Dt(e)),r=t&&Vs(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),nr(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>nr(n);function js(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const vc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&Qi&&Pc(n)))n.markCursor=n.state.storedMarks||t.marks(),en(n,!0),n.markCursor=null;else if(en(n,!e.selection.empty),Q&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Js(n,vc)};function Pc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Js(n,20))};function Js(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>en(n),e))}function Hs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Bc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Oa(e.focusNode,e.focusOffset),r=Na(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function en(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Hs(n),e||n.docView&&n.docView.dirty){let t=Kn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function zc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const It=G&&Ce<15||ot&&Ia<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=It?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Xn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):zc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Fc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Lc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Rt(n,r.value,null,i,e):Rt(n,r.textContent,r.innerHTML,i,e)},50)}function Rt(n,e,t,r,i){let s=Rs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Fc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function qs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=It?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Rt(n,qs(r),r.getData("text/html"),i,t)?t.preventDefault():Lc(n,t)};class Ks{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Vc=Z?"altKey":"ctrlKey";function _s(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Vc]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(Dt(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Xn(n,l);(!t.dataTransfer.files.length||!V||Xi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(It?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",It||t.dataTransfer.setData("text/plain",c),n.dragging=new Ks(f,_s(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{$c(n,e,n.dragging)}finally{n.dragging=null}};function $c(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(Dt(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Rs(n,qs(e.dataTransfer),It?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&_s(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?_l(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Un(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function vt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class tn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof tn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&vt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Gs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=jc(l,n,e,t,i,s,o),f=nn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Gs(n,l,a+t);if(c){s=!0;let f=nn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Us(s?Ys(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function sr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Jc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Hc=G&&Ce<=11;class qc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Kc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new qc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Hc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Jc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(ws(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=st(s))t.add(s);for(let s=e.anchorNode;s;s=st(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&ws(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Q&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Gc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),_c(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Yc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Qc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Qc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Zc=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function ef(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Kn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Xe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Xc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!Zc.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=to(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((ot&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&nf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=to(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=tf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function to(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Un(n,e.resolve(t.anchor),e.resolve(t.head))}function tf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||or(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function rf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class no{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new kc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(lo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=so(this),io(this),this.nodeViews=oo(this),this.docView=ds(this.state.doc,ro(this),sr(this),this.dom,this),this.domObserver=new Kc(this,(r,i,s,o)=>ef(this,r,i,s,o)),this.domObserver.start(),xc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Zn(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(lo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Hs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=oo(this);of(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&Zn(this),this.editable=so(this),io(this);let a=sr(this),c=ro(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Pa(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&sf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Bc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ds(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ic(this)&&p.delaySelUpdate())?be(this,h):(Ms(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ba(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&Zi(this,t.getBoundingClientRect(),e)}else Zi(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Wa(this,e)}coordsAtPos(e,t=1){return is(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ka(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Xn(this,e)}destroy(){this.docView&&(Sc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],sr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,wa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Cc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Da(this.dom.ownerDocument)==this.dom&&Uc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}no.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function ro(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function io(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function so(n){return!n.someProp("editable",e=>e(n.state)===!1)}function sf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function oo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function of(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function lo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},rn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},lf=typeof navigator<"u"&&/Mac/.test(navigator.platform),af=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),rn[$]=String.fromCharCode($);for(var lr in Ae)rn.hasOwnProperty(lr)||(rn[lr]=Ae[lr]);function cf(n){var e=lf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||af&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?rn:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const ff=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),uf=typeof navigator<"u"&&/Win/.test(navigator.platform);function df(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=rl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:co({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const gf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),yf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),bf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=Ze(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},kf=n=>e=>n(e),xf=()=>({state:n,dispatch:e})=>Li(n,e),Sf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Mf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Cf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},wf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Tf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,fo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:fo(n,t,"left"),to:fo(e,t,"right")}),Nf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Of(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Ef=()=>({commands:n})=>n.keyboardShortcut("Enter"),Df=()=>({state:n,dispatch:e})=>Fi(n,e);function Af(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function sn(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Af(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function uo(n,e,t={}){return n.find(r=>r.type===e&&sn(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function ho(n,e,t={}){return!!uo(n,e,t)}function cr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!uo([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&ho([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=cr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},Rf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(on()||mo())&&r.dom.focus(),Pf()&&!on()&&!mo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!po(t.state.selection))return o(),!0;const l=vf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},zf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Ff=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),go=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&go(r)}return n};function ln(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return go(t)}function yo(n){return typeof n?.nodesBetween=="function"}function ft(n,e,t){if(yo(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ft("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Kr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(ln(n),t.parseOptions):de.fromSchema(a).parse(ln(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(ln(n),t.parseOptions).content:s.parse(ln(n),t.parseOptions)}return ft("",e,t)}function bo(n){return!("type"in n)}function ko(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Lf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=bo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):yo(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&ko(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function xo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=xo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ft(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&ko(e,e.steps.length-1,-1)),!0):!1},$f=()=>({state:n,dispatch:e})=>oa(n,e),Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>Ai(n,e),Jf=()=>({state:n,dispatch:e})=>Pi(n,e),Hf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e})=>ia(n,e),_f=()=>({state:n,dispatch:e})=>sa(n,e);function So(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Uf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Uf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function fr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>sn(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Yf=(n,e={})=>({state:t,dispatch:r})=>fr(t,H(n,t.schema),e)?aa(t,r):!1,Xf=()=>({state:n,dispatch:e})=>Vi(n,e),Qf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return xa(r)(e,t)},Zf=()=>({state:n,dispatch:e})=>zi(n,e);function Mo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Co(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const eu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Mo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,Co(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(Co(d.attrs,e))))})})}),a},tu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),nu=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},ru=()=>({state:n,dispatch:e})=>Ri(n,e),iu=()=>({state:n,dispatch:e})=>Bi(n,e),su=()=>({state:n,dispatch:e})=>ua(n,e),ou=()=>({state:n,dispatch:e})=>Ji(n,e),lu=()=>({state:n,dispatch:e})=>ji(n,e);function au(n,e,t={},r={}){return ft(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const cu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=au(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=bo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function fu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function uu(n,e){const t=new ki(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function du(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function ur(n){return e=>du(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function wo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...wo(t())]:e}).flat(10)}function hu(n){return typeof n=="function"}function D(n,e=void 0,...t){return hu(n)?e?n.bind(e)(...t):n(...t):n}function pu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function an(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function mu(n){const e=[],{nodeExtensions:t,markExtensions:r}=an(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function gu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function To(n){const e=[],t=gu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...To(r[i]),...To(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Oo(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>cn(t,r),{})}function yu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function No(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):yu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Eo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&pu(t)?!1:t!=null))}function Do(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function bu(n,e){var t;const r=mu(n),{nodeExtensions:i,markExtensions:s}=an(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Eo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Do))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>No(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Oo(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Eo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Do))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>No(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Oo(m,f)})),[c.name,d]}));return new Kr({topNode:o,nodes:l,marks:a})}function ku(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function xu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Mu(n,e){return bu(Su(n),e)}function Cu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
+`);return{dom:a,text:d,slice:e}}function vs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,`
+`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=mc(t),Ct&&gc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!dc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=yc(Fs(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(hc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const dc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function hc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Bs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=zs(o[o.length-1],s.length));let f=Ps(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Ps(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Bs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Fs(n,e,t){return et})}return Et.createHTML(n)}function mc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Vs(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ls[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=pc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},bc={touchstart:!0,touchmove:!0};class kc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function xc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Mc(n,r)&&!tr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},bc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),er(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Sc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function er(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>tr(n,r))})}function tr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Mc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Cc(n,e){!tr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Js(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),ot&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||uc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Js(n)||!t.charCode||t.ctrlKey&&!t.altKey||Z&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function Dt(n){return{left:n.clientX,top:n.clientY}}function wc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function nr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function At(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Tc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(At(n,new x(t)),!0):!1}function Oc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(At(n,x.create(n.state.doc,i)),!0):!1}function Nc(n,e,t,r,i){return nr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Oc(n,t):Tc(n,t))}function Ec(n,e,t,r){return nr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Dc(n,e,t,r){return nr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ac(n,t,r)}function Ac(n,e,t){if(t.button!=0)return!1;let r=$s(n,e,!0),i=n.state.doc;return r?(At(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new Rc(n,r)),!0):!1}function $s(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function rr(n){return en(n)}const Ws=Z?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=rr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&wc(t,n.input.lastClick)&&!t[Ws]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(Dt(t));o&&(s=="singleClick"?n.input.mouseDown=new Ic(n,o,t,!!r):(s=="doubleClick"?Ec:Dc)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Ic extends js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Ws],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Q&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(Dt(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Nc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(At(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Rc extends js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(Dt(e)),r=t&&$s(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),rr(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>rr(n);function Js(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const vc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&Zi&&Pc(n)))n.markCursor=n.state.storedMarks||t.marks(),en(n,!0),n.markCursor=null;else if(en(n,!e.selection.empty),Q&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Hs(n,vc)};function Pc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Hs(n,20))};function Hs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>en(n),e))}function qs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Bc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Oa(e.focusNode,e.focusOffset),r=Na(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function en(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),qs(n),e||n.docView&&n.docView.dirty){let t=_n(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function zc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const It=G&&Ce<15||ot&&Ia<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=It?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Qn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):zc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Fc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Lc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Rt(n,r.value,null,i,e):Rt(n,r.textContent,r.innerHTML,i,e)},50)}function Rt(n,e,t,r,i){let s=vs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Fc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Ks(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=It?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Rt(n,Ks(r),r.getData("text/html"),i,t)?t.preventDefault():Lc(n,t)};class _s{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Vc=Z?"altKey":"ctrlKey";function Us(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Vc]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(Dt(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Qn(n,l);(!t.dataTransfer.files.length||!V||Qi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(It?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",It||t.dataTransfer.setData("text/plain",c),n.dragging=new _s(f,Us(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{$c(n,e,n.dragging)}finally{n.dragging=null}};function $c(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(Dt(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=vs(n,Ks(e.dataTransfer),It?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Us(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?_l(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Gn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function vt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class tn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof tn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&vt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Ys(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=jc(l,n,e,t,i,s,o),f=nn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Ys(n,l,a+t);if(c){s=!0;let f=nn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Gs(s?Xs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function or(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Jc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Hc=G&&Ce<=11;class qc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Kc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new qc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Hc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Jc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Ts(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=st(s))t.add(s);for(let s=e.anchorNode;s;s=st(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Ts(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Q&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Gc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),_c(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Yc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Qc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Qc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Zc=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function ef(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=_n(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Xe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Xc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!Zc.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=no(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((ot&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&nf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=no(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=tf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function no(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Gn(n,e.resolve(t.anchor),e.resolve(t.head))}function tf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||lr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function rf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class ro{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new kc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(ao),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=oo(this),so(this),this.nodeViews=lo(this),this.docView=hs(this.state.doc,io(this),or(this),this.dom,this),this.domObserver=new Kc(this,(r,i,s,o)=>ef(this,r,i,s,o)),this.domObserver.start(),xc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&er(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(ao),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(qs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=lo(this);of(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&er(this),this.editable=oo(this),so(this);let a=or(this),c=io(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Pa(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&sf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Bc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=hs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ic(this)&&p.delaySelUpdate())?be(this,h):(Cs(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ba(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&es(this,t.getBoundingClientRect(),e)}else es(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Wa(this,e)}coordsAtPos(e,t=1){return ss(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ka(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Qn(this,e)}destroy(){this.docView&&(Sc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],or(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,wa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Cc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Da(this.dom.ownerDocument)==this.dom&&Uc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}ro.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function io(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function so(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function oo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function sf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function lo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function of(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function ao(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},rn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},lf=typeof navigator<"u"&&/Mac/.test(navigator.platform),af=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),rn[$]=String.fromCharCode($);for(var ar in Ae)rn.hasOwnProperty(ar)||(rn[ar]=Ae[ar]);function cf(n){var e=lf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||af&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?rn:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const ff=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),uf=typeof navigator<"u"&&/Win/.test(navigator.platform);function df(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=rl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:fo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const gf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),yf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),bf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=Ze(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},kf=n=>e=>n(e),xf=()=>({state:n,dispatch:e})=>Vi(n,e),Sf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Mf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Cf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},wf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Tf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,uo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:uo(n,t,"left"),to:uo(e,t,"right")}),Nf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Of(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Ef=()=>({commands:n})=>n.keyboardShortcut("Enter"),Df=()=>({state:n,dispatch:e})=>Li(n,e);function Af(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function sn(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Af(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function ho(n,e,t={}){return n.find(r=>r.type===e&&sn(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function po(n,e,t={}){return!!ho(n,e,t)}function fr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!ho([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&po([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=fr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},Rf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(on()||go())&&r.dom.focus(),Pf()&&!on()&&!go()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!mo(t.state.selection))return o(),!0;const l=vf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},zf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Ff=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),yo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&yo(r)}return n};function ln(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return yo(t)}function bo(n){return typeof n?.nodesBetween=="function"}function ft(n,e,t){if(bo(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ft("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new _r({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(ln(n),t.parseOptions):de.fromSchema(a).parse(ln(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(ln(n),t.parseOptions).content:s.parse(ln(n),t.parseOptions)}return ft("",e,t)}function ko(n){return!("type"in n)}function xo(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Lf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=ko(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):bo(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&xo(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function So(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=So(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ft(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&xo(e,e.steps.length-1,-1)),!0):!1},$f=()=>({state:n,dispatch:e})=>oa(n,e),Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>Ii(n,e),Jf=()=>({state:n,dispatch:e})=>Bi(n,e),Hf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e})=>ia(n,e),_f=()=>({state:n,dispatch:e})=>sa(n,e);function Mo(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Uf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Uf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function ur(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>sn(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Yf=(n,e={})=>({state:t,dispatch:r})=>ur(t,H(n,t.schema),e)?aa(t,r):!1,Xf=()=>({state:n,dispatch:e})=>$i(n,e),Qf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return xa(r)(e,t)},Zf=()=>({state:n,dispatch:e})=>Fi(n,e);function Co(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function wo(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const eu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Co(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,wo(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(wo(d.attrs,e))))})})}),a},tu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),nu=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},ru=()=>({state:n,dispatch:e})=>vi(n,e),iu=()=>({state:n,dispatch:e})=>zi(n,e),su=()=>({state:n,dispatch:e})=>ua(n,e),ou=()=>({state:n,dispatch:e})=>Hi(n,e),lu=()=>({state:n,dispatch:e})=>Ji(n,e);function au(n,e,t={},r={}){return ft(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const cu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=au(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=ko(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function fu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function uu(n,e){const t=new xi(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function du(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function dr(n){return e=>du(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function To(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...To(t())]:e}).flat(10)}function hu(n){return typeof n=="function"}function D(n,e=void 0,...t){return hu(n)?e?n.bind(e)(...t):n(...t):n}function pu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function an(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function mu(n){const e=[],{nodeExtensions:t,markExtensions:r}=an(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function gu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Oo(n){const e=[],t=gu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Oo(r[i]),...Oo(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function No(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>cn(t,r),{})}function yu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Eo(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):yu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Do(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&pu(t)?!1:t!=null))}function Ao(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function bu(n,e){var t;const r=mu(n),{nodeExtensions:i,markExtensions:s}=an(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Do({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Ao))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Eo(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:No(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Do({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Ao))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Eo(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:No(m,f)})),[c.name,d]}));return new _r({topNode:o,nodes:l,marks:a})}function ku(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function xu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Mu(n,e){return bu(Su(n),e)}function Cu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
 
-`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function wu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Tu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Ou(n){const e=Tu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Nu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Ou(r)}function Ao(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=cr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function fn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Eu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>sn(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>sn(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function dr(n,e){const{nodeExtensions:t}=an(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Io(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Io(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Du(n,e,t){const{selection:r}=e;let i=null;if(po(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Au=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=fu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Du(r,t,a)},Iu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Ru=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Hi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Hi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Pu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Bu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},zu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Ca(r)(e,t)};function Ro(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Fu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=fn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&Ro(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:xo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Ro(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Lu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...fn(u,f.type.name,f.attrs),...e},m={...fn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function vo(n){return!n||n==="1"?null:n}function Po(n,e){return vo(n)===vo(e)}const hr=(n,e)=>{const t=ur(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!Po(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},pr=(n,e)=>{const t=ur(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!Po(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Vu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const $u=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=ur(Qe=>dr(Qe.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&dr(N.type.name,u)?{node:N,pos:0}:null,Xe=_??v,Ld=!!_&&w.depth>=1&&w.depth-_.depth<=1,tl=!!v;if((Ld||tl)&&Xe){if(Xe.node.type===h)return ne&&tl?a().command(({tr:Qe,dispatch:yn})=>{const bn=Vu(Qe);return bn?(Qe.setSelection(bn),yn&&yn(Qe),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(dr(Xe.node.type.name,u)&&h.validContent(Xe.node.content))return a().command(()=>(s.setNodeMarkup(Xe.pos,h),!0)).command(()=>hr(s,h)).command(()=>pr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>hr(s,h)).command(()=>pr(s,h)).run():a().command(()=>{const Qe=f().wrapInList(h,r),yn=A.filter(bn=>d.includes(bn.type.name));return s.ensureMarks(yn),Qe?!0:c.clearNodes()}).wrapInList(h,r).command(()=>hr(s,h)).command(()=>pr(s,h)).run()},Wu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Eu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=fr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Ju=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return fr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Hu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},qu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Ku=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=cr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},_u=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Uu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Mo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Gu=new ie("__tiptap_decorations__"),Yu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Gu,{type:"force",name:n}),!0),Xu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return pa(i,e)(t,r)},Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ya(i,e)(t,r)};var Zu=ll({blur:()=>gf,clearContent:()=>yf,clearNodes:()=>bf,command:()=>kf,createParagraphNear:()=>xf,cut:()=>Sf,deleteCurrentNode:()=>Mf,deleteNode:()=>Cf,deleteRange:()=>wf,deleteSelection:()=>Nf,enter:()=>Ef,exitCode:()=>Df,extendMarkRange:()=>If,first:()=>Rf,focus:()=>Bf,forEach:()=>zf,insertContent:()=>Ff,insertContentAt:()=>Lf,insertDefaultBlock:()=>Vf,joinBackward:()=>jf,joinDown:()=>Wf,joinForward:()=>Jf,joinItemBackward:()=>Hf,joinItemForward:()=>qf,joinTextblockBackward:()=>Kf,joinTextblockForward:()=>_f,joinUp:()=>$f,keyboardShortcut:()=>Gf,lift:()=>Yf,liftEmptyBlock:()=>Xf,liftListItem:()=>Qf,newlineInCode:()=>Zf,resetAttributes:()=>eu,scrollIntoView:()=>tu,selectAll:()=>nu,selectNodeBackward:()=>ru,selectNodeForward:()=>iu,selectParentNode:()=>su,selectTextblockEnd:()=>ou,selectTextblockStart:()=>lu,setContent:()=>cu,setMark:()=>Au,setMeta:()=>Iu,setNode:()=>Ru,setNodeSelection:()=>vu,setTextDirection:()=>Pu,setTextSelection:()=>Bu,sinkListItem:()=>zu,splitBlock:()=>Fu,splitListItem:()=>Lu,toggleList:()=>$u,toggleMark:()=>Wu,toggleNode:()=>ju,toggleWrap:()=>Ju,undoInputRule:()=>Hu,unsetAllMarks:()=>qu,unsetMark:()=>Ku,unsetTextDirection:()=>_u,updateAttributes:()=>Uu,updateDecorations:()=>Yu,wrapIn:()=>Xu,wrapInList:()=>Qu});typeof process<"u"&&process.env.NODE_ENV;function ed(n){return Object.prototype.toString.call(n).slice(8,-1)}function un(n){return ed(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Bo(n,e){const t={...n};return un(n)&&un(e)&&Object.keys(e).forEach(r=>{un(e[r])&&un(n[r])?t[r]=Bo(n[r],e[r]):t[r]=e[r]}),t}var td=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},mr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Bo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},dn=class il extends mr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new il(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},nd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class sl extends mr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=wu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Cu(r,{from:a.pos,to:c.pos},l)).join(o??`
+`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function wu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Tu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Ou(n){const e=Tu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Nu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Ou(r)}function Io(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=fr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function fn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Eu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>sn(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>sn(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function hr(n,e){const{nodeExtensions:t}=an(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Ro(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Ro(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Du(n,e,t){const{selection:r}=e;let i=null;if(mo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Au=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=fu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Du(r,t,a)},Iu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Ru=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>qi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>qi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Pu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Bu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},zu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Ca(r)(e,t)};function vo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Fu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=fn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&vo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:So(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&vo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Lu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...fn(u,f.type.name,f.attrs),...e},m={...fn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Po(n){return!n||n==="1"?null:n}function Bo(n,e){return Po(n)===Po(e)}const pr=(n,e)=>{const t=dr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!Bo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},mr=(n,e)=>{const t=dr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!Bo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Vu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const $u=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=dr(Qe=>hr(Qe.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&hr(N.type.name,u)?{node:N,pos:0}:null,Xe=_??v,Ld=!!_&&w.depth>=1&&w.depth-_.depth<=1,tl=!!v;if((Ld||tl)&&Xe){if(Xe.node.type===h)return ne&&tl?a().command(({tr:Qe,dispatch:bn})=>{const kn=Vu(Qe);return kn?(Qe.setSelection(kn),bn&&bn(Qe),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(hr(Xe.node.type.name,u)&&h.validContent(Xe.node.content))return a().command(()=>(s.setNodeMarkup(Xe.pos,h),!0)).command(()=>pr(s,h)).command(()=>mr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>pr(s,h)).command(()=>mr(s,h)).run():a().command(()=>{const Qe=f().wrapInList(h,r),bn=A.filter(kn=>d.includes(kn.type.name));return s.ensureMarks(bn),Qe?!0:c.clearNodes()}).wrapInList(h,r).command(()=>pr(s,h)).command(()=>mr(s,h)).run()},Wu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Eu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=ur(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Ju=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return ur(t,i,e)?r.lift(i):r.wrapIn(i,e)},Hu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},qu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Ku=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=fr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},_u=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Uu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Co(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Gu=new ie("__tiptap_decorations__"),Yu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Gu,{type:"force",name:n}),!0),Xu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return pa(i,e)(t,r)},Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ya(i,e)(t,r)};var Zu=ll({blur:()=>gf,clearContent:()=>yf,clearNodes:()=>bf,command:()=>kf,createParagraphNear:()=>xf,cut:()=>Sf,deleteCurrentNode:()=>Mf,deleteNode:()=>Cf,deleteRange:()=>wf,deleteSelection:()=>Nf,enter:()=>Ef,exitCode:()=>Df,extendMarkRange:()=>If,first:()=>Rf,focus:()=>Bf,forEach:()=>zf,insertContent:()=>Ff,insertContentAt:()=>Lf,insertDefaultBlock:()=>Vf,joinBackward:()=>jf,joinDown:()=>Wf,joinForward:()=>Jf,joinItemBackward:()=>Hf,joinItemForward:()=>qf,joinTextblockBackward:()=>Kf,joinTextblockForward:()=>_f,joinUp:()=>$f,keyboardShortcut:()=>Gf,lift:()=>Yf,liftEmptyBlock:()=>Xf,liftListItem:()=>Qf,newlineInCode:()=>Zf,resetAttributes:()=>eu,scrollIntoView:()=>tu,selectAll:()=>nu,selectNodeBackward:()=>ru,selectNodeForward:()=>iu,selectParentNode:()=>su,selectTextblockEnd:()=>ou,selectTextblockStart:()=>lu,setContent:()=>cu,setMark:()=>Au,setMeta:()=>Iu,setNode:()=>Ru,setNodeSelection:()=>vu,setTextDirection:()=>Pu,setTextSelection:()=>Bu,sinkListItem:()=>zu,splitBlock:()=>Fu,splitListItem:()=>Lu,toggleList:()=>$u,toggleMark:()=>Wu,toggleNode:()=>ju,toggleWrap:()=>Ju,undoInputRule:()=>Hu,unsetAllMarks:()=>qu,unsetMark:()=>Ku,unsetTextDirection:()=>_u,updateAttributes:()=>Uu,updateDecorations:()=>Yu,wrapIn:()=>Xu,wrapInList:()=>Qu});typeof process<"u"&&process.env.NODE_ENV;function ed(n){return Object.prototype.toString.call(n).slice(8,-1)}function un(n){return ed(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function zo(n,e){const t={...n};return un(n)&&un(e)&&Object.keys(e).forEach(r=>{un(e[r])&&un(n[r])?t[r]=zo(n[r],e[r]):t[r]=e[r]}),t}var td=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},gr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>zo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},dn=class il extends gr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new il(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},nd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class sl extends gr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=wu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Cu(r,{from:a.pos,to:c.pos},l)).join(o??`
 
-`)}}})]}}),fe.create({name:"commands",addCommands(){return{...Zu}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=uu(n.before,[n,...e]);Nu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const rd=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:rd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return on()||So()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Io(t.doc))return;const f=t.tr,u=co({state:t,transaction:f}),{commands:d}=new mf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=an(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Pt(n){return new td({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Ao(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var zo=class ol extends mr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Ao(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var id=zo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
+`)}}})]}}),fe.create({name:"commands",addCommands(){return{...Zu}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=uu(n.before,[n,...e]);Nu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const rd=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:rd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return on()||Mo()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Ro(t.doc))return;const f=t.tr,u=fo({state:t,transaction:f}),{commands:d}=new mf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=an(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Pt(n){return new td({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Io(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Fo=class ol extends gr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Io(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var id=Fo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
 
-`):""}),sd=zo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Fo=new WeakSet,Lo=new WeakSet;function Ue(n){const e=n;return Fo.add(e),e}function gr(n){return Array.isArray(n)&&Fo.has(n)}function Vo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Lo.has(e)&&!gr(e)?Vo(e):[e])}function od(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!gr(i)&&!Lo.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(gr(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=Vo(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const $o=(n,e)=>od(n,e),ld=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,cd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var ud=dn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return $o("strong",{...cn(this.options.HTMLAttributes,n),children:$o("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Pt({find:ld,type:this.type}),Pt({find:cd,type:this.type})]},addPasteRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]}});const dd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,pd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var gd=dn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",cn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Pt({find:dd,type:this.type}),Pt({find:pd,type:this.type})]},addPasteRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]}});const yd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},bd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var kd=dn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",cn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Pt({find:yd,type:this.type})]},addPasteRules(){return[Bt({find:bd,type:this.type})]}}),hn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Wo(e):z.empty};var Wo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=hn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=hn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Wo([]);var xd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Sd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fCd&&(l=Md(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new yt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dSd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Md(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Cd=20;function wd(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Nd)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,pn(e)),n.undone,jo(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,pn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Td(t,n.prevRanges)),c=o?yr(n.prevRanges,t.mapping):jo(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,pn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),yr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),yr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Td(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function jo(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function yr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Od(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const qo=Ho(!1,!0),kr=Ho(!0,!0),Ye="data-bd-src",Dd=dn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),mn=Mu([id.extend({content:"inline*"}),sd,ud,gd,kd,Dd]),Ad=de.fromSchema(mn),Id=Le.fromSchema(mn),Rd={preserveWhitespace:"full"};function Ko(n){return Ad.parse(n,Rd)}function _o(n){const e=document.createElement("div");return e.appendChild(Id.serializeFragment(n.content)),e.innerHTML}function vd(n){try{return _o(Ko(n))===n.innerHTML}catch{return!1}}function Uo(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const xr=n=>parent.postMessage(n,"*"),Sr=new WeakMap;function Go(n){let e=Sr.get(n);return e===void 0&&(e=vd(n),Sr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let te=null,ve=null,ut=null,Mr="";function Yo(){return te?_o(te.state.doc):null}function Xo(){if(!ve||!ut)return;const n=Yo();n===null||n===Mr||(Mr=n,xr({type:"bd-edit:patch",start:ut.start,end:ut.end,html:n}))}function gn(){if(!te)return;Xo();const n=ve,e=Yo();te.destroy(),te=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Sr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,ut=null}function Pd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function Bd(n,e,t){if(ve===n)return;gn();const r=Uo(n);if(!r)return;ve=n,ut=r,Mr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=rt.create({doc:Ko(n),plugins:[Ed(),ao({"Mod-b":qi(mn.marks.bold),"Mod-i":qi(mn.marks.italic),"Mod-z":qo,"Mod-y":kr,"Shift-Mod-z":kr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(gn(),!0)}),ao(ga)]});te=new no({mount:n},{state:i,dispatchTransaction(s){te.updateState(te.state.apply(s)),s.docChanged&&Xo()}}),te.focus(),e!==void 0&&t!==void 0&&Pd(te,e,t)}function Qo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{const e=Qo(n.target);if(!e){gn();return}Go(e)&&Bd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Qo(n.target);e&&Go(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(xr({type:"bd-edit:clobbered"}),te?.destroy(),te=null,ve=null,ut=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const Zo=document.createElement("style");Zo.textContent=`
+`):""}),sd=Fo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Lo=new WeakSet,Vo=new WeakSet;function Ue(n){const e=n;return Lo.add(e),e}function yr(n){return Array.isArray(n)&&Lo.has(n)}function $o(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Vo.has(e)&&!yr(e)?$o(e):[e])}function od(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!yr(i)&&!Vo.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(yr(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=$o(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const Wo=(n,e)=>od(n,e),ld=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,cd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var ud=dn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Wo("strong",{...cn(this.options.HTMLAttributes,n),children:Wo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Pt({find:ld,type:this.type}),Pt({find:cd,type:this.type})]},addPasteRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]}});const dd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,pd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var gd=dn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",cn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Pt({find:dd,type:this.type}),Pt({find:pd,type:this.type})]},addPasteRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]}});const yd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},bd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var kd=dn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",cn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Pt({find:yd,type:this.type})]},addPasteRules(){return[Bt({find:bd,type:this.type})]}}),hn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new jo(e):z.empty};var jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=hn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=hn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new jo([]);var xd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Sd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fCd&&(l=Md(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new yt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dSd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Md(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Cd=20;function wd(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Nd)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,pn(e)),n.undone,Jo(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,pn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Td(t,n.prevRanges)),c=o?br(n.prevRanges,t.mapping):Jo(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,pn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),br(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),br(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Td(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Jo(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function br(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Od(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Ko=qo(!1,!0),xr=qo(!0,!0),Ye="data-bd-src",Dd=dn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),mn=Mu([id.extend({content:"inline*"}),sd,ud,gd,kd,Dd]),Ad=de.fromSchema(mn),Id=Le.fromSchema(mn),Rd={preserveWhitespace:"full"};function _o(n){return Ad.parse(n,Rd)}function Uo(n){const e=document.createElement("div");return e.appendChild(Id.serializeFragment(n.content)),e.innerHTML}function vd(n){try{return Uo(_o(n))===n.innerHTML}catch{return!1}}function Go(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const gn=n=>parent.postMessage(n,"*"),Sr=new WeakMap;function Yo(n){let e=Sr.get(n);return e===void 0&&(e=vd(n),Sr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let te=null,ve=null,ut=null,Mr="";function Xo(){return te?Uo(te.state.doc):null}function Cr(){if(!ve||!ut)return;const n=Xo();n===null||n===Mr||(Mr=n,gn({type:"bd-edit:patch",start:ut.start,end:ut.end,html:n}))}function yn(){if(!te)return;Cr();const n=ve,e=Xo();te.destroy(),te=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Sr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,ut=null}function Pd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function Bd(n,e,t){if(ve===n)return;yn();const r=Go(n);if(!r)return;ve=n,ut=r,Mr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=rt.create({doc:_o(n),plugins:[Ed(),co({"Mod-b":Ki(mn.marks.bold),"Mod-i":Ki(mn.marks.italic),"Mod-z":Ko,"Mod-y":xr,"Shift-Mod-z":xr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(yn(),!0)}),co(ga)]});te=new ro({mount:n},{state:i,dispatchTransaction(s){te.updateState(te.state.apply(s)),s.docChanged&&Cr()}}),te.focus(),e!==void 0&&t!==void 0&&Pd(te,e,t)}function Qo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{const e=Qo(n.target);if(!e){yn();return}Yo(e)&&Bd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Qo(n.target);e&&Yo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(gn({type:"bd-edit:clobbered"}),te?.destroy(),te=null,ve=null,ut=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const Zo=document.createElement("style");Zo.textContent=`
   [${Ye}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; }
   [${Ye}][data-bd-edit="no"]:hover  { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; }
   [${Ye}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; }
   [${Ye}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); }
-`,document.head.appendChild(Zo);const el=document.currentScript??document.querySelector("script[data-src-hash]"),zd=el?.dataset.srcHash??"",Fd=Number(el?.dataset.srcLen??"-1");xr({type:"bd-edit:ready",hash:zd,len:Fd,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Uo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",gn)})();
+`,document.head.appendChild(Zo);const el=document.currentScript??document.querySelector("script[data-src-hash]"),zd=el?.dataset.srcHash??"",Fd=Number(el?.dataset.srcLen??"-1");gn({type:"bd-edit:ready",hash:zd,len:Fd,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Go(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",yn),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;!e||e.type!=="bd-edit:flush"||typeof e.id!="number"||(Cr(),gn({type:"bd-edit:flushed",id:e.id}))})})();

From 228a0b15d71041c419caaa90918ce472cabe9781 Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Wed, 11 Nov 2026 23:39:26 +0900
Subject: [PATCH 12/34] fix(webapp): lock VisualEdit iframe during Done save
 and unlock on stay

---
 architecture/webapp-frontend.md               |  6 +-
 internal/webapp/frontend/src/apps/Browser.tsx | 12 +--
 .../frontend/src/components/VisualEdit.tsx    | 21 +++--
 internal/webapp/frontend/src/inline-edit.ts   | 38 ++++++--
 .../webapp/frontend/src/lib/frameflush.ts     | 33 +++++--
 .../src/lib/sharedfile_restore.test.ts        | 88 +++++++++++++++++--
 ...{Editor-vslxZvKp.js => Editor-DzwiNrvp.js} |  2 +-
 .../static/assets/VisualEdit-Co88xBUl.js      |  1 +
 .../static/assets/VisualEdit-ZWfN9slK.js      |  1 -
 .../{index-C9ixuBUD.js => index-BtQZiOrJ.js}  |  6 +-
 ...ile-CNg6aQyd.js => sharedfile-ifG4O60o.js} |  2 +-
 internal/webapp/static/index.html             |  2 +-
 internal/webapp/static/inline-edit.js         | 26 +++---
 13 files changed, 181 insertions(+), 57 deletions(-)
 rename internal/webapp/static/assets/{Editor-vslxZvKp.js => Editor-DzwiNrvp.js} (99%)
 create mode 100644 internal/webapp/static/assets/VisualEdit-Co88xBUl.js
 delete mode 100644 internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
 rename internal/webapp/static/assets/{index-C9ixuBUD.js => index-BtQZiOrJ.js} (98%)
 rename internal/webapp/static/assets/{sharedfile-CNg6aQyd.js => sharedfile-ifG4O60o.js} (99%)

diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md
index 56723eec..fe9e81c7 100644
--- a/architecture/webapp-frontend.md
+++ b/architecture/webapp-frontend.md
@@ -190,7 +190,7 @@ classDiagram
         +collab.ts CollabDoc peerCount isRemote onStalled encodeState applySplices applyRemoteUpdate (y-websocket to the hub-held document; stop only when there is no room route)
         +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once)
         +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them)
-        +frameflush.ts frameChannel FrameChannel (FIFO queue of iframe messages; drain posts bd-edit:flush and waits for bd-edit:flushed)
+        +frameflush.ts frameChannel FrameChannel saveLocked (FIFO queue of iframe messages; drain posts bd-edit:flush, optionally with lock, and waits for bd-edit:flushed; saveLocked unlocks with bd-edit:unlock unless the save landed)
         +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink
         +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room)
         +sharedfile.ts rebase (the head sha moved because a co-editor saved)
@@ -234,7 +234,7 @@ classDiagram
     components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand)
     note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain 
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
     note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow (Promise<boolean>) + askingShrink, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation"
-    note for lib "frameflush.ts is VisualEdit's side of the iframe's postMessage stream. frameChannel handles every message strictly in arrival order, each after the one before it finishes (anchoring is async), so an edit typed just before Done cannot still be queued when the save looks at the buffer. Before VisualEdit's saveNow, drain() posts bd-edit:flush with an id; inline-edit.ts posts any edit it still holds and then answers bd-edit:flushed with that id on the same channel, so once the answer is handled every earlier patch is in the document. A drain waits as long as the frame is there to answer, never on a timer, and gives up only when the frame is gone or the editor closes"
+    note for lib "frameflush.ts is VisualEdit's side of the iframe's postMessage stream. frameChannel handles every message strictly in arrival order, each after the one before it finishes (anchoring is async), so an edit typed just before Done cannot still be queued when the save looks at the buffer. drain() posts bd-edit:flush with an id; inline-edit.ts posts any edit it still holds and then answers bd-edit:flushed with that id on the same channel, so once the answer is handled every earlier patch is in the document. A drain waits as long as the frame is there to answer, never on a timer, and gives up only when the frame is gone or the editor closes. Done's save goes through saveLocked(drain, save, unlock): the flush carries lock: true, so the frame stops accepting edits until bd-edit:unlock and nothing typed during the save can be left out of it. If saveNow returns false or throws (a failed save or an open shrink question, so the editor stays), saveLocked posts bd-edit:unlock; a save that lands leaves the frame locked because the editor is about to close. Concurrent Done calls share one saveLocked"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
@@ -246,7 +246,7 @@ classDiagram
     shareMermaid --> lib : renderMermaid
     inlineComment --> lib : anchor.ts (no app imports)
     components --> lib : rangeFor describe hitTest (Comments)
-    components --> lib : merge3PreferRight diffSplices frameChannel (VisualEdit), saveNow askingShrink (FileView flush)
+    components --> lib : merge3PreferRight diffSplices frameChannel saveLocked (VisualEdit), saveNow askingShrink (FileView flush)
     Browser ..> components : Done awaits FileView's flushRef
     lib --> api : syncCollab putText keepalive (sharedfile)
     components ..> inlineComment : postMessage via the ?comment=1 iframe
diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx
index 8b2e70e0..e79f7b75 100644
--- a/internal/webapp/frontend/src/apps/Browser.tsx
+++ b/internal/webapp/frontend/src/apps/Browser.tsx
@@ -1166,18 +1166,18 @@ export default function Browser(props: {
                 if (flush && leavingFlushRef.current === flush) return;
                 leavingFlushRef.current = flush;
                 try {
-                  const target = urlForPath(path, project?.id, version, route.full, false);
-                  const here = window.location.pathname + window.location.search;
+                  const herePath = window.location.pathname;
                   let okToLeave = true;
                   try {
                     okToLeave = await (flush?.() ?? Promise.resolve(true));
                   } catch {
                     // The editor's own teardown still sends what it holds.
                   }
-                  if (!okToLeave) return; // the shrink dialog is open: answer it here
-                  // Somewhere else already (a click elsewhere while saving): stay there.
-                  if (window.location.pathname + window.location.search !== here) return;
-                  navigate(target);
+                  if (!okToLeave) return; // unsaved or shrink dialog open: stay here
+                  // Left this edit route already (clicked another file/view): stay there.
+                  if (window.location.pathname !== herePath) return;
+                  const fullNow = new URLSearchParams(window.location.search).get("full") === "1";
+                  navigate(urlForPath(path, project?.id, version, fullNow, false));
                 } finally {
                   if (leavingFlushRef.current === flush) leavingFlushRef.current = null;
                 }
diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx
index 6a441252..a711b385 100644
--- a/internal/webapp/frontend/src/components/VisualEdit.tsx
+++ b/internal/webapp/frontend/src/components/VisualEdit.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react";
 import * as Y from "yjs";
 import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile";
 import { diffSplices, merge3PreferRight } from "../lib/merge3";
-import { frameChannel } from "../lib/frameflush";
+import { frameChannel, saveLocked } from "../lib/frameflush";
 import { type CollabStatus } from "../lib/collab";
 import { askShrink, withdrawShrink } from "./ShrinkDialog";
 
@@ -245,7 +245,7 @@ export function VisualEdit({
        decides whether the editor may close. */
     const channel = frameChannel();
     let frameReady = false;
-    const drainFrame = async () => {
+    const drainFrame = async (lock: boolean) => {
       const el = frame.current;
       const win = el?.contentWindow;
       if (!el || !win) return;
@@ -259,6 +259,7 @@ export function VisualEdit({
         await channel.drain(
           (m) => win.postMessage(m, "*"),
           () => !frameReady || reloaded || frame.current !== el || el.contentWindow !== win,
+          lock,
         );
       } finally {
         el.removeEventListener("load", onLoad);
@@ -267,12 +268,20 @@ export function VisualEdit({
       clearTimeout(stageTimer);
       stageTimer = undefined;
     };
+    /* Done: the frame is drained AND locked, so nothing typed while the save
+       is on the wire can be left out of it; it is unlocked again unless the
+       save landed (lib/frameflush.ts saveLocked). Concurrent calls share one. */
+    let savingFrame: Promise | null = null;
     const exposed: SharedFile = {
       ...file,
-      saveNow: async () => {
-        await drainFrame();
-        return file.saveNow();
-      },
+      saveNow: () =>
+        (savingFrame ??= saveLocked(
+          () => drainFrame(true),
+          () => file.saveNow(),
+          () => frame.current?.contentWindow?.postMessage({ type: "bd-edit:unlock" }, "*"),
+        ).finally(() => {
+          savingFrame = null;
+        })),
     };
     if (handle) handle.current = exposed;
 
diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts
index 6b900a5f..999bb6d0 100644
--- a/internal/webapp/frontend/src/inline-edit.ts
+++ b/internal/webapp/frontend/src/inline-edit.ts
@@ -5,9 +5,12 @@
    (server.go's serveEditable). A reader never downloads an editor, and the
    iframe keeps exactly the sandbox it always had — no allow-same-origin — so
    nothing here can reach the hub's session. It talks to the app by postMessage
-   and accepts one thing back: `bd-edit:flush` (with a numeric id), which posts
-   any edit still held here and answers `bd-edit:flushed` with that id, so the
-   app's Done saves only after every patch before the answer has landed.
+   and accepts two things back: `bd-edit:flush` (a numeric id, optionally
+   `lock: true`), which posts any edit still held here and answers
+   `bd-edit:flushed` with that id — so the app's Done saves only after every
+   patch before the answer has landed — and, with `lock`, stops accepting
+   edits until `bd-edit:unlock`, so nothing typed during Done's save can be
+   left out of it.
 
    Three things had to be true at once, and they decided the design:
 
@@ -180,6 +183,9 @@ let view: EditorView | null = null;
 let host: HTMLElement | null = null;
 let range: Range | null = null;
 let before = "";
+/* Done's save is on the wire: no edit may start until the app says how it
+   went (`bd-edit:unlock` if the editor stays; a page torn down otherwise). */
+let locked = false;
 
 // The document as markup, or null if there is no live editor.
 function currentHTML(): string | null {
@@ -280,7 +286,9 @@ function mount(el: HTMLElement, x?: number, y?: number) {
     { mount: el },
     {
       state,
+      editable: () => !locked,
       dispatchTransaction(tr) {
+        if (locked && tr.docChanged) return;
         view!.updateState(view!.state.apply(tr));
         /* Reported on EVERY change, with no debounce of its own.
 
@@ -312,6 +320,7 @@ function nearestEditable(target: EventTarget | null): HTMLElement | null {
 document.addEventListener(
   "click",
   (e) => {
+    if (locked) return; // no element opens or closes while Done saves
     const el = nearestEditable(e.target);
     if (!el) {
       unmount(); // clicking away commits, the same as blurring
@@ -390,11 +399,24 @@ window.addEventListener("beforeunload", unmount);
 
 /* Done in the app: post what the open editor holds, then answer. The answer
    follows every patch on the same channel, so once the app has handled it, it
-   has handled them all. Only the app (the parent window) may ask. */
+   has handled them all. With `lock`, nothing more is typed until the app
+   unlocks (its save failed or asked a question) or tears the page down (it
+   saved). Only the app (the parent window) may ask. */
 window.addEventListener("message", (e) => {
   if (e.source !== window.parent) return;
-  const msg = e.data as { type?: unknown; id?: unknown } | null;
-  if (!msg || msg.type !== "bd-edit:flush" || typeof msg.id !== "number") return;
-  flush();
-  send({ type: "bd-edit:flushed", id: msg.id });
+  const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown } | null;
+  if (!msg) return;
+  if (msg.type === "bd-edit:flush" && typeof msg.id === "number") {
+    flush();
+    if (msg.lock === true) {
+      locked = true;
+      view?.setProps({ editable: () => !locked });
+    }
+    send({ type: "bd-edit:flushed", id: msg.id });
+    return;
+  }
+  if (msg.type === "bd-edit:unlock") {
+    locked = false;
+    view?.setProps({ editable: () => !locked });
+  }
 });
diff --git a/internal/webapp/frontend/src/lib/frameflush.ts b/internal/webapp/frontend/src/lib/frameflush.ts
index 9cfe2b4c..771acf9d 100644
--- a/internal/webapp/frontend/src/lib/frameflush.ts
+++ b/internal/webapp/frontend/src/lib/frameflush.ts
@@ -12,7 +12,9 @@
    after its last patch on the same channel, so by the time it is handled here
    every patch before it has been spliced into the document. */
 
-export type FlushRequest = { type: "bd-edit:flush"; id: number };
+// `lock`: the frame also stops taking edits until `bd-edit:unlock`, so nothing
+// typed while the save that follows is on the wire can be left out of it.
+export type FlushRequest = { type: "bd-edit:flush"; id: number; lock?: true };
 
 export type FrameChannel = {
   /** Handle one message, after every message before it has been handled. */
@@ -21,8 +23,9 @@ export type FrameChannel = {
   flushed(id: number): void;
   /** Ask the frame for everything it holds and wait until it has been
       handled. Waits as long as the frame is there to answer — never on a
-      timer — and gives up only once `gone()` says it cannot. */
-  drain(post: (msg: FlushRequest) => void, gone: () => boolean): Promise;
+      timer — and gives up only once `gone()` says it cannot. With `lock`, the
+      frame takes no more edits until it is sent `bd-edit:unlock`. */
+  drain(post: (msg: FlushRequest) => void, gone: () => boolean, lock?: boolean): Promise;
   /** The editor is going: nothing waits on the frame any more. */
   close(): void;
 };
@@ -45,7 +48,7 @@ export function frameChannel(): FrameChannel {
       waiting.get(id)?.();
       waiting.delete(id);
     },
-    async drain(post, gone) {
+    async drain(post, gone, lock = false) {
       await settled();
       if (closed || gone()) return;
       const id = ++seq;
@@ -59,7 +62,7 @@ export function frameChannel(): FrameChannel {
         }, GONE_POLL_MS);
       });
       try {
-        post({ type: "bd-edit:flush", id });
+        post(lock ? { type: "bd-edit:flush", id, lock: true } : { type: "bd-edit:flush", id });
         await answered;
       } finally {
         clearInterval(poll);
@@ -73,3 +76,23 @@ export function frameChannel(): FrameChannel {
     },
   };
 }
+
+/* Done's save through the frame: drain it and lock it (`drain`), save, and
+   unlock it unless the save landed. A save that lands leaves the frame
+   locked, since the editor is about to close; one that fails, throws or
+   opens a question unlocks it, since the editor stays and the user may go on
+   typing. */
+export async function saveLocked(
+  drain: () => Promise,
+  save: () => Promise,
+  unlock: () => void,
+): Promise {
+  let ok = false;
+  try {
+    await drain();
+    ok = await save();
+    return ok;
+  } finally {
+    if (!ok) unlock();
+  }
+}
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index c73f8436..6f5c260c 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -54,7 +54,7 @@ const { CollabDoc } = await import("./collab.ts");
 const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts");
 const { parseConflict } = await import("./conflict.ts");
 const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts");
-const { frameChannel } = await import("./frameflush.ts");
+const { frameChannel, saveLocked } = await import("./frameflush.ts");
 
 /* toEqual's semantics: a property that is undefined is a property that is
    absent. Only plain objects and arrays are rebuilt; anything else (a
@@ -2484,11 +2484,14 @@ for (const keepAnswer of [200, 503]) {
    that patch would meet. Draining first — flush request, the frame posts what
    it holds, then `bd-edit:flushed` on the same channel — puts the patch in
    the document before the save decides. `frame` stands in for the iframe:
-   `deliver` is a message arriving on window "message", later, in order. */
+   `deliver` is a message arriving on window "message", later, in order; a
+   flush with `lock` makes it refuse typing (`type`) until it is unlocked. */
 function frameHarness(answer: (body: string) => Response) {
   const puts: string[] = [];
+  const net: { hold: Promise | null } = { hold: null };
   globalThis.fetch = (async (_url: RequestInfo | URL, init?: RequestInit) => {
     puts.push(String(init?.body));
+    if (net.hold) await net.hold;
     return answer(String(init?.body));
   }) as typeof fetch;
   const state = { buffer: "a\nb\nc\n" };
@@ -2521,18 +2524,29 @@ function frameHarness(answer: (body: string) => Response) {
         else channel.flushed(msg.id);
       }),
     );
-  const frame = { gone: false, answers: true, flushes: 0 };
-  const post = (m: { type: "bd-edit:flush"; id: number }) => {
+  const frame = { gone: false, answers: true, flushes: 0, locked: false };
+  const post = (m: { type: "bd-edit:flush"; id: number; lock?: true }) => {
     frame.flushes++;
+    if (m.lock) frame.locked = true;
     if (frame.answers) deliver({ type: "flushed", id: m.id });
   };
-  // VisualEdit's exposed saveNow.
-  const saveNow = async () => {
-    await channel.drain(post, () => frame.gone);
-    return file.saveNow();
+  // Typing in the frame: a patch posted, unless Done's save has it locked.
+  const type = (text: string) => {
+    if (frame.locked) return false;
+    deliver({ type: "patch", text });
+    return true;
   };
+  // VisualEdit's exposed saveNow.
+  const saveNow = () =>
+    saveLocked(
+      () => channel.drain(post, () => frame.gone, true),
+      () => file.saveNow(),
+      () => {
+        frame.locked = false;
+      },
+    );
   const ready = () => waitFor(() => assert.equal(solo, true));
-  return { file, state, asks, puts, channel, deliver, frame, saveNow, ready };
+  return { file, state, asks, puts, net, channel, deliver, type, frame, saveNow, ready };
 }
 
 test("Done drains the frame's queued patch before saving: a sharp shrink in it asks", async () => {
@@ -2611,3 +2625,59 @@ test("Done's drain waits on a live frame and stops once the frame is gone", asyn
     realTimers();
   }
 });
+
+/* Typing while Done's save is on the wire never reaches that save, so it is
+   blocked: the flush locks the frame. A save that lands leaves it locked (the
+   editor closes); one that fails or asks a question unlocks it, and the
+   typing after that is taken and saved by the next Done. */
+for (const outcome of ["saved", "503", "shrink"] as const) {
+  test(`the frame is locked while Done saves, and unlocked if the editor stays (${outcome})`, async () => {
+    let status = outcome === "saved" ? 200 : outcome === "503" ? 503 : 422;
+    const h = frameHarness(() =>
+      status === 200
+        ? new Response(JSON.stringify({ sha: "sha-b" }), { status: 200 })
+        : status === 503
+          ? new Response("unavailable", { status: 503 })
+          : new Response(JSON.stringify({ error: "would cut most of the file", shrink: true }), { status: 422 }),
+    );
+    try {
+      await h.ready();
+      assert.equal(h.type("a\nb\nc\nd\n"), true);
+      const gate = Promise.withResolvers();
+      h.net.hold = gate.promise;
+      let result: boolean | null = null;
+      void h.saveNow().then((r) => {
+        result = r;
+      });
+      await waitFor(() => assert.equal(h.puts.length, 1)); // the save is on the wire
+      assert.equal(h.puts[0], "a\nb\nc\nd\n");
+      assert.equal(h.frame.locked, true);
+      assert.equal(h.type("a\nb\nc\nd\ntyped during the save\n"), false); // blocked
+
+      h.net.hold = null;
+      gate.resolve();
+      await waitFor(() => assert.notEqual(result, null));
+      if (outcome === "saved") {
+        assert.equal(result, true);
+        assert.equal(h.frame.locked, true); // the editor is closing
+        same(h.puts, ["a\nb\nc\nd\n"]);
+        return;
+      }
+      assert.equal(result, false);
+      assert.equal(h.frame.locked, false); // the editor stays: typing again
+      if (outcome === "shrink") assert.equal(h.file.askingShrink(), true);
+      else {
+        assert.equal(h.type("a\nb\nc\nd\ne\n"), true);
+        await waitFor(() => assert.equal(h.state.buffer, "a\nb\nc\nd\ne\n"));
+        status = 200;
+        assert.equal(await h.saveNow(), true);
+        assert.equal(h.puts.at(-1), "a\nb\nc\nd\ne\n");
+        assert.equal(h.frame.locked, true);
+      }
+    } finally {
+      h.channel.close();
+      h.file.destroy();
+      await settle();
+    }
+  });
+}
diff --git a/internal/webapp/static/assets/Editor-vslxZvKp.js b/internal/webapp/static/assets/Editor-DzwiNrvp.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-vslxZvKp.js
rename to internal/webapp/static/assets/Editor-DzwiNrvp.js
index 438fcfe4..1239ce9b 100644
--- a/internal/webapp/static/assets/Editor-vslxZvKp.js
+++ b/internal/webapp/static/assets/Editor-DzwiNrvp.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-C9ixuBUD.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CNg6aQyd.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BtQZiOrJ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-ifG4O60o.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-Co88xBUl.js b/internal/webapp/static/assets/VisualEdit-Co88xBUl.js
new file mode 100644
index 00000000..0f66f3b3
--- /dev/null
+++ b/internal/webapp/static/assets/VisualEdit-Co88xBUl.js
@@ -0,0 +1 @@
+import{r as c,j as E,w as we,a as be}from"./index-BtQZiOrJ.js";import{o as ve,D as Te,c as L,a as G,m as ce,d as le}from"./sharedfile-ifG4O60o.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Se=50;function Re(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,A=!1){if(await W(),x||j())return;const b=++f;let v;const q=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},Se)});try{d(A?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await q}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function ke(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function Ee(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Fe({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:A,onConflictCopy:b,baseSha:v,onSaved:q,onWriting:M,onRendered:J,handle:D}){const T=c.useRef(null),[K,de]=c.useState(null),[ue,Q]=c.useState(!1),[fe,U]=c.useState(!1),X=c.useRef(0),[Z,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b};const I=c.useRef(x),H=c.useRef(W);H.current=W;const $=c.useRef(v);$.current=v;const B=c.useRef(null);return c.useEffect(()=>{B.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,P=!1,r=null,m;const xe=700;Q(!1),U(!1);const he=setTimeout(()=>{!y&&X.current<1&&(X.current++,S(e=>e+1))},11e3),pe=setTimeout(()=>U(!0),24e3),s=B.current=ve({apiBase:u,path:f,seed:I.current,baseSha:$.current,who:H.current?.name,me:H.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>be(f,e),onShrinkWithdrawn:we,onReady:()=>{if(clearTimeout(m),m=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(y&&t===i)for(const[o,n]of g){const p=L(n.from,e),C=L(n.to,e);p&&C&&g.set(o,{from:G(s.collab.text,p.index),to:G(s.collab.text,C.index),span:n.span,orig:n.orig})}else g.clear(),y=!1,t!==i&&S(o=>o+1);e.destroy()}P=!0,k()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,I.current),P=!0,k()},onStalled:()=>{P||r||(r=new Te,r.getText("body").insert(0,I.current),P=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():I.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),_=Re();let O=!1;const me=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let o=!1;const n=()=>{o=!0};t.addEventListener("load",n);try{await _.drain(p=>i.postMessage(p,"*"),()=>!O||o||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0};let ee=null;const te={...s,saveNow:()=>ee??=ke(()=>me(!0),()=>s.saveNow(),()=>T.current?.contentWindow?.postMessage({type:"bd-edit:unlock"},"*")).finally(()=>{ee=null})};D&&(D.current=te);const g=new Map,ne=e=>e.start+","+e.end,k=async()=>{if(y||!R||!P)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await Ee(t);if(i!==null?i!==re:V>=0&&t.length!==V){R=null,S(n=>n+1);return}g.clear();for(const n of R)g.set(ne(n),{from:G(e,n.start),to:G(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});y=!0,Q(!0),h.current.onRendered?.()};let re="",V=-1,y=!1;const ge=async e=>{if(e.type==="bd-edit:flushed"){_.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){de("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,re=e.hash,V=e.len,O=!0,await k();return}if(e.type!=="bd-edit:patch")return;y||await k();const t=g.get(ne(e));if(!t)return;if(r){const l=L(t.from,r),F=L(t.to,r);if(!l||!F||l.index>F.index)return;const N=r.getText("body"),ye=F.index-l.index;if(l.index===0&&F.index===N.length&&t.spant.span*4+256){g.clear(),y=!1,S(w=>w+1);return}const z=N.toString().slice(l.index,F.index),ae=ce(t.orig,z,e.html);if(t.orig=e.html,z===ae)return;r.transact(()=>{for(const w of le(z,ae))w.deleteCount>0&&N.delete(l.index+w.index,w.deleteCount),w.insertText&&N.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{s.saveNow()},xe);return}const i=s.collab.doc,o=L(t.from,i),n=L(t.to,i);if(!o||!n||o.index>n.index)return;const p=s.collab.text,C=n.index-o.index;if(o.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),g.clear(),y=!1,S(l=>l+1);return}const Y=p.toString().slice(o.index,n.index),ie=ce(t.orig,Y,e.html);t.orig=e.html,Y!==ie&&s.collab.applySplices(le(Y,ie).map(l=>({...l,index:l.index+o.index})))},oe=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||_.enqueue(()=>ge(t))},se=()=>{k()};return s.collab.text.observe(se),window.addEventListener("message",oe),()=>{D?.current===te&&(D.current=null),O=!1,_.close(),clearTimeout(he),clearTimeout(pe),clearTimeout(m),s.collab.text.unobserve(se),setTimeout(()=>{window.removeEventListener("message",oe),clearTimeout(m),s.destroy(),r?.destroy()},300)}},[u,f,Z]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),fe&&!ue&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},Z)]})}export{Fe as VisualEdit};
diff --git a/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js b/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
deleted file mode 100644
index 6251887f..00000000
--- a/internal/webapp/static/assets/VisualEdit-ZWfN9slK.js
+++ /dev/null
@@ -1 +0,0 @@
-import{r as a,j as R,w as ye,a as we}from"./index-C9ixuBUD.js";import{o as be,D as ve,c as E,a as _,m as ae,d as ce}from"./sharedfile-CNg6aQyd.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Te=50;function Se(){let f=Promise.resolve();const l=new Map;let x=0,k=!1;const L=()=>f.then(()=>{});return{enqueue(d){f=f.then(d).catch(()=>{})},flushed(d){l.get(d)?.(),l.delete(d)},async drain(d,j){if(await L(),k||j())return;const w=++x;let W;const b=new Promise(P=>{l.set(w,P),W=setInterval(()=>{!k&&!j()||(l.delete(w),P())},Te)});try{d({type:"bd-edit:flush",id:w}),await b}finally{clearInterval(W)}await L()},close(){k=!0;for(const d of l.values())d();l.clear()}}}async function Re(f){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(f));return[...new Uint8Array(l)].map(x=>x.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ce({apiBase:f,fileURL:l,path:x,initial:k,me:L,onStateChange:d,onCollab:j,onPeers:w,onConflictCopy:W,baseSha:b,onSaved:P,onWriting:z,onRendered:J,handle:q}){const C=a.useRef(null),[K,le]=a.useState(null),[de,Q]=a.useState(!1),[ue,U]=a.useState(!1),X=a.useRef(0),[Z,v]=a.useState(0),u=a.useRef({onStateChange:d,onCollab:j,onPeers:w,onSaved:P,onWriting:z,onRendered:J,onConflictCopy:W});u.current={onStateChange:d,onCollab:j,onPeers:w,onSaved:P,onWriting:z,onRendered:J,onConflictCopy:W};const D=a.useRef(k),G=a.useRef(L);G.current=L;const $=a.useRef(b);$.current=b;const B=a.useRef(null);return a.useEffect(()=>{B.current?.rebase(b)},[b]),a.useEffect(()=>{let T=null,M=!1,r=null,h;const fe=700;Q(!1),U(!1);const xe=setTimeout(()=>{!p&&X.current<1&&(X.current++,v(e=>e+1))},11e3),he=setTimeout(()=>U(!0),24e3),s=B.current=be({apiBase:f,path:x,seed:D.current,baseSha:$.current,who:G.current?.name,me:G.current,onConflictCopy:e=>u.current.onConflictCopy?.(e),onShrinkRefused:e=>we(x,e),onShrinkWithdrawn:ye,onReady:()=>{if(clearTimeout(h),h=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(p&&t===i)for(const[o,n]of m){const y=E(n.from,e),N=E(n.to,e);y&&N&&m.set(o,{from:_(s.collab.text,y.index),to:_(s.collab.text,N.index),span:n.span,orig:n.orig})}else m.clear(),p=!1,t!==i&&v(o=>o+1);e.destroy()}M=!0,S()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,D.current),M=!0,S()},onStalled:()=>{M||r||(r=new ve,r.getText("body").insert(0,D.current),M=!0,S())},onState:e=>u.current.onStateChange?.(e),onCollab:e=>u.current.onCollab?.(e),onPeers:e=>u.current.onPeers?.(e),onSaved:e=>u.current.onSaved?.(e),onWriting:()=>u.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():D.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),I=Se();let H=!1;const me=async()=>{const e=C.current,t=e?.contentWindow;if(!e||!t)return;let i=!1;const o=()=>{i=!0};e.addEventListener("load",o);try{await I.drain(n=>t.postMessage(n,"*"),()=>!H||i||C.current!==e||e.contentWindow!==t)}finally{e.removeEventListener("load",o)}clearTimeout(h),h=void 0},ee={...s,saveNow:async()=>(await me(),s.saveNow())};q&&(q.current=ee);const m=new Map,te=e=>e.start+","+e.end,S=async()=>{if(p||!T||!M)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(T.some(n=>n.end>t.length||n.start>n.end)){T=null,v(n=>n+1);return}const i=await Re(t);if(i!==null?i!==ne:O>=0&&t.length!==O){T=null,v(n=>n+1);return}m.clear();for(const n of T)m.set(te(n),{from:_(e,n.start),to:_(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});p=!0,Q(!0),u.current.onRendered?.()};let ne="",O=-1,p=!1;const pe=async e=>{if(e.type==="bd-edit:flushed"){I.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){le("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){T=e.ranges,ne=e.hash,O=e.len,H=!0,await S();return}if(e.type!=="bd-edit:patch")return;p||await S();const t=m.get(te(e));if(!t)return;if(r){const c=E(t.from,r),A=E(t.to,r);if(!c||!A||c.index>A.index)return;const F=r.getText("body"),ge=A.index-c.index;if(c.index===0&&A.index===F.length&&t.spant.span*4+256){m.clear(),p=!1,v(g=>g+1);return}const Y=F.toString().slice(c.index,A.index),ie=ae(t.orig,Y,e.html);if(t.orig=e.html,Y===ie)return;r.transact(()=>{for(const g of ce(Y,ie))g.deleteCount>0&&F.delete(c.index+g.index,g.deleteCount),g.insertText&&F.insert(c.index+g.index,g.insertText)}),u.current.onStateChange?.("dirty"),clearTimeout(h),h=setTimeout(()=>{s.saveNow()},fe);return}const i=s.collab.doc,o=E(t.from,i),n=E(t.to,i);if(!o||!n||o.index>n.index)return;const y=s.collab.text,N=n.index-o.index;if(o.index===0&&n.index===y.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:y.length}),m.clear(),p=!1,v(c=>c+1);return}const V=y.toString().slice(o.index,n.index),se=ae(t.orig,V,e.html);t.orig=e.html,V!==se&&s.collab.applySplices(ce(V,se).map(c=>({...c,index:c.index+o.index})))},re=e=>{if(!C.current||e.source!==C.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||I.enqueue(()=>pe(t))},oe=()=>{S()};return s.collab.text.observe(oe),window.addEventListener("message",re),()=>{q?.current===ee&&(q.current=null),H=!1,I.close(),clearTimeout(xe),clearTimeout(he),clearTimeout(h),s.collab.text.unobserve(oe),setTimeout(()=>{window.removeEventListener("message",re),clearTimeout(h),s.destroy(),r?.destroy()},300)}},[f,x,Z]),R.jsxs(R.Fragment,{children:[K&&R.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),ue&&!de&&R.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",R.jsx("b",{children:"Edit source"}),"."]}),R.jsx("iframe",{ref:C,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:x},Z)]})}export{Ce as VisualEdit};
diff --git a/internal/webapp/static/assets/index-C9ixuBUD.js b/internal/webapp/static/assets/index-BtQZiOrJ.js
similarity index 98%
rename from internal/webapp/static/assets/index-C9ixuBUD.js
rename to internal/webapp/static/assets/index-BtQZiOrJ.js
index 35a83cf9..0bebdf36 100644
--- a/internal/webapp/static/assets/index-C9ixuBUD.js
+++ b/internal/webapp/static/assets/index-BtQZiOrJ.js
@@ -1,4 +1,4 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-vslxZvKp.js","assets/sharedfile-CNg6aQyd.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-ZWfN9slK.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DzwiNrvp.js","assets/sharedfile-ifG4O60o.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-Co88xBUl.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-vslxZvKp.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-ZWfN9slK.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DzwiNrvp.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-Co88xBUl.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
 `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
 `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
-`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),Nt=b.useRef(null),dn=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),sn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||sn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,sn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,rn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),an=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!an)return;const ie=an+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[an]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!sn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",cn("history",ze)),Nn("insights","Insights",cn("dashboard",ze)),Nn("gear","Settings",cn("settings",ze)),Nn("laptop","Connect a device",cn("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:sn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!sn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{sn||(Cp(),gS(f,n,M))},onFocus:()=>{sn||(Cp(),gS(f,n,M))},title:sn?"Stop editing":"Edit this file",onClick:async()=>{if(!sn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&dn.current===ie)){dn.current=ie;try{const Ee=$n(M,l?.id,L,r.full,!1),ze=window.location.pathname+window.location.search;let Qe=!0;try{Qe=await(ie?.()??Promise.resolve(!0))}catch{}if(!Qe||window.location.pathname+window.location.search!==ze)return;gt(Ee)}finally{dn.current===ie&&(dn.current=null)}}},children:[!sn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:sn?"Done":"Edit"})]}),sn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),an&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:rn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
+`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),Nt=b.useRef(null),dn=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),sn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||sn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,sn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,rn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),an=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!an)return;const ie=an+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[an]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!sn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",cn("history",ze)),Nn("insights","Insights",cn("dashboard",ze)),Nn("gear","Settings",cn("settings",ze)),Nn("laptop","Connect a device",cn("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:sn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!sn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{sn||(Cp(),gS(f,n,M))},onFocus:()=>{sn||(Cp(),gS(f,n,M))},title:sn?"Stop editing":"Edit this file",onClick:async()=>{if(!sn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&dn.current===ie)){dn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{dn.current===ie&&(dn.current=null)}}},children:[!sn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:sn?"Done":"Edit"})]}),sn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),an&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:rn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-CNg6aQyd.js b/internal/webapp/static/assets/sharedfile-ifG4O60o.js
similarity index 99%
rename from internal/webapp/static/assets/sharedfile-CNg6aQyd.js
rename to internal/webapp/static/assets/sharedfile-ifG4O60o.js
index 1cf25f65..1b393c0e 100644
--- a/internal/webapp/static/assets/sharedfile-CNg6aQyd.js
+++ b/internal/webapp/static/assets/sharedfile-ifG4O60o.js
@@ -1,4 +1,4 @@
-import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-C9ixuBUD.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-BtQZiOrJ.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
 `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[tn]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?cn(e,(n,s)=>Us(n,t[s])):!1;class st{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[tn](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Jr(t,this),t}expect(t){return Jr(t,this),t}}class tr extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ht()};class pc extends st{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends st{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends st{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends st{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):cn(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends st{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&cn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends st{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&cn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends st{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(st);class Tc extends st{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends st{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends st{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>en(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const en=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=en(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(en));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ht()},Jr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
 ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:en(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Pr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Pr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(en(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Pc=e=>{const t=Vc();for(let n=0;n(Bi(e,Pc(t)),e),lu=(e,t=[],n=[])=>Jc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Pi(e)),Wi.forEach(t=>t.print(e))},Ji=(...e)=>{console.warn(...Pi(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Ps{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>jr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return Ze(this.restDecoder)}readBuf(){return lc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(K(t)),this.clientDecoder=new Ln(K(t)),this.leftClockDecoder=new ks(K(t)),this.rightClockDecoder=new ks(K(t)),this.infoDecoder=new Vr(K(t),Ae),this.stringDecoder=new Rl(K(t)),this.parentInfoDecoder=new Vr(K(t),Ae),this.typeRefDecoder=new Ln(K(t)),this.lenDecoder=new Ln(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ze(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ze(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,h=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(u,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)h(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),h=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,h.update])}}else l.pendingStructs=h;const u=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);u&&d?l.pendingDs=Fn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===hn)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new hn),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ht()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ht();l>=0?h=c._length:h=0}return Ca(c,h,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!an(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ht()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Jn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Js(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{so(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new hn;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!an(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Ps{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,I=b-S;I>0&&nn(f,w,S,I)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else u.push(new Ra(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ji("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,hn),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Jt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),h=Ms(c);return Ne(o,h),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Jt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const h=or(l);return Ne(i,h),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let h=i.curr;h!==null;h=i.next())Jt(l,t(h),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,hn),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return an(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Ji("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return rn(e,(s,r)=>{n.push(t(s,r,e))}),n},Pa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Z();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&sn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&sn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new un(s);break;case he:l=new fn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Z(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){rn(this,t)}[Symbol.iterator](){return Pa(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Wt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&sn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
 `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},Jl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})()
 BearDrive
 
-  
+  
   
   
   
diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js
index e8cc6669..4ce28bc3 100644
--- a/internal/webapp/static/inline-edit.js
+++ b/internal/webapp/static/inline-edit.js
@@ -1,21 +1,21 @@
-(function(){"use strict";var Or=Object.defineProperty,ll=(n,e)=>{let t={};for(var r in n)Or(t,r,{get:n[r],enumerable:!0});return Or(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Nr(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ar(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?zt(t+1,s):zt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class dt extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Rr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Ir(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Ir(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Ir(s.content,e-i-1,t-i-1)))}function Rr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Rr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function al(n,e,t){if(t.openStart>n.depth)throw new dt("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new dt("Inconsistent open depths");return vr(n,e,t,0)}function vr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function ht(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Sn(n,e,i+1),o=r.depth>i&&Sn(t,r,i+1),l=[];return ht(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Pr(s,o),Pe(Be(s,Br(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,Lt(n,e,i+1)),l),ht(e,t,i,l),o&&Pe(Be(o,Lt(t,r,i+1)),l)),ht(r,null,i,l),new b(l)}function Lt(n,e,t){let r=[];if(ht(null,n,t,r),n.depth>t){let i=Sn(n,e,t+1);Pe(Be(i,Lt(n,e,t+1)),r)}return ht(e,null,t,r),new b(r)}function cl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class pt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Vt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new pt(t,r,s)}static resolveCached(e,t){let r=zr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Fr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class $t extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Fr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new $t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new $t(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Fr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new hl(e,t);if(r.next==null)return Fe.empty;let i=Lr(r);r.next&&r.err("Unexpected trailing text");let s=xl(kl(i));return Sl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
-`)}}Fe.empty=new Fe(!0);class hl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Lr(n){let e=[];do e.push(pl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function pl(n){let e=[];do e.push(ml(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function ml(n){let e=bl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=gl(n,e);else break;return e}function Vr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function gl(n,e){let t=Vr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Vr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function yl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function bl(n){if(n.eat("(")){let e=Lr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=yl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function kl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Jr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new nl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Ml(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Cl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ml(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Wt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=qr(e,i.attrs),this.excluded=null;let s=jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Jr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Wt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class _r{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Kr.compile(this.spec.nodes,this),this.marks=Wt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Ur(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Ur(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Kr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new $t(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Ur(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function wl(n){return n.tag!=null}function Tl(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(wl(i))this.tags.push(i);else if(Tl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Qr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Qr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=Zr(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=Zr(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Gr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Ol={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Yr={ol:!0,ul:!0},mt=1,Mn=2,gt=4;function Xr(n,e,t){return e!=null?(e?mt:0)|(e==="full"?Mn:0):n&&n.whitespace=="pre"?mt|Mn:t&~gt}class jt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o>?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&mt)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Gr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Qr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Xr(null,t.preserveWhitespace,0)|(r?gt:0);i?s=new jt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new jt(null,null,E.none,!0,null,o):s=new jt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Mn?"full":this.localPreserveWS||(i.options&mt)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
-`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ei(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new jt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=mt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Nl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Yr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function El(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function Zr(n){let e={};for(let t in n)e[t]=n[t];return e}function ei(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Ht(Jt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Ht(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ti(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ti(e.marks)}}function ti(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Jt(n){return n.document||window.document}const ni=new WeakMap;function Dl(n){let e=ni.get(n);return e===void 0&&ni.set(n,e=Al(n)),e}function Al(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Ht(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ri=65535,ii=Math.pow(2,16);function Il(n,e){return n+e*ii}function si(n){return n&ri}function Rl(n){return(n-(n&ri))/ii}const oi=1,li=2,qt=4,ai=8;class Cn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ai)>0}get deletedBefore(){return(this.delInfo&(oi|qt))>0}get deletedAfter(){return(this.delInfo&(li|qt))>0}get deletedAcross(){return(this.delInfo&qt)>0}}class Y{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&Y.empty)return Y.empty}recover(e){let t=0,r=si(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Il(l/3,e-a),m=e==a?li:e==u?oi:qt;return(t<0?e!=a:e!=u)&&(m|=ai),new Cn(h,m,p)}i+=f-c}return r?e+i:new Cn(e+i,0,null)}touches(e,t){let r=0,i=si(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new yt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Tn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function On(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function vl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Pl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Wt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function Nn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Bl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function Ze(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function $l(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Wl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&di(n,o,l,s),Nn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&ui(n,o,l,s),!1}})}function ui(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
-`))}})}function Wl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Jl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return hi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Hl(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&hi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function ql(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);di(n,f.node(),f.before(),l)}o.inlineContent&&Nn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);ui(n,f.node(),f.before(),n.steps.length)}return n}function Kl(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function _t(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return pi(i,s,r)?new R(e,t,r):new Ul(i,s,r).fit()}function pi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Ul{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=mi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return yi(e,-1)<=t?!1:(this.unplaced.size>1&&yi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=mi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(bt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(bt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(gi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=kt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=En(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=kt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=kt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=kt(this.placed,this.frontier.length,t))}}function bt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(bt(n.firstChild.content,e-1,t)))}function kt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(kt(n.lastChild.content,e-1,t)))}function mi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,gi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function En(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Gl(t,s.content,o)?l:null}function Gl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Yl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function bi(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Ql(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Kl(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function Zl(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=ki(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function ki(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class et extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return Y.empty}invert(e){return new et(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new et(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new et(t.pos,t.attr,t.value)}}W.jsonID("attr",et);class xt extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return Y.empty}invert(e){return new xt(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new xt(t.attr,t.value)}}W.jsonID("docAttr",xt);let tt=class extends Error{};tt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},tt.prototype=Object.create(Error.prototype),tt.prototype.constructor=tt,tt.prototype.name="TransformError";class xi{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new yt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new tt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=_t(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Xl(this,e,t,r),this}replaceRangeWith(e,t,r){return Ql(this,e,t,r),this}deleteRange(e,t){return Zl(this,e,t),this}lift(e,t){return zl(this,e,t),this}join(e,t=1){return ql(this,e,t),this}wrap(e,t){return Vl(this,e,t),this}setBlockType(e,t=e,r,i=null){return $l(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new et(e,t,r)),this}setDocAttribute(e,t){return this.step(new xt(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Jl(this,e,t,r),this}addMark(e,t,r){return vl(this,e,t,r),this}removeMark(e,t,r){return Pl(this,e,t,r),this}clearIncompatible(e,t,r){return Nn(this,e,t,r),this}}const Dn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ea(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?nt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):nt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return nt(e,e,0,0,1)||new U(e)}static atEnd(e){return nt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Dn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Dn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Dn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ea{constructor(e,t){this.$from=e,this.$to=t}}let Si=!1;function Mi(n){!Si&&!n.parent.inlineContent&&(Si=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Mi(e),Mi(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Ut(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=nt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ci(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const wi=1,Gt=2,Ti=4;class na extends xi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Gt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Gt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Gt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ti,this}get scrolledIntoView(){return(this.updated&Ti)>0}}function Oi(n,e){return!e||!n?n:n.bind(e)}class St{constructor(e,t,r){this.name=e,this.init=Oi(t.init,r),this.apply=Oi(t.apply,r)}}const ra=[new St("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new St("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new St("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new St("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class In{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ra.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new St(r.key,r.spec.state,r))})}}class rt{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new In(e.schema,e.plugins),s=new rt(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ni(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ni(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ni(e.props,this,this.props),this.key=e.key?e.key.key:Ei("plugin")}getState(e){return e[this.key]}}const Rn=Object.create(null);function Ei(n){return n in Rn?n+"$"+ ++Rn[n]:(Rn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ei(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Di=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ai(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ii=(n,e,t)=>{let r=Ai(n,t);if(!r)return!1;let i=vn(r);if(!i){let o=r.blockRange(),l=o&&Ze(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Wi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(it(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=_t(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},ia=(n,e,t)=>{let r=Ai(n,t);if(!r)return!1;let i=vn(r);return i?Ri(n,i,e):!1},sa=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=Pn(r);return i?Ri(n,i,e):!1};function Ri(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=_t(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function it(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const vi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=vn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function vn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Pi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Pi(n,t);if(!r)return!1;let i=Pn(r);if(!i)return!1;let s=i.nodeAfter;if(Wi(n,i,e,1))return!0;if(r.parent.content.size==0&&(it(s,"start")||x.isSelectable(s))){let o=_t(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=Kt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},la=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=Kt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},aa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&Ze(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Fi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
-`).scrollIntoView()),!0)};function Bn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Bn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Vi=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Bn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&Ze(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ca(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Bn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const fa=ca(),ua=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},da=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ha(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Wi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ha(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&Ze(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&it(s,"start",!0)&&it(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ji=ji(-1),Hi=ji(1);function pa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&ci(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function qi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Ki(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ma(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Vt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Sa(e,t,n,s):Ma(e,t,s):!0:!1}}function Sa(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ca(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},st=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Ln=null;const me=function(n,e,t){let r=Ln||(Ln=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},wa=function(){Ln=null},We=function(n,e,t,r){return t&&(Gi(n,e,t,r,-1)||Gi(n,e,t,r,1))},Ta=/^(img|br|input|textarea|hr)$/i;function Gi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:X(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Mt(n)||Ta.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?X(n):0}else return!1}}function X(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Oa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=X(n)}else if(n.parentNode&&!Mt(n))e=L(n),n=n.parentNode;else return null}}function Na(n,e){for(;;){if(n.nodeType==3&&e2),Z=ot||(ce?/Mac/.test(ce.platform):!1),Zi=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),Ct=!!Yi&&"webkitFontSmoothing"in Yi.documentElement.style,Ia=Ct?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Ra(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function va(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function es(n,e,t){if(!Jn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=st(o);continue}let l=o,a=l==s.body,c=a?Ra(s):va(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:st(o)}}function Pa(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ts(n.dom)}}function ts(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=st(r));return e}function Ba({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ns(t,r==0?0:r-e)}function ns(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Fa(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:rs(t,i)}function Fa(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function jn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function La(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function $a(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function is(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Ct&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=$a(n,r,i,e))}l==null&&(l=Va(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Jn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,wt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Hn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==X(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,X(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return wt(we(c,1),!1)}if(s==null&&i=0)}function wt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Hn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ls(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ja(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return ls(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ss(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ha=/[\u0590-\u08ac]/;function qa(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ha.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:ls(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let as=null,cs=null,fs=!1;function Ka(n,e,t){return as==e&&cs==t?fs:(as=e,cs=t,fs=t=="up"||t=="down"?Ja(n,e,t):qa(n,e,t))}const ee=0,us=1,Je=2,se=3;class Tt{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=ee,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ps){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ds&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:us,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:us;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==ee&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class _a extends Tt{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Tt{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=ee){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Kn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=ys(f,r,t),c?a=new Ua(e,t,r,i,f,u||null,d,c):t.isText?new Xt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==ee&&e.eq(this.node)&&Qt(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Ya(this,o&&o.node,e);Za(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),ms(this.contentDOM,this.children,e),ot&&ec(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=tc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new _a(this,s,t,i);e.input.compositionNodes.push(o),this.children=Kn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=ee}updateOuterDeco(e){if(Qt(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=gs(this.dom,this.nodeDOM,qn(this.outerDeco,this.node,t),qn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function hs(n,e,t,r,i){ys(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Xt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=ee&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=ee||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=ee,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Xt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ps extends Tt{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==ee&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ua extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function ms(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Qa(n,e){return n.type.side-e.type.side}function Za(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ec(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function tc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Kn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function _n(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Yt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Ea(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!ks(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function rc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function Cs(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(ws(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else ws(n)}function ws(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Gn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Ts(n){return n.editable&&!n.hasFocus()?!1:Os(n)}function Os(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function ic(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Yn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Ns(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Yn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(Z&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):Ct?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Yn(n.state,e);return i?Ne(n,i):!1}}}function Zt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Nt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function at(n,e){return e<0?sc(n):oc(n)}function sc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Q&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Nt(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Es(t))break;{let l=t.previousSibling;for(;l&&Nt(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=Zt(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Xn(n,t,r):i&&Xn(n,i,s)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=Zt(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function Ds(n,e){let t=n.state.doc.resolve(e);if(!(V||Zi)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function As(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||Z&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Yn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Is(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Rs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function cc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Rs(n,r,"true"),setTimeout(()=>Rs(n,r,"false"),20)}return!1}function fc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function uc(n,e){let t=e.keyCode,r=fc(e);if(t==8||Z&&t==72&&r=="c")return Is(n,-1)||at(n,-1);if(t==46&&!e.shiftKey||Z&&t==68&&r=="c")return Is(n,1)||at(n,1);if(t==13||t==27)return!0;if(t==37||Z&&t==66&&r=="c"){let i=t==37?Ds(n,n.state.selection.from)=="ltr"?-1:1:-1;return Ns(n,i,r)||at(n,i)}else if(t==39||Z&&t==70&&r=="c"){let i=t==39?Ds(n,n.state.selection.from)=="ltr"?1:-1:1;return Ns(n,i,r)||at(n,i)}else{if(t==38||Z&&t==80&&r=="c")return As(n,-1,r)||at(n,-1);if(t==40||Z&&t==78&&r=="c")return cc(n)||As(n,1,r)||at(n,1);if(r==(Z?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Qn(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=Vs(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ls[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
+(function(){"use strict";var Nr=Object.defineProperty,al=(n,e)=>{let t={};for(var r in n)Nr(t,r,{get:n[r],enumerable:!0});return Nr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Er(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ir(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Ft(t+1,s):Ft(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=vr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Rr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Rr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Rr(s.content,e-i-1,t-i-1)))}function vr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=vr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function cl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Pr(n,e,t,0)}function Pr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Mn(n,e,i+1),o=r.depth>i&&Mn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Br(s,o),Pe(Be(s,zr(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,Vt(n,e,i+1)),l),pt(e,t,i,l),o&&Pe(Be(o,Vt(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function Vt(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Mn(n,e,t+1);Pe(Be(i,Vt(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function fl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new $t(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Fr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Lr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class Wt extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Lr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Wt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Wt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Lr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new pl(e,t);if(r.next==null)return Fe.empty;let i=Vr(r);r.next&&r.err("Unexpected trailing text");let s=Sl(xl(i));return Ml(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
+`)}}Fe.empty=new Fe(!0);class pl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Vr(n){let e=[];do e.push(ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ml(n){let e=[];do e.push(gl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function gl(n){let e=kl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=yl(n,e);else break;return e}function $r(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function yl(n,e){let t=$r(n),r=t;return n.eat(",")&&(n.next!="}"?r=$r(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function bl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function kl(n){if(n.eat("(")){let e=Vr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=bl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function xl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Hr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new rl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Cl(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class wl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Cl(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Kr(e,i.attrs),this.excluded=null;let s=Jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Hr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Ur{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=_r.compile(this.spec.nodes,this),this.marks=jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Gr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Gr(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _r){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Wt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Gr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Tl(n){return n.tag!=null}function Ol(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Tl(i))this.tags.push(i);else if(Ol(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Zr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Zr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ei(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ei(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Yr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Nl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Xr={ol:!0,ul:!0},gt=1,Cn=2,yt=4;function Qr(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Cn:0):n&&n.whitespace=="pre"?gt|Cn:t&~yt}class Jt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Yr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Zr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Qr(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new Jt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Jt(null,null,E.none,!0,null,o):s=new Jt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Cn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
+`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ti(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Jt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function El(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Xr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Dl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ei(n){let e={};for(let t in n)e[t]=n[t];return e}function ti(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&qt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:qt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ni(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ni(e.marks)}}function ni(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const ri=new WeakMap;function Al(n){let e=ri.get(n);return e===void 0&&ri.set(n,e=Il(n)),e}function Il(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=qt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ii=65535,si=Math.pow(2,16);function Rl(n,e){return n+e*si}function oi(n){return n&ii}function vl(n){return(n-(n&ii))/si}const li=1,ai=2,Kt=4,ci=8;class wn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ci)>0}get deletedBefore(){return(this.delInfo&(li|Kt))>0}get deletedAfter(){return(this.delInfo&(ai|Kt))>0}get deletedAcross(){return(this.delInfo&Kt)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=oi(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Rl(l/3,e-a),m=e==a?ai:e==u?li:Kt;return(t<0?e!=a:e!=u)&&(m|=ci),new wn(h,m,p)}i+=f-c}return r?e+i:new wn(e+i,0,null)}touches(e,t){let r=0,i=oi(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(On(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Nn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Pl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Bl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function En(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function zl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function et(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Wl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&jl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&hi(n,o,l,s),En(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&di(n,o,l,s),!1}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function hi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
+`))}})}function jl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Hl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return pi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&pi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Kl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);hi(n,f.node(),f.before(),l)}o.inlineContent&&En(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);di(n,f.node(),f.before(),n.steps.length)}return n}function _l(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Ut(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return mi(i,s,r)?new R(e,t,r):new Gl(i,s,r).fit()}function mi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Gl{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=gi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return bi(e,-1)<=t?!1:(this.unplaced.size>1&&bi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=gi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(yi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=Dn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function gi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,yi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function Dn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Yl(t,s.content,o)?l:null}function Yl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Xl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function ki(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Zl(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=_l(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ea(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=xi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function xi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class tt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new tt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new tt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new tt(t.pos,t.attr,t.value)}}W.jsonID("attr",tt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let nt=class extends Error{};nt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},nt.prototype=Object.create(Error.prototype),nt.prototype.constructor=nt,nt.prototype.name="TransformError";class Si{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new nt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Ut(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Ql(this,e,t,r),this}replaceRangeWith(e,t,r){return Zl(this,e,t,r),this}deleteRange(e,t){return ea(this,e,t),this}lift(e,t){return Fl(this,e,t),this}join(e,t=1){return Kl(this,e,t),this}wrap(e,t){return $l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Wl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new tt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Hl(this,e,t,r),this}addMark(e,t,r){return Pl(this,e,t,r),this}removeMark(e,t,r){return Bl(this,e,t,r),this}clearIncompatible(e,t,r){return En(this,e,t,r),this}}const An=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ta(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?rt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):rt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return rt(e,e,0,0,1)||new U(e)}static atEnd(e){return rt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=An[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in An)throw new RangeError("Duplicate use of selection JSON ID "+e);return An[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ta{constructor(e,t){this.$from=e,this.$to=t}}let Mi=!1;function Ci(n){!Mi&&!n.parent.inlineContent&&(Mi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ci(e),Ci(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Gt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=rt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function wi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ti=1,Yt=2,Oi=4;class ra extends Si{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Yt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Yt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Yt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Oi,this}get scrolledIntoView(){return(this.updated&Oi)>0}}function Ni(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ni(t.init,r),this.apply=Ni(t.apply,r)}}const ia=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Rn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ia.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class it{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Rn(e.schema,e.plugins),s=new it(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ei(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ei(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ei(e.props,this,this.props),this.key=e.key?e.key.key:Di("plugin")}getState(e){return e[this.key]}}const vn=Object.create(null);function Di(n){return n in vn?n+"$"+ ++vn[n]:(vn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Di(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ai=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ii(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ri=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Pn(r);if(!i){let o=r.blockRange(),l=o&&et(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(ji(n,i,e,-1))return!0;if(r.parent.content.size==0&&(st(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Ut(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},sa=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Pn(r);return i?vi(n,i,e):!1},oa=(n,e,t)=>{let r=Bi(n,t);if(!r)return!1;let i=Bn(r);return i?vi(n,i,e):!1};function vi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Ut(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function st(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Pi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Pn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Pn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Bi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Bi(n,t);if(!r)return!1;let i=Bn(r);if(!i)return!1;let s=i.nodeAfter;if(ji(n,i,e,1))return!0;if(r.parent.content.size==0&&(st(s,"start")||x.isSelectable(s))){let o=Ut(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=_t(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},aa=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=_t(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ca=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&et(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Li=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
+`).scrollIntoView()),!0)};function zn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=zn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},$i=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=zn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&et(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function fa(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=zn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ua=fa(),da=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ha=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function pa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function ji(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&pa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&et(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&st(s,"start",!0)&&st(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Hi=Ji(-1),qi=Ji(1);function ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&fi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ki(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function _i(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ga(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new $t(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ma(e,t,n,s):Ca(e,t,s):!0:!1}}function Ma(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function wa(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},ot=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Vn=null;const me=function(n,e,t){let r=Vn||(Vn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ta=function(){Vn=null},We=function(n,e,t,r){return t&&(Yi(n,e,t,r,-1)||Yi(n,e,t,r,1))},Oa=/^(img|br|input|textarea|hr)$/i;function Yi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Oa.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Na(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ea(n,e){for(;;){if(n.nodeType==3&&e2),ee=lt||(ce?/Mac/.test(ce.platform):!1),es=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),wt=!!Xi&&"webkitFontSmoothing"in Xi.documentElement.style,Ra=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function va(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function Pa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function ts(n,e,t){if(!Hn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=ot(o);continue}let l=o,a=l==s.body,c=a?va(s):Pa(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:ot(o)}}function Ba(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ns(n.dom)}}function ns(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=ot(r));return e}function za({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;rs(t,r==0?0:r-e)}function rs(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?La(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:is(t,i)}function La(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Jn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Va(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Wa(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function ss(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Wa(n,r,i,e))}l==null&&(l=$a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Hn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return qn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(we(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function qn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function as(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ha(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return as(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ls(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const qa=/[\u0590-\u08ac]/;function Ka(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:as(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let cs=null,fs=null,us=!1;function _a(n,e,t){return cs==e&&fs==t?us:(cs=e,fs=t,us=t=="up"||t=="down"?Ha(n,e,t):Ka(n,e,t))}const te=0,ds=1,Je=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ms){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof hs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:ds,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:ds;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Ua extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=_n(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=bs(f,r,t),c?a=new Ga(e,t,r,i,f,u||null,d,c):t.isText?new Qt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&Zt(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Xa(this,o&&o.node,e);ec(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),gs(this.contentDOM,this.children,e),lt&&tc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=nc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Ua(this,s,t,i);e.input.compositionNodes.push(o),this.children=_n(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(Zt(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ys(this.dom,this.nodeDOM,Kn(this.outerDeco,this.node,t),Kn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ps(n,e,t,r,i){bs(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Qt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Qt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ms extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ga extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function gs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Za(n,e){return n.type.side-e.type.side}function ec(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function tc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function nc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function _n(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Un(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Xt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Da(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!xs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function ic(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function ws(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ts(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ts(n)}function Ts(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Yn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Os(n){return n.editable&&!n.hasFocus()?!1:Ns(n)}function Ns(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function sc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Xn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Es(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Xn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Xn(n.state,e);return i?Ne(n,i):!1}}}function en(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ct(n,e){return e<0?oc(n):lc(n)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Ds(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=en(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Qn(n,t,r):i&&Qn(n,i,s)}function lc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=en(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function As(n,e){let t=n.state.doc.resolve(e);if(!(V||es)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Is(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Xn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Rs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function vs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function fc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;vs(n,r,"true"),setTimeout(()=>vs(n,r,"false"),20)}return!1}function uc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function dc(n,e){let t=e.keyCode,r=uc(e);if(t==8||ee&&t==72&&r=="c")return Rs(n,-1)||ct(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Rs(n,1)||ct(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?As(n,n.state.selection.from)=="ltr"?-1:1:-1;return Es(n,i,r)||ct(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?As(n,n.state.selection.from)=="ltr"?1:-1:1;return Es(n,i,r)||ct(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Is(n,-1,r)||ct(n,-1);if(t==40||ee&&t==78&&r=="c")return fc(n)||Is(n,1,r)||ct(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Zn(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=$s(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Vs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
 
-`);return{dom:a,text:d,slice:e}}function vs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,`
-`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=mc(t),Ct&&gc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!dc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=yc(Fs(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(hc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const dc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function hc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Bs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=zs(o[o.length-1],s.length));let f=Ps(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Ps(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Bs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Fs(n,e,t){return et})}return Et.createHTML(n)}function mc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Vs(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ls[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=pc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},bc={touchstart:!0,touchmove:!0};class kc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function xc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Mc(n,r)&&!tr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},bc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),er(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Sc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function er(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>tr(n,r))})}function tr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Mc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Cc(n,e){!tr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Js(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),ot&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||uc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Js(n)||!t.charCode||t.ctrlKey&&!t.altKey||Z&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function Dt(n){return{left:n.clientX,top:n.clientY}}function wc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function nr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function At(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Tc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(At(n,new x(t)),!0):!1}function Oc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(At(n,x.create(n.state.doc,i)),!0):!1}function Nc(n,e,t,r,i){return nr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Oc(n,t):Tc(n,t))}function Ec(n,e,t,r){return nr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Dc(n,e,t,r){return nr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ac(n,t,r)}function Ac(n,e,t){if(t.button!=0)return!1;let r=$s(n,e,!0),i=n.state.doc;return r?(At(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new Rc(n,r)),!0):!1}function $s(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function rr(n){return en(n)}const Ws=Z?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=rr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&wc(t,n.input.lastClick)&&!t[Ws]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(Dt(t));o&&(s=="singleClick"?n.input.mouseDown=new Ic(n,o,t,!!r):(s=="doubleClick"?Ec:Dc)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Ic extends js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Ws],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Q&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(Dt(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Nc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(At(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Rc extends js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(Dt(e)),r=t&&$s(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),rr(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>rr(n);function Js(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const vc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&Zi&&Pc(n)))n.markCursor=n.state.storedMarks||t.marks(),en(n,!0),n.markCursor=null;else if(en(n,!e.selection.empty),Q&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Hs(n,vc)};function Pc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Hs(n,20))};function Hs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>en(n),e))}function qs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Bc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Oa(e.focusNode,e.focusOffset),r=Na(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function en(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),qs(n),e||n.docView&&n.docView.dirty){let t=_n(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function zc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const It=G&&Ce<15||ot&&Ia<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=It?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Qn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):zc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Fc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Lc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Rt(n,r.value,null,i,e):Rt(n,r.textContent,r.innerHTML,i,e)},50)}function Rt(n,e,t,r,i){let s=vs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Fc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Ks(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=It?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Rt(n,Ks(r),r.getData("text/html"),i,t)?t.preventDefault():Lc(n,t)};class _s{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Vc=Z?"altKey":"ctrlKey";function Us(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Vc]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(Dt(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Qn(n,l);(!t.dataTransfer.files.length||!V||Qi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(It?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",It||t.dataTransfer.setData("text/plain",c),n.dragging=new _s(f,Us(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{$c(n,e,n.dragging)}finally{n.dragging=null}};function $c(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(Dt(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=vs(n,Ks(e.dataTransfer),It?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Us(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?_l(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Gn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function vt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class tn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof tn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&vt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Ys(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=jc(l,n,e,t,i,s,o),f=nn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Ys(n,l,a+t);if(c){s=!0;let f=nn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Gs(s?Xs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function or(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Jc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Hc=G&&Ce<=11;class qc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Kc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new qc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Hc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Jc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Ts(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=st(s))t.add(s);for(let s=e.anchorNode;s;s=st(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Ts(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Q&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Gc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),_c(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Yc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Qc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Qc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Zc=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function ef(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=_n(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Xe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Xc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!Zc.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=no(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((ot&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&nf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=no(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=tf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function no(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Gn(n,e.resolve(t.anchor),e.resolve(t.head))}function tf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||lr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function rf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class ro{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new kc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(ao),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=oo(this),so(this),this.nodeViews=lo(this),this.docView=hs(this.state.doc,io(this),or(this),this.dom,this),this.domObserver=new Kc(this,(r,i,s,o)=>ef(this,r,i,s,o)),this.domObserver.start(),xc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&er(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(ao),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(qs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=lo(this);of(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&er(this),this.editable=oo(this),so(this);let a=or(this),c=io(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Pa(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&sf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Bc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=hs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ic(this)&&p.delaySelUpdate())?be(this,h):(Cs(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ba(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&es(this,t.getBoundingClientRect(),e)}else es(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Wa(this,e)}coordsAtPos(e,t=1){return ss(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ka(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Qn(this,e)}destroy(){this.docView&&(Sc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],or(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,wa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Cc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Da(this.dom.ownerDocument)==this.dom&&Uc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}ro.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function io(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function so(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function oo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function sf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function lo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function of(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function ao(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},rn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},lf=typeof navigator<"u"&&/Mac/.test(navigator.platform),af=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),rn[$]=String.fromCharCode($);for(var ar in Ae)rn.hasOwnProperty(ar)||(rn[ar]=Ae[ar]);function cf(n){var e=lf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||af&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?rn:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const ff=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),uf=typeof navigator<"u"&&/Win/.test(navigator.platform);function df(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=rl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:fo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const gf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),yf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),bf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=Ze(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},kf=n=>e=>n(e),xf=()=>({state:n,dispatch:e})=>Vi(n,e),Sf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Mf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Cf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},wf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Tf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,uo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:uo(n,t,"left"),to:uo(e,t,"right")}),Nf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Of(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Ef=()=>({commands:n})=>n.keyboardShortcut("Enter"),Df=()=>({state:n,dispatch:e})=>Li(n,e);function Af(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function sn(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Af(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function ho(n,e,t={}){return n.find(r=>r.type===e&&sn(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function po(n,e,t={}){return!!ho(n,e,t)}function fr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!ho([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&po([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=fr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},Rf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(on()||go())&&r.dom.focus(),Pf()&&!on()&&!go()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!mo(t.state.selection))return o(),!0;const l=vf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},zf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Ff=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),yo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&yo(r)}return n};function ln(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return yo(t)}function bo(n){return typeof n?.nodesBetween=="function"}function ft(n,e,t){if(bo(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ft("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new _r({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(ln(n),t.parseOptions):de.fromSchema(a).parse(ln(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(ln(n),t.parseOptions).content:s.parse(ln(n),t.parseOptions)}return ft("",e,t)}function ko(n){return!("type"in n)}function xo(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Lf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ft(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=ko(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):bo(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&xo(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function So(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=So(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ft(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&xo(e,e.steps.length-1,-1)),!0):!1},$f=()=>({state:n,dispatch:e})=>oa(n,e),Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>Ii(n,e),Jf=()=>({state:n,dispatch:e})=>Bi(n,e),Hf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Kt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e})=>ia(n,e),_f=()=>({state:n,dispatch:e})=>sa(n,e);function Mo(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Uf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Uf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function ur(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>sn(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Yf=(n,e={})=>({state:t,dispatch:r})=>ur(t,H(n,t.schema),e)?aa(t,r):!1,Xf=()=>({state:n,dispatch:e})=>$i(n,e),Qf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return xa(r)(e,t)},Zf=()=>({state:n,dispatch:e})=>Fi(n,e);function Co(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function wo(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const eu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Co(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,wo(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(wo(d.attrs,e))))})})}),a},tu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),nu=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},ru=()=>({state:n,dispatch:e})=>vi(n,e),iu=()=>({state:n,dispatch:e})=>zi(n,e),su=()=>({state:n,dispatch:e})=>ua(n,e),ou=()=>({state:n,dispatch:e})=>Hi(n,e),lu=()=>({state:n,dispatch:e})=>Ji(n,e);function au(n,e,t={},r={}){return ft(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const cu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=au(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=ko(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function fu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function uu(n,e){const t=new xi(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function du(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function dr(n){return e=>du(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function To(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...To(t())]:e}).flat(10)}function hu(n){return typeof n=="function"}function D(n,e=void 0,...t){return hu(n)?e?n.bind(e)(...t):n(...t):n}function pu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function an(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function mu(n){const e=[],{nodeExtensions:t,markExtensions:r}=an(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function gu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Oo(n){const e=[],t=gu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Oo(r[i]),...Oo(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function No(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>cn(t,r),{})}function yu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Eo(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):yu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Do(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&pu(t)?!1:t!=null))}function Ao(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function bu(n,e){var t;const r=mu(n),{nodeExtensions:i,markExtensions:s}=an(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Do({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Ao))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Eo(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:No(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Do({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Ao))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Eo(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:No(m,f)})),[c.name,d]}));return new _r({topNode:o,nodes:l,marks:a})}function ku(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function xu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Mu(n,e){return bu(Su(n),e)}function Cu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
+`);return{dom:a,text:d,slice:e}}function Ps(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,`
+`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=gc(t),wt&&yc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!hc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=bc(Ls(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(pc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const hc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function pc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&zs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Fs(o[o.length-1],s.length));let f=Bs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Bs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function zs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ls(n,e,t){return et})}return Dt.createHTML(n)}function gc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=$s(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Vs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},kc={touchstart:!0,touchmove:!0};class xc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Sc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Cc(n,r)&&!nr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},kc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),tr(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Mc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function tr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>nr(n,r))})}function nr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Cc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function wc(n,e){!nr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Hs(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),lt&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||dc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Hs(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Tc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function rr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Oc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Nc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ec(n,e,t,r,i){return rr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Nc(n,t):Oc(n,t))}function Dc(n,e,t,r){return rr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Ac(n,e,t,r){return rr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ic(n,t,r)}function Ic(n,e,t){if(t.button!=0)return!1;let r=Ws(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new vc(n,r)),!0):!1}function Ws(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function ir(n){return tn(n)}const js=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=ir(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Tc(t,n.input.lastClick)&&!t[js]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Rc(n,o,t,!!r):(s=="doubleClick"?Dc:Ac)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class Js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Rc extends Js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[js],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Ec(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class vc extends Js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Ws(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),ir(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>ir(n);function Hs(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Pc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&es&&Bc(n)))n.markCursor=n.state.storedMarks||t.marks(),tn(n,!0),n.markCursor=null;else if(tn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}qs(n,Pc)};function Bc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,qs(n,20))};function qs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>tn(n),e))}function Ks(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function zc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Na(e.focusNode,e.focusOffset),r=Ea(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function tn(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Ks(n),e||n.docView&&n.docView.dirty){let t=Un(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Fc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&Ce<15||lt&&Ra<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Zn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Fc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Lc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Vc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Ps(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Lc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function _s(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,_s(r),r.getData("text/html"),i,t)?t.preventDefault():Vc(n,t)};class Us{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const $c=ee?"altKey":"ctrlKey";function Gs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[$c]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Zn(n,l);(!t.dataTransfer.files.length||!V||Zi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Us(f,Gs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Wc(n,e,n.dragging)}finally{n.dragging=null}};function Wc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Ps(n,_s(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Gs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Ul(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Yn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class nn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof nn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Xs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Jc(l,n,e,t,i,s,o),f=rn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Xs(n,l,a+t);if(c){s=!0;let f=rn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Ys(s?Qs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function lr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Hc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qc=G&&Ce<=11;class Kc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class _c{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Kc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Hc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Os(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=ot(s))t.add(s);for(let s=e.anchorNode;s;s=ot(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Os(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Yc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Uc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Xc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Zc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Zc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},ef=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function tf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Un(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Qe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Qc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!ef.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=ro(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((lt&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&rf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=ro(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=nf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function ro(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Yn(n,e.resolve(t.anchor),e.resolve(t.head))}function nf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||ar(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function sf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class io{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new xc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(co),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=lo(this),oo(this),this.nodeViews=ao(this),this.docView=ps(this.state.doc,so(this),lr(this),this.dom,this),this.domObserver=new _c(this,(r,i,s,o)=>tf(this,r,i,s,o)),this.domObserver.start(),Sc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&tr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(co),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Ks(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=ao(this);lf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&tr(this),this.editable=lo(this),oo(this);let a=lr(this),c=so(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Ba(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&of(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=zc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ps(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sc(this)&&p.delaySelUpdate())?be(this,h):(ws(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&za(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&ts(this,t.getBoundingClientRect(),e)}else ts(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ja(this,e)}coordsAtPos(e,t=1){return ls(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return _a(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Zn(this,e)}destroy(){this.docView&&(Mc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],lr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ta())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return wc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Aa(this.dom.ownerDocument)==this.dom&&Gc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}io.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function so(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function oo(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function lo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function of(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function ao(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function lf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function co(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},sn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},af=typeof navigator<"u"&&/Mac/.test(navigator.platform),cf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),sn[$]=String.fromCharCode($);for(var cr in Ae)sn.hasOwnProperty(cr)||(sn[cr]=Ae[cr]);function ff(n){var e=af&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||cf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?sn:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const uf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),df=typeof navigator<"u"&&/Win/.test(navigator.platform);function hf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=il.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:uo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const yf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),bf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),kf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=et(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},xf=n=>e=>n(e),Sf=()=>({state:n,dispatch:e})=>$i(n,e),Mf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Cf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const wf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Tf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Of=n=>n.content?/^text(\*|\+)/.test(n.content):!1,ho=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:ho(n,t,"left"),to:ho(e,t,"right")}),Ef=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Nf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Df=()=>({commands:n})=>n.keyboardShortcut("Enter"),Af=()=>({state:n,dispatch:e})=>Vi(n,e);function If(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function on(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:If(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function po(n,e,t={}){return n.find(r=>r.type===e&&on(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function mo(n,e,t={}){return!!po(n,e,t)}function ur(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!po([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&mo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=ur(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},vf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(ln()||yo())&&r.dom.focus(),Bf()&&!ln()&&!yo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!go(t.state.selection))return o(),!0;const l=Pf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Ff=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Lf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),bo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&bo(r)}return n};function an(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return bo(t)}function ko(n){return typeof n?.nodesBetween=="function"}function ut(n,e,t){if(ko(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ut("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Ur({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(an(n),t.parseOptions):de.fromSchema(a).parse(an(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(an(n),t.parseOptions).content:s.parse(an(n),t.parseOptions)}return ut("",e,t)}function xo(n){return!("type"in n)}function So(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Vf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=xo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):ko(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&So(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function Mo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=Mo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ut(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&So(e,e.steps.length-1,-1)),!0):!1},Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>aa(n,e),Jf=()=>({state:n,dispatch:e})=>Ri(n,e),Hf=()=>({state:n,dispatch:e})=>zi(n,e),qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=_t(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=_t(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},_f=()=>({state:n,dispatch:e})=>sa(n,e),Uf=()=>({state:n,dispatch:e})=>oa(n,e);function Co(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Gf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Gf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function dr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>on(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Xf=(n,e={})=>({state:t,dispatch:r})=>dr(t,H(n,t.schema),e)?ca(t,r):!1,Qf=()=>({state:n,dispatch:e})=>Wi(n,e),Zf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Sa(r)(e,t)},eu=()=>({state:n,dispatch:e})=>Li(n,e);function wo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function To(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const tu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,To(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(To(d.attrs,e))))})})}),a},nu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ru=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},iu=()=>({state:n,dispatch:e})=>Pi(n,e),su=()=>({state:n,dispatch:e})=>Fi(n,e),ou=()=>({state:n,dispatch:e})=>da(n,e),lu=()=>({state:n,dispatch:e})=>qi(n,e),au=()=>({state:n,dispatch:e})=>Hi(n,e);function cu(n,e,t={},r={}){return ut(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const fu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=cu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=xo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function uu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function du(n,e){const t=new Si(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function hu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function hr(n){return e=>hu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Oo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Oo(t())]:e}).flat(10)}function pu(n){return typeof n=="function"}function D(n,e=void 0,...t){return pu(n)?e?n.bind(e)(...t):n(...t):n}function mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function cn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function gu(n){const e=[],{nodeExtensions:t,markExtensions:r}=cn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function yu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function No(n){const e=[],t=yu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...No(r[i]),...No(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Eo(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>fn(t,r),{})}function bu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Do(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):bu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ao(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&mu(t)?!1:t!=null))}function Io(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function ku(n,e){var t;const r=gu(n),{nodeExtensions:i,markExtensions:s}=cn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Do(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Eo(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Do(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Eo(m,f)})),[c.name,d]}));return new Ur({topNode:o,nodes:l,marks:a})}function xu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Su(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Cu(n,e){return ku(Mu(n),e)}function wu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
 
-`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function wu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Tu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Ou(n){const e=Tu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Nu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Ou(r)}function Io(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=fr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function fn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Eu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>sn(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>sn(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function hr(n,e){const{nodeExtensions:t}=an(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Ro(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Ro(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Du(n,e,t){const{selection:r}=e;let i=null;if(mo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Au=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=fu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Du(r,t,a)},Iu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Ru=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>qi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>qi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Pu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Bu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},zu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Ca(r)(e,t)};function vo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Fu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=fn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&vo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:So(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&vo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Lu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...fn(u,f.type.name,f.attrs),...e},m={...fn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Po(n){return!n||n==="1"?null:n}function Bo(n,e){return Po(n)===Po(e)}const pr=(n,e)=>{const t=dr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!Bo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},mr=(n,e)=>{const t=dr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!Bo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Vu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const $u=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=dr(Qe=>hr(Qe.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&hr(N.type.name,u)?{node:N,pos:0}:null,Xe=_??v,Ld=!!_&&w.depth>=1&&w.depth-_.depth<=1,tl=!!v;if((Ld||tl)&&Xe){if(Xe.node.type===h)return ne&&tl?a().command(({tr:Qe,dispatch:bn})=>{const kn=Vu(Qe);return kn?(Qe.setSelection(kn),bn&&bn(Qe),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(hr(Xe.node.type.name,u)&&h.validContent(Xe.node.content))return a().command(()=>(s.setNodeMarkup(Xe.pos,h),!0)).command(()=>pr(s,h)).command(()=>mr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>pr(s,h)).command(()=>mr(s,h)).run():a().command(()=>{const Qe=f().wrapInList(h,r),bn=A.filter(kn=>d.includes(kn.type.name));return s.ensureMarks(bn),Qe?!0:c.clearNodes()}).wrapInList(h,r).command(()=>pr(s,h)).command(()=>mr(s,h)).run()},Wu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Eu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=ur(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Ju=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return ur(t,i,e)?r.lift(i):r.wrapIn(i,e)},Hu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},qu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Ku=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=fr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},_u=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Uu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Co(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Gu=new ie("__tiptap_decorations__"),Yu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Gu,{type:"force",name:n}),!0),Xu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return pa(i,e)(t,r)},Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ya(i,e)(t,r)};var Zu=ll({blur:()=>gf,clearContent:()=>yf,clearNodes:()=>bf,command:()=>kf,createParagraphNear:()=>xf,cut:()=>Sf,deleteCurrentNode:()=>Mf,deleteNode:()=>Cf,deleteRange:()=>wf,deleteSelection:()=>Nf,enter:()=>Ef,exitCode:()=>Df,extendMarkRange:()=>If,first:()=>Rf,focus:()=>Bf,forEach:()=>zf,insertContent:()=>Ff,insertContentAt:()=>Lf,insertDefaultBlock:()=>Vf,joinBackward:()=>jf,joinDown:()=>Wf,joinForward:()=>Jf,joinItemBackward:()=>Hf,joinItemForward:()=>qf,joinTextblockBackward:()=>Kf,joinTextblockForward:()=>_f,joinUp:()=>$f,keyboardShortcut:()=>Gf,lift:()=>Yf,liftEmptyBlock:()=>Xf,liftListItem:()=>Qf,newlineInCode:()=>Zf,resetAttributes:()=>eu,scrollIntoView:()=>tu,selectAll:()=>nu,selectNodeBackward:()=>ru,selectNodeForward:()=>iu,selectParentNode:()=>su,selectTextblockEnd:()=>ou,selectTextblockStart:()=>lu,setContent:()=>cu,setMark:()=>Au,setMeta:()=>Iu,setNode:()=>Ru,setNodeSelection:()=>vu,setTextDirection:()=>Pu,setTextSelection:()=>Bu,sinkListItem:()=>zu,splitBlock:()=>Fu,splitListItem:()=>Lu,toggleList:()=>$u,toggleMark:()=>Wu,toggleNode:()=>ju,toggleWrap:()=>Ju,undoInputRule:()=>Hu,unsetAllMarks:()=>qu,unsetMark:()=>Ku,unsetTextDirection:()=>_u,updateAttributes:()=>Uu,updateDecorations:()=>Yu,wrapIn:()=>Xu,wrapInList:()=>Qu});typeof process<"u"&&process.env.NODE_ENV;function ed(n){return Object.prototype.toString.call(n).slice(8,-1)}function un(n){return ed(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function zo(n,e){const t={...n};return un(n)&&un(e)&&Object.keys(e).forEach(r=>{un(e[r])&&un(n[r])?t[r]=zo(n[r],e[r]):t[r]=e[r]}),t}var td=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},gr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>zo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},dn=class il extends gr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new il(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},nd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class sl extends gr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=wu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Cu(r,{from:a.pos,to:c.pos},l)).join(o??`
+`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Tu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Ou(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Nu(n){const e=Ou(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Eu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Nu(r)}function Ro(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=ur(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function un(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Du(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>on(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>on(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function pr(n,e){const{nodeExtensions:t}=cn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function vo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(vo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Au(n,e,t){const{selection:r}=e;let i=null;if(go(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Iu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=uu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Au(r,t,a)},Ru=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),vu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ki(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ki(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Bu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},zu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},Fu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)};function Po(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Lu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=un(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&Po(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:Mo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Po(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Vu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...un(u,f.type.name,f.attrs),...e},m={...un(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Bo(n){return!n||n==="1"?null:n}function zo(n,e){return Bo(n)===Bo(e)}const mr=(n,e)=>{const t=hr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},gr=(n,e)=>{const t=hr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function $u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Wu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=hr(Ze=>pr(Ze.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&pr(N.type.name,u)?{node:N,pos:0}:null,Qe=_??v,Vd=!!_&&w.depth>=1&&w.depth-_.depth<=1,nl=!!v;if((Vd||nl)&&Qe){if(Qe.node.type===h)return ne&&nl?a().command(({tr:Ze,dispatch:kn})=>{const xn=$u(Ze);return xn?(Ze.setSelection(xn),kn&&kn(Ze),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(pr(Qe.node.type.name,u)&&h.validContent(Qe.node.content))return a().command(()=>(s.setNodeMarkup(Qe.pos,h),!0)).command(()=>mr(s,h)).command(()=>gr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>mr(s,h)).command(()=>gr(s,h)).run():a().command(()=>{const Ze=f().wrapInList(h,r),kn=A.filter(xn=>d.includes(xn.type.name));return s.ensureMarks(kn),Ze?!0:c.clearNodes()}).wrapInList(h,r).command(()=>mr(s,h)).command(()=>gr(s,h)).run()},ju=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Du(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=dr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Hu=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return dr(t,i,e)?r.lift(i):r.wrapIn(i,e)},qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Ku=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},_u=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=ur(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Uu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Gu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Yu=new ie("__tiptap_decorations__"),Xu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Yu,{type:"force",name:n}),!0),Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ma(i,e)(t,r)},Zu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)};var ed=al({blur:()=>yf,clearContent:()=>bf,clearNodes:()=>kf,command:()=>xf,createParagraphNear:()=>Sf,cut:()=>Mf,deleteCurrentNode:()=>Cf,deleteNode:()=>wf,deleteRange:()=>Tf,deleteSelection:()=>Ef,enter:()=>Df,exitCode:()=>Af,extendMarkRange:()=>Rf,first:()=>vf,focus:()=>zf,forEach:()=>Ff,insertContent:()=>Lf,insertContentAt:()=>Vf,insertDefaultBlock:()=>$f,joinBackward:()=>Jf,joinDown:()=>jf,joinForward:()=>Hf,joinItemBackward:()=>qf,joinItemForward:()=>Kf,joinTextblockBackward:()=>_f,joinTextblockForward:()=>Uf,joinUp:()=>Wf,keyboardShortcut:()=>Yf,lift:()=>Xf,liftEmptyBlock:()=>Qf,liftListItem:()=>Zf,newlineInCode:()=>eu,resetAttributes:()=>tu,scrollIntoView:()=>nu,selectAll:()=>ru,selectNodeBackward:()=>iu,selectNodeForward:()=>su,selectParentNode:()=>ou,selectTextblockEnd:()=>lu,selectTextblockStart:()=>au,setContent:()=>fu,setMark:()=>Iu,setMeta:()=>Ru,setNode:()=>vu,setNodeSelection:()=>Pu,setTextDirection:()=>Bu,setTextSelection:()=>zu,sinkListItem:()=>Fu,splitBlock:()=>Lu,splitListItem:()=>Vu,toggleList:()=>Wu,toggleMark:()=>ju,toggleNode:()=>Ju,toggleWrap:()=>Hu,undoInputRule:()=>qu,unsetAllMarks:()=>Ku,unsetMark:()=>_u,unsetTextDirection:()=>Uu,updateAttributes:()=>Gu,updateDecorations:()=>Xu,wrapIn:()=>Qu,wrapInList:()=>Zu});typeof process<"u"&&process.env.NODE_ENV;function td(n){return Object.prototype.toString.call(n).slice(8,-1)}function dn(n){return td(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Fo(n,e){const t={...n};return dn(n)&&dn(e)&&Object.keys(e).forEach(r=>{dn(e[r])&&dn(n[r])?t[r]=Fo(n[r],e[r]):t[r]=e[r]}),t}var nd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},yr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Fo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},hn=class sl extends yr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},rd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ol extends yr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Tu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>wu(r,{from:a.pos,to:c.pos},l)).join(o??`
 
-`)}}})]}}),fe.create({name:"commands",addCommands(){return{...Zu}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=uu(n.before,[n,...e]);Nu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const rd=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:rd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return on()||Mo()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Ro(t.doc))return;const f=t.tr,u=fo({state:t,transaction:f}),{commands:d}=new mf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=an(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Pt(n){return new td({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Io(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Fo=class ol extends gr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Io(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var id=Fo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
+`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ed}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=du(n.before,[n,...e]);Eu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const id=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:id,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return ln()||Co()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!vo(t.doc))return;const f=t.tr,u=uo({state:t,transaction:f}),{commands:d}=new gf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=cn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Ro(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Lo=class ll extends yr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ll(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new rd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Ro(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var sd=Lo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
 
-`):""}),sd=Fo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Lo=new WeakSet,Vo=new WeakSet;function Ue(n){const e=n;return Lo.add(e),e}function yr(n){return Array.isArray(n)&&Lo.has(n)}function $o(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Vo.has(e)&&!yr(e)?$o(e):[e])}function od(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!yr(i)&&!Vo.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(yr(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=$o(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const Wo=(n,e)=>od(n,e),ld=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,cd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var ud=dn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Wo("strong",{...cn(this.options.HTMLAttributes,n),children:Wo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Pt({find:ld,type:this.type}),Pt({find:cd,type:this.type})]},addPasteRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]}});const dd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,pd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var gd=dn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",cn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Pt({find:dd,type:this.type}),Pt({find:pd,type:this.type})]},addPasteRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]}});const yd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},bd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var kd=dn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",cn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Pt({find:yd,type:this.type})]},addPasteRules(){return[Bt({find:bd,type:this.type})]}}),hn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new jo(e):z.empty};var jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=hn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=hn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new jo([]);var xd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Sd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fCd&&(l=Md(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new yt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dSd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Md(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Cd=20;function wd(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Nd)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,pn(e)),n.undone,Jo(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,pn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Td(t,n.prevRanges)),c=o?br(n.prevRanges,t.mapping):Jo(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,pn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),br(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),br(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Td(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Jo(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function br(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Od(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Ko=qo(!1,!0),xr=qo(!0,!0),Ye="data-bd-src",Dd=dn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),mn=Mu([id.extend({content:"inline*"}),sd,ud,gd,kd,Dd]),Ad=de.fromSchema(mn),Id=Le.fromSchema(mn),Rd={preserveWhitespace:"full"};function _o(n){return Ad.parse(n,Rd)}function Uo(n){const e=document.createElement("div");return e.appendChild(Id.serializeFragment(n.content)),e.innerHTML}function vd(n){try{return Uo(_o(n))===n.innerHTML}catch{return!1}}function Go(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const gn=n=>parent.postMessage(n,"*"),Sr=new WeakMap;function Yo(n){let e=Sr.get(n);return e===void 0&&(e=vd(n),Sr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let te=null,ve=null,ut=null,Mr="";function Xo(){return te?Uo(te.state.doc):null}function Cr(){if(!ve||!ut)return;const n=Xo();n===null||n===Mr||(Mr=n,gn({type:"bd-edit:patch",start:ut.start,end:ut.end,html:n}))}function yn(){if(!te)return;Cr();const n=ve,e=Xo();te.destroy(),te=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Sr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,ut=null}function Pd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function Bd(n,e,t){if(ve===n)return;yn();const r=Go(n);if(!r)return;ve=n,ut=r,Mr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=rt.create({doc:_o(n),plugins:[Ed(),co({"Mod-b":Ki(mn.marks.bold),"Mod-i":Ki(mn.marks.italic),"Mod-z":Ko,"Mod-y":xr,"Shift-Mod-z":xr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(yn(),!0)}),co(ga)]});te=new ro({mount:n},{state:i,dispatchTransaction(s){te.updateState(te.state.apply(s)),s.docChanged&&Cr()}}),te.focus(),e!==void 0&&t!==void 0&&Pd(te,e,t)}function Qo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{const e=Qo(n.target);if(!e){yn();return}Yo(e)&&Bd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Qo(n.target);e&&Yo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(gn({type:"bd-edit:clobbered"}),te?.destroy(),te=null,ve=null,ut=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const Zo=document.createElement("style");Zo.textContent=`
+`):""}),od=Lo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Vo=new WeakSet,$o=new WeakSet;function Ue(n){const e=n;return Vo.add(e),e}function br(n){return Array.isArray(n)&&Vo.has(n)}function Wo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&$o.has(e)&&!br(e)?Wo(e):[e])}function ld(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!br(i)&&!$o.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(br(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=Wo(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const jo=(n,e)=>ld(n,e),ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,ud=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var dd=hn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return jo("strong",{...fn(this.options.HTMLAttributes,n),children:jo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]},addPasteRules(){return[zt({find:cd,type:this.type}),zt({find:ud,type:this.type})]}});const hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,pd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,gd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var yd=hn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",fn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},kd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var xd=hn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",fn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type})]}}),pn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Jo(e):z.empty};var Jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=pn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=pn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Jo([]);var Sd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Md=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fwd&&(l=Cd(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dMd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Cd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const wd=20;function Td(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Ed)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,mn(e)),n.undone,Ho(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,mn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Od(t,n.prevRanges)),c=o?kr(n.prevRanges,t.mapping):Ho(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,mn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),kr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),kr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Od(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ho(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function kr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Nd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const _o=Ko(!1,!0),Sr=Ko(!0,!0),Ye="data-bd-src",Ad=hn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),gn=Cu([sd.extend({content:"inline*"}),od,dd,yd,xd,Ad]),Id=de.fromSchema(gn),Rd=Le.fromSchema(gn),vd={preserveWhitespace:"full"};function Uo(n){return Id.parse(n,vd)}function Go(n){const e=document.createElement("div");return e.appendChild(Rd.serializeFragment(n.content)),e.innerHTML}function Pd(n){try{return Go(Uo(n))===n.innerHTML}catch{return!1}}function Yo(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const yn=n=>parent.postMessage(n,"*"),Mr=new WeakMap;function Xo(n){let e=Mr.get(n);return e===void 0&&(e=Pd(n),Mr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,ve=null,dt=null,Cr="",Xe=!1;function Qo(){return Y?Go(Y.state.doc):null}function wr(){if(!ve||!dt)return;const n=Qo();n===null||n===Cr||(Cr=n,yn({type:"bd-edit:patch",start:dt.start,end:dt.end,html:n}))}function bn(){if(!Y)return;wr();const n=ve,e=Qo();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Mr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,dt=null}function Bd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function zd(n,e,t){if(ve===n)return;bn();const r=Yo(n);if(!r)return;ve=n,dt=r,Cr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=it.create({doc:Uo(n),plugins:[Dd(),fo({"Mod-b":_i(gn.marks.bold),"Mod-i":_i(gn.marks.italic),"Mod-z":_o,"Mod-y":Sr,"Shift-Mod-z":Sr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(bn(),!0)}),fo(ya)]});Y=new io({mount:n},{state:i,editable:()=>!Xe,dispatchTransaction(s){Xe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&wr())}}),Y.focus(),e!==void 0&&t!==void 0&&Bd(Y,e,t)}function Zo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Xe)return;const e=Zo(n.target);if(!e){bn();return}Xo(e)&&zd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Zo(n.target);e&&Xo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(yn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,ve=null,dt=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const el=document.createElement("style");el.textContent=`
   [${Ye}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; }
   [${Ye}][data-bd-edit="no"]:hover  { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; }
   [${Ye}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; }
   [${Ye}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); }
-`,document.head.appendChild(Zo);const el=document.currentScript??document.querySelector("script[data-src-hash]"),zd=el?.dataset.srcHash??"",Fd=Number(el?.dataset.srcLen??"-1");gn({type:"bd-edit:ready",hash:zd,len:Fd,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Go(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",yn),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;!e||e.type!=="bd-edit:flush"||typeof e.id!="number"||(Cr(),gn({type:"bd-edit:flushed",id:e.id}))})})();
+`,document.head.appendChild(el);const tl=document.currentScript??document.querySelector("script[data-src-hash]"),Fd=tl?.dataset.srcHash??"",Ld=Number(tl?.dataset.srcLen??"-1");yn({type:"bd-edit:ready",hash:Fd,len:Ld,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Yo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",bn),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:flush"&&typeof e.id=="number"){wr(),e.lock===!0&&(Xe=!0,Y?.setProps({editable:()=>!Xe})),yn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Xe=!1,Y?.setProps({editable:()=>!Xe}))}})})();

From 255a89e4c2554383c2f4d34ec895af484daa0ed7 Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Wed, 11 Nov 2026 23:46:13 +0900
Subject: [PATCH 13/34] fix(webapp): guard Edit source swap during Done save
 and re-check active handle

---
 internal/webapp/frontend/src/apps/Browser.tsx |  5 ++++-
 .../frontend/src/components/FileView.tsx      | 20 +++++++++++--------
 ...{Editor-DzwiNrvp.js => Editor-DYseo8Gn.js} |  2 +-
 ...dit-Co88xBUl.js => VisualEdit-DWsPYvxy.js} |  2 +-
 .../{index-BtQZiOrJ.js => index-YxeGfSng.js}  | 18 ++++++++---------
 ...ile-ifG4O60o.js => sharedfile-CM4z2OLg.js} |  2 +-
 internal/webapp/static/index.html             |  2 +-
 7 files changed, 29 insertions(+), 22 deletions(-)
 rename internal/webapp/static/assets/{Editor-DzwiNrvp.js => Editor-DYseo8Gn.js} (99%)
 rename internal/webapp/static/assets/{VisualEdit-Co88xBUl.js => VisualEdit-DWsPYvxy.js} (97%)
 rename internal/webapp/static/assets/{index-BtQZiOrJ.js => index-YxeGfSng.js} (95%)
 rename internal/webapp/static/assets/{sharedfile-ifG4O60o.js => sharedfile-CM4z2OLg.js} (99%)

diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx
index e79f7b75..9722e395 100644
--- a/internal/webapp/frontend/src/apps/Browser.tsx
+++ b/internal/webapp/frontend/src/apps/Browser.tsx
@@ -1199,7 +1199,10 @@ export default function Browser(props: {
                   ? "Back to editing the page"
                   : "Edit this file's HTML markup"
               }
-              onClick={() => setEditSource((e) => !e)}
+              onClick={() => {
+                if (editFlushRef.current && leavingFlushRef.current === editFlushRef.current) return;
+                setEditSource((e) => !e);
+              }}
             >
               {editSource ? "Edit page" : "Edit source"}
             
diff --git a/internal/webapp/frontend/src/components/FileView.tsx b/internal/webapp/frontend/src/components/FileView.tsx
index 031a2290..5b4d02c1 100644
--- a/internal/webapp/frontend/src/components/FileView.tsx
+++ b/internal/webapp/frontend/src/components/FileView.tsx
@@ -519,15 +519,19 @@ function EditView(props: Parameters[0]) {
        only copy of the buffer and the retry that is still trying to land it.
        Clean or a bystander settles at once. */
     const flush = async () => {
-      const f = fileHandle.current;
-      if (!f) return true;
-      let saved = false;
-      try {
-        saved = await f.saveNow();
-      } catch {
-        return false;
+      for (;;) {
+        const f = fileHandle.current;
+        if (!f) return true;
+        let saved = false;
+        try {
+          saved = await f.saveNow();
+        } catch {
+          return false;
+        }
+        if (!saved || f.askingShrink()) return false;
+        if (fileHandle.current && fileHandle.current !== f) continue;
+        break;
       }
-      if (!saved || f.askingShrink()) return false;
       void qc.invalidateQueries({ queryKey: ["render", apiBase, path] });
       void qc.invalidateQueries({ queryKey: ["text", fileURL] });
       return true;
diff --git a/internal/webapp/static/assets/Editor-DzwiNrvp.js b/internal/webapp/static/assets/Editor-DYseo8Gn.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-DzwiNrvp.js
rename to internal/webapp/static/assets/Editor-DYseo8Gn.js
index 1239ce9b..8495e821 100644
--- a/internal/webapp/static/assets/Editor-DzwiNrvp.js
+++ b/internal/webapp/static/assets/Editor-DYseo8Gn.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BtQZiOrJ.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-ifG4O60o.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-YxeGfSng.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CM4z2OLg.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-Co88xBUl.js b/internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
similarity index 97%
rename from internal/webapp/static/assets/VisualEdit-Co88xBUl.js
rename to internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
index 0f66f3b3..ec8f4d47 100644
--- a/internal/webapp/static/assets/VisualEdit-Co88xBUl.js
+++ b/internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
@@ -1 +1 @@
-import{r as c,j as E,w as we,a as be}from"./index-BtQZiOrJ.js";import{o as ve,D as Te,c as L,a as G,m as ce,d as le}from"./sharedfile-ifG4O60o.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Se=50;function Re(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,A=!1){if(await W(),x||j())return;const b=++f;let v;const q=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},Se)});try{d(A?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await q}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function ke(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function Ee(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Fe({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:A,onConflictCopy:b,baseSha:v,onSaved:q,onWriting:M,onRendered:J,handle:D}){const T=c.useRef(null),[K,de]=c.useState(null),[ue,Q]=c.useState(!1),[fe,U]=c.useState(!1),X=c.useRef(0),[Z,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b};const I=c.useRef(x),H=c.useRef(W);H.current=W;const $=c.useRef(v);$.current=v;const B=c.useRef(null);return c.useEffect(()=>{B.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,P=!1,r=null,m;const xe=700;Q(!1),U(!1);const he=setTimeout(()=>{!y&&X.current<1&&(X.current++,S(e=>e+1))},11e3),pe=setTimeout(()=>U(!0),24e3),s=B.current=ve({apiBase:u,path:f,seed:I.current,baseSha:$.current,who:H.current?.name,me:H.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>be(f,e),onShrinkWithdrawn:we,onReady:()=>{if(clearTimeout(m),m=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(y&&t===i)for(const[o,n]of g){const p=L(n.from,e),C=L(n.to,e);p&&C&&g.set(o,{from:G(s.collab.text,p.index),to:G(s.collab.text,C.index),span:n.span,orig:n.orig})}else g.clear(),y=!1,t!==i&&S(o=>o+1);e.destroy()}P=!0,k()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,I.current),P=!0,k()},onStalled:()=>{P||r||(r=new Te,r.getText("body").insert(0,I.current),P=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():I.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),_=Re();let O=!1;const me=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let o=!1;const n=()=>{o=!0};t.addEventListener("load",n);try{await _.drain(p=>i.postMessage(p,"*"),()=>!O||o||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0};let ee=null;const te={...s,saveNow:()=>ee??=ke(()=>me(!0),()=>s.saveNow(),()=>T.current?.contentWindow?.postMessage({type:"bd-edit:unlock"},"*")).finally(()=>{ee=null})};D&&(D.current=te);const g=new Map,ne=e=>e.start+","+e.end,k=async()=>{if(y||!R||!P)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await Ee(t);if(i!==null?i!==re:V>=0&&t.length!==V){R=null,S(n=>n+1);return}g.clear();for(const n of R)g.set(ne(n),{from:G(e,n.start),to:G(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});y=!0,Q(!0),h.current.onRendered?.()};let re="",V=-1,y=!1;const ge=async e=>{if(e.type==="bd-edit:flushed"){_.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){de("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,re=e.hash,V=e.len,O=!0,await k();return}if(e.type!=="bd-edit:patch")return;y||await k();const t=g.get(ne(e));if(!t)return;if(r){const l=L(t.from,r),F=L(t.to,r);if(!l||!F||l.index>F.index)return;const N=r.getText("body"),ye=F.index-l.index;if(l.index===0&&F.index===N.length&&t.spant.span*4+256){g.clear(),y=!1,S(w=>w+1);return}const z=N.toString().slice(l.index,F.index),ae=ce(t.orig,z,e.html);if(t.orig=e.html,z===ae)return;r.transact(()=>{for(const w of le(z,ae))w.deleteCount>0&&N.delete(l.index+w.index,w.deleteCount),w.insertText&&N.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{s.saveNow()},xe);return}const i=s.collab.doc,o=L(t.from,i),n=L(t.to,i);if(!o||!n||o.index>n.index)return;const p=s.collab.text,C=n.index-o.index;if(o.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),g.clear(),y=!1,S(l=>l+1);return}const Y=p.toString().slice(o.index,n.index),ie=ce(t.orig,Y,e.html);t.orig=e.html,Y!==ie&&s.collab.applySplices(le(Y,ie).map(l=>({...l,index:l.index+o.index})))},oe=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||_.enqueue(()=>ge(t))},se=()=>{k()};return s.collab.text.observe(se),window.addEventListener("message",oe),()=>{D?.current===te&&(D.current=null),O=!1,_.close(),clearTimeout(he),clearTimeout(pe),clearTimeout(m),s.collab.text.unobserve(se),setTimeout(()=>{window.removeEventListener("message",oe),clearTimeout(m),s.destroy(),r?.destroy()},300)}},[u,f,Z]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),fe&&!ue&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},Z)]})}export{Fe as VisualEdit};
+import{r as c,j as E,w as we,a as be}from"./index-YxeGfSng.js";import{o as ve,D as Te,c as L,a as G,m as ce,d as le}from"./sharedfile-CM4z2OLg.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Se=50;function Re(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,A=!1){if(await W(),x||j())return;const b=++f;let v;const q=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},Se)});try{d(A?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await q}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function ke(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function Ee(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Fe({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:A,onConflictCopy:b,baseSha:v,onSaved:q,onWriting:M,onRendered:J,handle:D}){const T=c.useRef(null),[K,de]=c.useState(null),[ue,Q]=c.useState(!1),[fe,U]=c.useState(!1),X=c.useRef(0),[Z,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b};const I=c.useRef(x),H=c.useRef(W);H.current=W;const $=c.useRef(v);$.current=v;const B=c.useRef(null);return c.useEffect(()=>{B.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,P=!1,r=null,m;const xe=700;Q(!1),U(!1);const he=setTimeout(()=>{!y&&X.current<1&&(X.current++,S(e=>e+1))},11e3),pe=setTimeout(()=>U(!0),24e3),s=B.current=ve({apiBase:u,path:f,seed:I.current,baseSha:$.current,who:H.current?.name,me:H.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>be(f,e),onShrinkWithdrawn:we,onReady:()=>{if(clearTimeout(m),m=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(y&&t===i)for(const[o,n]of g){const p=L(n.from,e),C=L(n.to,e);p&&C&&g.set(o,{from:G(s.collab.text,p.index),to:G(s.collab.text,C.index),span:n.span,orig:n.orig})}else g.clear(),y=!1,t!==i&&S(o=>o+1);e.destroy()}P=!0,k()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,I.current),P=!0,k()},onStalled:()=>{P||r||(r=new Te,r.getText("body").insert(0,I.current),P=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():I.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),_=Re();let O=!1;const me=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let o=!1;const n=()=>{o=!0};t.addEventListener("load",n);try{await _.drain(p=>i.postMessage(p,"*"),()=>!O||o||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0};let ee=null;const te={...s,saveNow:()=>ee??=ke(()=>me(!0),()=>s.saveNow(),()=>T.current?.contentWindow?.postMessage({type:"bd-edit:unlock"},"*")).finally(()=>{ee=null})};D&&(D.current=te);const g=new Map,ne=e=>e.start+","+e.end,k=async()=>{if(y||!R||!P)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await Ee(t);if(i!==null?i!==re:V>=0&&t.length!==V){R=null,S(n=>n+1);return}g.clear();for(const n of R)g.set(ne(n),{from:G(e,n.start),to:G(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});y=!0,Q(!0),h.current.onRendered?.()};let re="",V=-1,y=!1;const ge=async e=>{if(e.type==="bd-edit:flushed"){_.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){de("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,re=e.hash,V=e.len,O=!0,await k();return}if(e.type!=="bd-edit:patch")return;y||await k();const t=g.get(ne(e));if(!t)return;if(r){const l=L(t.from,r),F=L(t.to,r);if(!l||!F||l.index>F.index)return;const N=r.getText("body"),ye=F.index-l.index;if(l.index===0&&F.index===N.length&&t.spant.span*4+256){g.clear(),y=!1,S(w=>w+1);return}const z=N.toString().slice(l.index,F.index),ae=ce(t.orig,z,e.html);if(t.orig=e.html,z===ae)return;r.transact(()=>{for(const w of le(z,ae))w.deleteCount>0&&N.delete(l.index+w.index,w.deleteCount),w.insertText&&N.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{s.saveNow()},xe);return}const i=s.collab.doc,o=L(t.from,i),n=L(t.to,i);if(!o||!n||o.index>n.index)return;const p=s.collab.text,C=n.index-o.index;if(o.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),g.clear(),y=!1,S(l=>l+1);return}const Y=p.toString().slice(o.index,n.index),ie=ce(t.orig,Y,e.html);t.orig=e.html,Y!==ie&&s.collab.applySplices(le(Y,ie).map(l=>({...l,index:l.index+o.index})))},oe=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||_.enqueue(()=>ge(t))},se=()=>{k()};return s.collab.text.observe(se),window.addEventListener("message",oe),()=>{D?.current===te&&(D.current=null),O=!1,_.close(),clearTimeout(he),clearTimeout(pe),clearTimeout(m),s.collab.text.unobserve(se),setTimeout(()=>{window.removeEventListener("message",oe),clearTimeout(m),s.destroy(),r?.destroy()},300)}},[u,f,Z]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),fe&&!ue&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},Z)]})}export{Fe as VisualEdit};
diff --git a/internal/webapp/static/assets/index-BtQZiOrJ.js b/internal/webapp/static/assets/index-YxeGfSng.js
similarity index 95%
rename from internal/webapp/static/assets/index-BtQZiOrJ.js
rename to internal/webapp/static/assets/index-YxeGfSng.js
index 0bebdf36..e804446f 100644
--- a/internal/webapp/static/assets/index-BtQZiOrJ.js
+++ b/internal/webapp/static/assets/index-YxeGfSng.js
@@ -1,4 +1,4 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DzwiNrvp.js","assets/sharedfile-ifG4O60o.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-Co88xBUl.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DYseo8Gn.js","assets/sharedfile-CM4z2OLg.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DWsPYvxy.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1p||F[d]!==ne[p]){var ce=`
 `+F[d].replace(" at new "," at ");return s.displayName&&ce.includes("")&&(ce=ce.replace("",s.displayName)),ce}while(1<=d&&0<=p);break}}}finally{es=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?tt(c):""}function ot(s,a){switch(s.tag){case 26:case 27:case 5:return tt(s.type);case 16:return tt("Lazy");case 13:return s.child!==a&&a!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return Fe(s.type,!1);case 11:return Fe(s.type.render,!1);case 1:return Fe(s.type,!0);case 31:return tt("Activity");default:return""}}function Yt(s){try{var a="",c=null;do a+=ot(s,c),c=s,s=s.return;while(s);return a}catch(d){return`
 Error generating stack: `+d.message+`
-`+d.stack}}var Nt=Object.prototype.hasOwnProperty,dn=e.unstable_scheduleCallback,jt=e.unstable_cancelCallback,Lt=e.unstable_shouldYield,ts=e.unstable_requestPaint,At=e.unstable_now,sn=e.unstable_getCurrentPriorityLevel,ns=e.unstable_ImmediatePriority,hr=e.unstable_UserBlockingPriority,Hs=e.unstable_NormalPriority,ms=e.unstable_LowPriority,Tn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Ae,je=Math.log,_e=Math.LN2;function Ae(s){return s>>>=0,s===0?32:31-(je(s)/_e|0)|0}var Ke=256,Ct=262144,rn=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function dt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function Et(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $t(){var s=rn;return rn<<=1,(rn&62914560)===0&&(rn=4194304),s}function Hn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function vt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function fn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Lf=/[\n"\\]/g;function On(s){return s.replace(Lf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Bs(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+En(a)):s.value!==""+En(a)&&(s.value=""+En(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ti(s,C,En(a)):c!=null?Ti(s,C,En(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+En(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){ki(s);return}c=c!=null?""+En(c):"",a=a!=null?""+En(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),ki(s)}function Ti(s,a,c){a==="number"&&Ri(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Gs(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ff=!1;if(vr)try{var Ho={};Object.defineProperty(Ho,"passive",{get:function(){Ff=!0}}),window.addEventListener("test",Ho,Ho),window.removeEventListener("test",Ho,Ho)}catch{Ff=!1}var Zr=null,If=null,Cc=null;function wy(){if(Cc)return Cc;var s,a=If,c=a.length,d,p="value"in Zr?Zr.value:Zr.textContent,v=p.length;for(s=0;s=Go),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Di=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Di)return s==="compositionend"||!qf&&Ry(s,a)?(s=wy(),Cc=If=Zr=null,Di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Ri(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Ri(s.document)}return a}function Kf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=vr&&"documentMode"in document&&11>=document.documentMode,zi=null,Zf=null,Qo=null,Yf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Yf||zi==null||zi!==Ri(d)||(d=zi,"selectionStart"in d&&Kf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Qo&&Yo(Qo,d)||(Qo=d,d=vu(Zf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ze?(st=De,De=null):st=De.sibling;var ut=se(J,De,te[Ze],ue);if(ut===null){De===null&&(De=st);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=st}if(Ze===te.length)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;ZeZe?(st=De,De=null):st=De.sibling;var ga=se(J,De,ut.value,ue);if(ga===null){De===null&&(De=st);break}s&&De&&ga.alternate===null&&a(J,De),G=v(ga,G,Ze),ct===null?$e=ga:ct.sibling=ga,ct=ga,De=st}if(ut.done)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;!ut.done;Ze++,ut=te.next())ut=fe(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return it&&xr(J,Ze),$e}for(De=d(De);!ut.done;Ze++,ut=te.next())ut=oe(De,J,Ze,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ze:ut.key),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),it&&xr(J,Ze),$e}function bt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Za($e)===G.type){c(J,G.sibling),ue=p(G,te.props),nl(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ha(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=Dc(te.type,te.key,te.props,null,J.mode,ue),nl(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=nh(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Za(te),bt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if($e=Q(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return bt(J,G,Uc(te),ue);if(te.$$typeof===R)return bt(J,G,$c(J,te),ue);Vc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=th(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{tl=0;var $e=bt(J,G,te,ue);return Gi=null,$e}catch(De){if(De===Bi||De===Ic)throw De;var ct=rs(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Qa=d0(!0),f0=d0(!1),Jr=!1;function mh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ph(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ea(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function ta(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Ac(s),Yy(s,null,c),a}return Oc(s,d,a,c),Ac(s)}function sl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}function gh(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var vh=!1;function rl(){if(vh){var s=qi;if(s!==null)throw s}}function al(s,a,c,d){vh=!1;var p=s.updateQueue;Jr=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(nt&se)===se:(d&se)===se){se!==0&&se===Hi&&(vh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Pe=k;se=a;var bt=c;switch(Pe.tag){case 1:if(Oe=Pe.payload,typeof Oe=="function"){fe=Oe.call(bt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Pe.payload,se=typeof Oe=="function"?Oe.call(bt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:Jr=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ia|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,Lh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);ll(s,a,ce,cs(s))}else ll(s,a,d,cs(s))}catch(fe){ll(s,a,{then:function(){},status:"rejected",reason:fe},cs())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Dh(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),ll(s,a.next.queue,{},cs())}function zh(){return gn(_l)}function Z0(){return Bt().memoizedState}function Y0(){return Bt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=cs();s=ea(c);var d=ta(a,s,c);d!==null&&(Xn(d,a,c),sl(d,a,c)),a={cache:uh()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=cs();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Wc(s)?X0(a,c):(c=Jf(s,a,c,d),c!==null&&(Xn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=cs();ll(s,a,c,d)}function ll(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Wc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ss(k,C))return Oc(s,a,p,0),_t===null&&Tc(),!1}catch{}if(c=Jf(s,a,p,d),c!==null)return Xn(c,s,d),W0(c,a,d),!0}return!1}function Lh(s,a,c,d){if(d={lane:2,revertLane:mm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Wc(s)){if(a)throw Error(r(479))}else a=Jf(s,c,d,2),a!==null&&Xn(a,s,2)}function Wc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Zi=Bc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}var cl={readContext:gn,use:Zc,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};cl.useEffectEvent=Pt;var J0={readContext:gn,use:Zc,useCallback:function(s,a){return zn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Qc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Qc(4194308,4,s,a)},useInsertionEffect:function(s,a){Qc(4,2,s,a)},useMemo:function(s,a){var c=zn();a=a===void 0?null:a;var d=s();if(Xa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=zn();if(c!==void 0){var p=c(a);if(Xa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=zn();return s={current:s},a.memoizedState=s},useState:function(s){s=Rh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Oh,useDeferredValue:function(s,a){var c=zn();return Ah(c,s,a)},useTransition:function(){var s=Rh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),zn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=zn();if(it){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),_t===null)throw Error(r(349));(nt&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Qi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=zn(),a=_t.identifierPrefix;if(it){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Gc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[Ft]=a,v[_n]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&_r(a)}}return Rt(a),Qh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&_r(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ui(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[Ft]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Xr(a,!0)}else s=yu(s).createTextNode(d),s[Ft]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ui(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(is(a),a):(is(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ui(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(is(a),a):(is(a),null)}return is(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),su(a,a.updateQueue),Rt(a),null);case 4:return Se(),s===null&&ym(a.stateNode.containerInfo),Rt(a),null;case 10:return wr(a.type),Rt(a),null;case 19:if(D(qt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)dl(d,!1);else{if(Ut!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=qc(s),v!==null){for(a.flags|=128,dl(d,!1),s=v.updateQueue,a.updateQueue=s,su(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(qt,qt.current&1|2),it&&xr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&At()>lu&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304)}else{if(!p)if(s=qc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,su(a,s),dl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!it)return Rt(a),null}else 2*At()-d.renderingStartTime>lu&&c!==536870912&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=At(),s.sibling=null,c=qt.current,B(qt,p?c&1|2:c&1),it&&xr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return is(a),xh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&su(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Ka),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),wr(Qt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(rh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return wr(Qt),Se(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Me(a),null;case 31:if(a.memoizedState!==null){if(is(a),a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(is(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(qt),null;case 4:return Se(),null;case 10:return wr(a.type),null;case 22:case 23:return is(a),xh(),s!==null&&D(Ka),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return wr(Qt),null;case 25:return null;default:return null}}function jx(s,a){switch(rh(a),a.tag){case 3:wr(Qt),Se();break;case 26:case 27:case 5:Me(a);break;case 4:Se();break;case 31:a.memoizedState!==null&&is(a);break;case 13:is(a);break;case 19:D(qt);break;case 10:wr(a.type);break;case 22:case 23:is(a),xh(),s!==null&&D(Ka);break;case 24:wr(Qt)}}function fl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ra(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Wa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function hl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Xh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[_n]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&da(s.type)||s.tag===4}function Wh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&da(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Jh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Qe));else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Jh(s,a,c),s=s.sibling;s!==null;)Jh(s,a,c),s=s.sibling}function ru(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(ru(s,a,c),s=s.sibling;s!==null;)ru(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[Ft]=s,a[_n]=c}catch(v){pt(s,s.return,v)}}var Er=!1,Jt=!1,em=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Vk(s,a){if(s=s.containerInfo,wm=_u,s=Uy(s),Kf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(Sm={focusedElem:s,selectionRange:c},_u=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[Ft]=s,Ht(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kbt&&(C=bt,bt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,bt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>bt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=om,om=null;var v=la,C=Tr;if(on=0,to=la=null,Tr=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,xl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=xs(c,a),a=Ph(s.stateNode,a,2),s=ta(s,a,2),s!==null&&(vt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(oa===null||!oa.has(d))){s=xs(c,s),c=ox(2),d=ta(a,c,2),d!==null&&(lx(c,d,a,s),vt(d,2),Ws(d));break}}a=a.return}}function dm(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(sm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,_t===s&&(nt&c)===c&&(Ut===4||Ut===3&&(nt&62914560)===nt&&300>At()-ou?(ft&2)===0&&no(s,0):rm|=c,eo===nt&&(eo=0)),Ws(s)}function ob(s,a){a===0&&(a=$t()),s=Va(s,a),s!==null&&(vt(s,a),Ws(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return dn(s,a)}var mu=null,ro=null,fm=!1,pu=!1,hm=!1,ua=0;function Ws(s){s!==ro&&s.next===null&&(ro===null?mu=ro=s:ro=ro.next=s),pu=!0,fm||(fm=!0,tR())}function xl(s,a){if(!hm&&pu){hm=!0;do for(var c=!1,d=mu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=nt,v=Le(d,d===_t?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||dt(d,v)||(c=!0,db(d,v));d=d.next}while(c);hm=!1}}function eR(){lb()}function lb(){pu=fm=!1;var s=0;ua!==0&&dR()&&(s=ua);for(var a=At(),c=null,d=mu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?mu=p:c.next=p,p===null&&(ro=c)):(c=d,(s!==0||(v&3)!==0)&&(pu=!0)),d=p}on!==0&&on!==5||xl(s),ua!==0&&(ua=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=ao;if(d&&typeof a=="string"&&a){var p=On(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function bR(s){Or.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Or.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Or.L(s,a,c);var d=ao;if(d&&s&&a){var p='link[rel="preload"][as="'+On(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+On(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+On(c.imageSizes)+'"]')):p+='[href="'+On(s)+'"]';var v=p;switch(a){case"style":v=io(s);break;case"script":v=oo(s)}_s.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),_s.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(jl(v))||a==="script"&&d.querySelector(Cl(v))||(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function jR(s,a){Or.m(s,a);var c=ao;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+On(d)+'"][href="'+On(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=oo(s)}if(!_s.has(v)&&(s=g({rel:"modulepreload",href:s},a),_s.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Cl(v)))return}d=c.createElement("link"),yn(d,"link",s),Ht(d),c.head.appendChild(d)}}}function CR(s,a,c){Or.S(s,a,c);var d=ao;if(d&&s){var p=Gr(d).hoistableStyles,v=io(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(jl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=_s.get(v))&&Rm(s,c);var F=C=d.createElement("link");Ht(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,bu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Or.X(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Or.M(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?xu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=io(c.href),c=Gr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=io(c.href);var v=Gr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(jl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),_s.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},_s.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=oo(c),c=Gr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function io(s){return'href="'+On(s)+'"'}function jl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Ht(a),s.head.appendChild(a))}function oo(s){return'[src="'+On(s)+'"]'}function Cl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+On(c.href)+'"]');if(d)return a.instance=d,Ht(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Ht(d),yn(d,"style",p),bu(d,c.precedence,s),a.instance=d;case"stylesheet":p=io(c.href);var v=s.querySelector(jl(p));if(v)return a.state.loading|=4,a.instance=v,Ht(v),v;d=Ab(c),(p=_s.get(p))&&Rm(d,p),v=(s.ownerDocument||s).createElement("link"),Ht(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,bu(v,c.precedence,s),a.instance=v;case"script":return v=oo(c.src),(p=s.querySelector(Cl(v)))?(a.instance=p,Ht(p),p):(d=c,(p=_s.get(v))&&(d=g({},c),Mm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Ht(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,bu(d,c.precedence,s));return a.instance}function bu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=io(d.href),v=a.querySelector(jl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=Su.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Ht(v);return}v=a.ownerDocument||a,d=Ab(d),(p=_s.get(p))&&Rm(d,p),v=v.createElement("link"),Ht(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=Su.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Tm=0;function MR(s,a){return s.stylesheets&&s.count===0&&Cu(s,s.stylesheets),0Tm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ju=null;function Cu(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ju=new Map,a.forEach(TR,s),ju=null,Su.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=ju.get(s);if(c)var d=c.get(null);else{c=new Map,ju.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Pm.exports=XR(),Pm.exports}var JR=WR(),To=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends To{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fg=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ai=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Fn(){}function aM(e,t){return typeof e=="function"?e(t):e}function Rp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Sa(e,t){return typeof e=="function"?e(t):e}function us(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Ig(u,t.options))return!1}else if(!ql(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(di(t.options.mutationKey)!==di(l))return!1}else if(!ql(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ig(e,t){return(t?.queryKeyHashFn||di)(e)}function di(e){return JSON.stringify(e,(t,n)=>Mp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function ql(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ql(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Mp(e)&&Mp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ai.setTimeout(t,e)})}function Tp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pg=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ug(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Bl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Op(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var un=fM(),hM=class extends To{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},gd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?gd.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Op(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Ap(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>Fg.isFocused()&&(e.networkMode==="always"||gd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Bl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rp(this.gcTime)&&(this.#e=ai.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Bl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ai.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Dp,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Dp(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Dp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Dp(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Tp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Fn).catch(Fn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>us(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Sa(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Ap&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Ap){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),un.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends To{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Op(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof us(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!pd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||Sa(this.options.staleTime,this.#t)!==Sa(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Fn)),t}#g(){this.#b();const e=Sa(this.options.staleTime,this.#t);if(Bl.isServer()||this.#s.isStale||!Rp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ai.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Bl.isServer()||us(this.options.enabled,this.#t)===!1||!Rp(this.#c)||this.#c===0)&&(this.#f=ai.setInterval(()=>{(this.options.refetchIntervalInBackground||Fg.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ai.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ai.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Tp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Tp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Vg(e,t),refetch:this.refetch,promise:this.#o,isEnabled:us(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Op();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),pd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){un.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return us(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&us(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&zp(e,t,t.refetchOnMount)}function zp(e,t,n){if(us(t.enabled,e)!==!1&&Sa(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vg(e,t)}return!1}function mw(e,t,n,r){return(e!==t||us(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vg(e,n)}function Vg(e,t){return us(t.enabled,e)!==!1&&e.isStaleByTime(Sa(t.staleTime,e))}function bM(e,t){return!pd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),un.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ou(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ou(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){un.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return un.batch(()=>Promise.all(e.map(t=>t.continue().catch(Fn))))}};function Ou(e){return e.options.scope?.id}var CM=class extends To{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),pd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&di(n.mutationKey)!==di(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){un.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Ig(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){un.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){un.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){un.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){un.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Fg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Sa(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return un.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;un.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return un.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=un.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Fn).catch(Fn)}invalidateQueries(e,t={}){return un.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=un.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Fn)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Fn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Sa(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Fn).catch(Fn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Fn).catch(Fn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(di(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ql(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(di(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{ql(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ig(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),mn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Ug(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Ug(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(un.batchCalls(x)):Fn;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Bl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Fn).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function rt(e,t){return tj(e,XS)}function FM(e,t){const n=mn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(un.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Fn)},[r]);if(i.error&&Ug(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function Hd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function qd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Hg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function Oo(e){const t=await e.text();throw new Hg(e.status,HM(e.status,t),t)}async function We(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&qd(),t.ok||await Oo(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&qd(),t.ok||await Oo(t),t}async function en(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await Oo(i),Hd(e,t),i.status===204?{}:i.json()}async function vd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&Hd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&qd(),n.ok||await Oo(n),Hd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&qd(),f.ok||await Oo(f),Hd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await Oo(l),await l.json()}let Lp=null;function GM(){Lp??=We("/api/config")}function KM(){return rt({queryKey:["config"],queryFn:async()=>{const e=Lp;Lp=null;const t=await(e??We("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var rc=VS();const ZM=PS(rc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Eo(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Au=="function"&&(i=Au(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Au=="function"&&(j=Au(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Zt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=No("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Au=Vd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=aT.reduce((e,t)=>{const n=No(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&rc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(lt.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Na(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Na(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=No(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Zt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=No(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Zt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?b.useLayoutEffect:()=>{},uT=Vd[" useInsertionEffect ".trim().toString()]||ar;function ac({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Tl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Tl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Tl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Tl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Tl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function ds(e){const[t,n]=b.useState(vT());return ar(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Pr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",$p="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,qg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Bd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(qg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Zt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=kT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Pr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const X=()=>j({});return document.addEventListener($p,X),()=>document.removeEventListener($p,X)},[]),o.jsx(lt.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Bd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(qg),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(lt.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(qg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Pr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Pr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent($p);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var qm="focusScope.autoFocusOnMount",Bm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",Bg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Pr(i),y=Pr(l),g=b.useRef(null),w=Zt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:xa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||xa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&xa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(qm,jw);f.addEventListener(qm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&xa(f))}return()=>{f.removeEventListener(qm,m),setTimeout(()=>{const _=new CustomEvent(Bm,jw);f.addEventListener(Bm,y),f.dispatchEvent(_),_.defaultPrevented||xa(S??document.body,{select:!0}),f.removeEventListener(Bm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&xa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&xa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(lt.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});Bg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function xa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Gd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?rc.createPortal(o.jsx(lt.div,{...r,ref:t}),u):null});Gd.displayName=LT;var Du=0,co=null;function dj(){b.useEffect(()=>{co||(co={start:Nw(),end:Nw()});const{start:e,end:t}=co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Du++,()=>{Du===1&&(co?.start.remove(),co?.end.remove(),co=null),Du=Math.max(0,Du-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),So="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
+`+d.stack}}var jt=Object.prototype.hasOwnProperty,sn=e.unstable_scheduleCallback,Ct=e.unstable_cancelCallback,Lt=e.unstable_shouldYield,ts=e.unstable_requestPaint,At=e.unstable_now,rn=e.unstable_getCurrentPriorityLevel,ns=e.unstable_ImmediatePriority,hr=e.unstable_UserBlockingPriority,Hs=e.unstable_NormalPriority,ms=e.unstable_LowPriority,Tn=e.unstable_IdlePriority,z=e.log,Y=e.unstable_setDisableYieldValue,W=null,de=null;function me(s){if(typeof z=="function"&&Y(s),de&&typeof de.setStrictMode=="function")try{de.setStrictMode(W,s)}catch{}}var xe=Math.clz32?Math.clz32:Ae,je=Math.log,_e=Math.LN2;function Ae(s){return s>>>=0,s===0?32:31-(je(s)/_e|0)|0}var Ke=256,_t=262144,an=4194304;function Dt(s){var a=s&42;if(a!==0)return a;switch(s&-s){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function Le(s,a,c){var d=s.pendingLanes;if(d===0)return 0;var p=0,v=s.suspendedLanes,C=s.pingedLanes;s=s.warmLanes;var k=d&134217727;return k!==0?(d=k&~v,d!==0?p=Dt(d):(C&=k,C!==0?p=Dt(C):c||(c=k&~s,c!==0&&(p=Dt(c))))):(k=d&~v,k!==0?p=Dt(k):C!==0?p=Dt(C):c||(c=d&~s,c!==0&&(p=Dt(c)))),p===0?0:a!==0&&a!==p&&(a&v)===0&&(v=p&-p,c=a&-a,v>=c||v===32&&(c&4194048)!==0)?a:p}function dt(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function Nt(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $t(){var s=an;return an<<=1,(an&62914560)===0&&(an=4194304),s}function Hn(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function vt(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function fn(s,a,c,d,p,v){var C=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var k=s.entanglements,F=s.expirationTimes,ne=s.hiddenUpdates;for(c=C&~c;0"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Lf=/[\n"\\]/g;function On(s){return s.replace(Lf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Bs(s,a,c,d,p,v,C,k){s.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?s.type=C:s.removeAttribute("type"),a!=null?C==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+En(a)):s.value!==""+En(a)&&(s.value=""+En(a)):C!=="submit"&&C!=="reset"||s.removeAttribute("value"),a!=null?Ti(s,C,En(a)):c!=null?Ti(s,C,En(c)):d!=null&&s.removeAttribute("value"),p==null&&v!=null&&(s.defaultChecked=!!v),p!=null&&(s.checked=p&&typeof p!="function"&&typeof p!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?s.name=""+En(k):s.removeAttribute("name")}function Mi(s,a,c,d,p,v,C,k){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(s.type=v),a!=null||c!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){ki(s);return}c=c!=null?""+En(c):"",a=a!=null?""+En(a):c,k||a===s.value||(s.value=a),s.defaultValue=a}d=d??p,d=typeof d!="function"&&typeof d!="symbol"&&!!d,s.checked=k?s.checked:!!d,s.defaultChecked=!!d,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(s.name=C),ki(s)}function Ti(s,a,c){a==="number"&&Ri(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Gs(s,a,c,d){if(s=s.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ff=!1;if(vr)try{var Ho={};Object.defineProperty(Ho,"passive",{get:function(){Ff=!0}}),window.addEventListener("test",Ho,Ho),window.removeEventListener("test",Ho,Ho)}catch{Ff=!1}var Zr=null,If=null,Cc=null;function wy(){if(Cc)return Cc;var s,a=If,c=a.length,d,p="value"in Zr?Zr.value:Zr.textContent,v=p.length;for(s=0;s=Go),Ny=" ",ky=!1;function Ry(s,a){switch(s){case"keyup":return lk.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function My(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Di=!1;function uk(s,a){switch(s){case"compositionend":return My(a);case"keypress":return a.which!==32?null:(ky=!0,Ny);case"textInput":return s=a.data,s===Ny&&ky?null:s;default:return null}}function dk(s,a){if(Di)return s==="compositionend"||!qf&&Ry(s,a)?(s=wy(),Cc=If=Zr=null,Di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-s};s=d}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=Fy(c)}}function Py(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Py(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Uy(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=Ri(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=Ri(s.document)}return a}function Kf(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var xk=vr&&"documentMode"in document&&11>=document.documentMode,zi=null,Zf=null,Qo=null,Yf=!1;function Vy(s,a,c){var d=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Yf||zi==null||zi!==Ri(d)||(d=zi,"selectionStart"in d&&Kf(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Qo&&Yo(Qo,d)||(Qo=d,d=vu(Zf,"onSelect"),0>=C,p-=C,Ys=1<<32-xe(a)+p|c<Ze?(st=De,De=null):st=De.sibling;var ut=se(J,De,te[Ze],ue);if(ut===null){De===null&&(De=st);break}s&&De&&ut.alternate===null&&a(J,De),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut,De=st}if(Ze===te.length)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;ZeZe?(st=De,De=null):st=De.sibling;var ga=se(J,De,ut.value,ue);if(ga===null){De===null&&(De=st);break}s&&De&&ga.alternate===null&&a(J,De),G=v(ga,G,Ze),ct===null?$e=ga:ct.sibling=ga,ct=ga,De=st}if(ut.done)return c(J,De),it&&xr(J,Ze),$e;if(De===null){for(;!ut.done;Ze++,ut=te.next())ut=fe(J,ut.value,ue),ut!==null&&(G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return it&&xr(J,Ze),$e}for(De=d(De);!ut.done;Ze++,ut=te.next())ut=oe(De,J,Ze,ut.value,ue),ut!==null&&(s&&ut.alternate!==null&&De.delete(ut.key===null?Ze:ut.key),G=v(ut,G,Ze),ct===null?$e=ut:ct.sibling=ut,ct=ut);return s&&De.forEach(function(IR){return a(J,IR)}),it&&xr(J,Ze),$e}function bt(J,G,te,ue){if(typeof te=="object"&&te!==null&&te.type===S&&te.key===null&&(te=te.props.children),typeof te=="object"&&te!==null){switch(te.$$typeof){case x:e:{for(var $e=te.key;G!==null;){if(G.key===$e){if($e=te.type,$e===S){if(G.tag===7){c(J,G.sibling),ue=p(G,te.props.children),ue.return=J,J=ue;break e}}else if(G.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===H&&Za($e)===G.type){c(J,G.sibling),ue=p(G,te.props),nl(ue,te),ue.return=J,J=ue;break e}c(J,G);break}else a(J,G);G=G.sibling}te.type===S?(ue=Ha(te.props.children,J.mode,ue,te.key),ue.return=J,J=ue):(ue=Dc(te.type,te.key,te.props,null,J.mode,ue),nl(ue,te),ue.return=J,J=ue)}return C(J);case j:e:{for($e=te.key;G!==null;){if(G.key===$e)if(G.tag===4&&G.stateNode.containerInfo===te.containerInfo&&G.stateNode.implementation===te.implementation){c(J,G.sibling),ue=p(G,te.children||[]),ue.return=J,J=ue;break e}else{c(J,G);break}else a(J,G);G=G.sibling}ue=nh(te,J.mode,ue),ue.return=J,J=ue}return C(J);case H:return te=Za(te),bt(J,G,te,ue)}if(be(te))return Oe(J,G,te,ue);if(Q(te)){if($e=Q(te),typeof $e!="function")throw Error(r(150));return te=$e.call(te),Pe(J,G,te,ue)}if(typeof te.then=="function")return bt(J,G,Uc(te),ue);if(te.$$typeof===R)return bt(J,G,$c(J,te),ue);Vc(J,te)}return typeof te=="string"&&te!==""||typeof te=="number"||typeof te=="bigint"?(te=""+te,G!==null&&G.tag===6?(c(J,G.sibling),ue=p(G,te),ue.return=J,J=ue):(c(J,G),ue=th(te,J.mode,ue),ue.return=J,J=ue),C(J)):c(J,G)}return function(J,G,te,ue){try{tl=0;var $e=bt(J,G,te,ue);return Gi=null,$e}catch(De){if(De===Bi||De===Ic)throw De;var ct=rs(29,De,null,J.mode);return ct.lanes=ue,ct.return=J,ct}}}var Qa=d0(!0),f0=d0(!1),Jr=!1;function mh(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ph(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function ea(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function ta(s,a,c){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(ft&2)!==0){var p=d.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),d.pending=a,a=Ac(s),Yy(s,null,c),a}return Oc(s,d,a,c),Ac(s)}function sl(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}function gh(s,a){var c=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,c===d)){var p=null,v=null;if(c=c.firstBaseUpdate,c!==null){do{var C={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};v===null?p=v=C:v=v.next=C,c=c.next}while(c!==null);v===null?p=v=a:v=v.next=a}else p=v=a;c={baseState:d.baseState,firstBaseUpdate:p,lastBaseUpdate:v,shared:d.shared,callbacks:d.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var vh=!1;function rl(){if(vh){var s=qi;if(s!==null)throw s}}function al(s,a,c,d){vh=!1;var p=s.updateQueue;Jr=!1;var v=p.firstBaseUpdate,C=p.lastBaseUpdate,k=p.shared.pending;if(k!==null){p.shared.pending=null;var F=k,ne=F.next;F.next=null,C===null?v=ne:C.next=ne,C=F;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==C&&(k===null?ce.firstBaseUpdate=ne:k.next=ne,ce.lastBaseUpdate=F))}if(v!==null){var fe=p.baseState;C=0,ce=ne=F=null,k=v;do{var se=k.lane&-536870913,oe=se!==k.lane;if(oe?(nt&se)===se:(d&se)===se){se!==0&&se===Hi&&(vh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=s,Pe=k;se=a;var bt=c;switch(Pe.tag){case 1:if(Oe=Pe.payload,typeof Oe=="function"){fe=Oe.call(bt,fe,se);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Pe.payload,se=typeof Oe=="function"?Oe.call(bt,fe,se):Oe,se==null)break e;fe=g({},fe,se);break e;case 2:Jr=!0}}se=k.callback,se!==null&&(s.flags|=64,oe&&(s.flags|=8192),oe=p.callbacks,oe===null?p.callbacks=[se]:oe.push(se))}else oe={lane:se,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(ne=ce=oe,F=fe):ce=ce.next=oe,C|=se;if(k=k.next,k===null){if(k=p.shared.pending,k===null)break;oe=k,k=oe.next,oe.next=null,p.lastBaseUpdate=oe,p.shared.pending=null}}while(!0);ce===null&&(F=fe),p.baseState=F,p.firstBaseUpdate=ne,p.lastBaseUpdate=ce,v===null&&(p.shared.lanes=0),ia|=C,s.lanes=C,s.memoizedState=fe}}function h0(s,a){if(typeof s!="function")throw Error(r(191,s));s.call(a)}function m0(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;sv?v:8;var C=$.T,k={};$.T=k,Lh(s,!1,a,c);try{var F=p(),ne=$.S;if(ne!==null&&ne(k,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var ce=kk(F,d);ll(s,a,ce,cs(s))}else ll(s,a,d,cs(s))}catch(fe){ll(s,a,{then:function(){},status:"rejected",reason:fe},cs())}finally{q.p=v,C!==null&&k.types!==null&&(C.types=k.types),$.T=C}}function Dk(){}function Dh(s,a,c,d){if(s.tag!==5)throw Error(r(476));var p=G0(s).queue;B0(s,p,a,V,c===null?Dk:function(){return K0(s),c(d)})}function G0(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:V},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jr,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function K0(s){var a=G0(s);a.next===null&&(a=s.alternate.memoizedState),ll(s,a.next.queue,{},cs())}function zh(){return gn(_l)}function Z0(){return Bt().memoizedState}function Y0(){return Bt().memoizedState}function zk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=cs();s=ea(c);var d=ta(a,s,c);d!==null&&(Xn(d,a,c),sl(d,a,c)),a={cache:uh()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var d=cs();c={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Wc(s)?X0(a,c):(c=Jf(s,a,c,d),c!==null&&(Xn(c,s,d),W0(c,a,d)))}function Q0(s,a,c){var d=cs();ll(s,a,c,d)}function ll(s,a,c,d){var p={lane:d,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Wc(s))X0(a,p);else{var v=s.alternate;if(s.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var C=a.lastRenderedState,k=v(C,c);if(p.hasEagerState=!0,p.eagerState=k,ss(k,C))return Oc(s,a,p,0),Et===null&&Tc(),!1}catch{}if(c=Jf(s,a,p,d),c!==null)return Xn(c,s,d),W0(c,a,d),!0}return!1}function Lh(s,a,c,d){if(d={lane:2,revertLane:mm(),gesture:null,action:d,hasEagerState:!1,eagerState:null,next:null},Wc(s)){if(a)throw Error(r(479))}else a=Jf(s,c,d,2),a!==null&&Xn(a,s,2)}function Wc(s){var a=s.alternate;return s===Ge||a!==null&&a===Ge}function X0(s,a){Zi=Bc=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function W0(s,a,c){if((c&4194048)!==0){var d=a.lanes;d&=s.pendingLanes,c|=d,a.lanes=c,Cn(s,c)}}var cl={readContext:gn,use:Zc,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};cl.useEffectEvent=Pt;var J0={readContext:gn,use:Zc,useCallback:function(s,a){return zn().memoizedState=[s,a===void 0?null:a],s},useContext:gn,useEffect:L0,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Qc(4194308,4,P0.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Qc(4194308,4,s,a)},useInsertionEffect:function(s,a){Qc(4,2,s,a)},useMemo:function(s,a){var c=zn();a=a===void 0?null:a;var d=s();if(Xa){me(!0);try{s()}finally{me(!1)}}return c.memoizedState=[d,a],d},useReducer:function(s,a,c){var d=zn();if(c!==void 0){var p=c(a);if(Xa){me(!0);try{c(a)}finally{me(!1)}}}else p=a;return d.memoizedState=d.baseState=p,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:p},d.queue=s,s=s.dispatch=Lk.bind(null,Ge,s),[d.memoizedState,s]},useRef:function(s){var a=zn();return s={current:s},a.memoizedState=s},useState:function(s){s=Rh(s);var a=s.queue,c=Q0.bind(null,Ge,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:Oh,useDeferredValue:function(s,a){var c=zn();return Ah(c,s,a)},useTransition:function(){var s=Rh(!1);return s=B0.bind(null,Ge,s.queue,!0,!1),zn().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var d=Ge,p=zn();if(it){if(c===void 0)throw Error(r(407));c=c()}else{if(c=a(),Et===null)throw Error(r(349));(nt&127)!==0||b0(d,a,c)}p.memoizedState=c;var v={value:c,getSnapshot:a};return p.queue=v,L0(S0.bind(null,d,v,s),[s]),d.flags|=2048,Qi(9,{destroy:void 0},w0.bind(null,d,v,c,a),null),c},useId:function(){var s=zn(),a=Et.identifierPrefix;if(it){var c=Qs,d=Ys;c=(d&~(1<<32-xe(d)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Gc++,0<\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof d.is=="string"?C.createElement("select",{is:d.is}):C.createElement("select"),d.multiple?v.multiple=!0:d.size&&(v.size=d.size);break;default:v=typeof d.is=="string"?C.createElement(p,{is:d.is}):C.createElement(p)}}v[Ft]=a,v[_n]=d;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)v.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=v;e:switch(yn(v,p,d),p){case"button":case"input":case"select":case"textarea":d=!!d.autoFocus;break e;case"img":d=!0;break e;default:d=!1}d&&_r(a)}}return Rt(a),Qh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==d&&_r(a);else{if(typeof d!="string"&&a.stateNode===null)throw Error(r(166));if(s=re.current,Ui(a)){if(s=a.stateNode,c=a.memoizedProps,d=null,p=pn,p!==null)switch(p.tag){case 27:case 5:d=p.memoizedProps}s[Ft]=a,s=!!(s.nodeValue===c||d!==null&&d.suppressHydrationWarning===!0||yb(s.nodeValue,c)),s||Xr(a,!0)}else s=yu(s).createTextNode(d),s[Ft]=a,a.stateNode=s}return Rt(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(d=Ui(a),c!==null){if(s===null){if(!d)throw Error(r(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(r(557));s[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),s=!1}else c=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(is(a),a):(is(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Rt(a),null;case 13:if(d=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(p=Ui(a),d!==null&&d.dehydrated!==null){if(s===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else qa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Rt(a),p=!1}else p=ih(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(is(a),a):(is(a),null)}return is(a),(a.flags&128)!==0?(a.lanes=c,a):(c=d!==null,s=s!==null&&s.memoizedState!==null,c&&(d=a.child,p=null,d.alternate!==null&&d.alternate.memoizedState!==null&&d.alternate.memoizedState.cachePool!==null&&(p=d.alternate.memoizedState.cachePool.pool),v=null,d.memoizedState!==null&&d.memoizedState.cachePool!==null&&(v=d.memoizedState.cachePool.pool),v!==p&&(d.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),su(a,a.updateQueue),Rt(a),null);case 4:return Se(),s===null&&ym(a.stateNode.containerInfo),Rt(a),null;case 10:return wr(a.type),Rt(a),null;case 19:if(D(qt),d=a.memoizedState,d===null)return Rt(a),null;if(p=(a.flags&128)!==0,v=d.rendering,v===null)if(p)dl(d,!1);else{if(Ut!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(v=qc(s),v!==null){for(a.flags|=128,dl(d,!1),s=v.updateQueue,a.updateQueue=s,su(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Qy(c,s),c=c.sibling;return B(qt,qt.current&1|2),it&&xr(a,d.treeForkCount),a.child}s=s.sibling}d.tail!==null&&At()>lu&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304)}else{if(!p)if(s=qc(v),s!==null){if(a.flags|=128,p=!0,s=s.updateQueue,a.updateQueue=s,su(a,s),dl(d,!0),d.tail===null&&d.tailMode==="hidden"&&!v.alternate&&!it)return Rt(a),null}else 2*At()-d.renderingStartTime>lu&&c!==536870912&&(a.flags|=128,p=!0,dl(d,!1),a.lanes=4194304);d.isBackwards?(v.sibling=a.child,a.child=v):(s=d.last,s!==null?s.sibling=v:a.child=v,d.last=v)}return d.tail!==null?(s=d.tail,d.rendering=s,d.tail=s.sibling,d.renderingStartTime=At(),s.sibling=null,c=qt.current,B(qt,p?c&1|2:c&1),it&&xr(a,d.treeForkCount),s):(Rt(a),null);case 22:case 23:return is(a),xh(),d=a.memoizedState!==null,s!==null?s.memoizedState!==null!==d&&(a.flags|=8192):d&&(a.flags|=8192),d?(c&536870912)!==0&&(a.flags&128)===0&&(Rt(a),a.subtreeFlags&6&&(a.flags|=8192)):Rt(a),c=a.updateQueue,c!==null&&su(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==c&&(a.flags|=2048),s!==null&&D(Ka),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),wr(Qt),Rt(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Uk(s,a){switch(rh(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return wr(Qt),Se(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Me(a),null;case 31:if(a.memoizedState!==null){if(is(a),a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(is(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(r(340));qa()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return D(qt),null;case 4:return Se(),null;case 10:return wr(a.type),null;case 22:case 23:return is(a),xh(),s!==null&&D(Ka),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return wr(Qt),null;case 25:return null;default:return null}}function jx(s,a){switch(rh(a),a.tag){case 3:wr(Qt),Se();break;case 26:case 27:case 5:Me(a);break;case 4:Se();break;case 31:a.memoizedState!==null&&is(a);break;case 13:is(a);break;case 19:D(qt);break;case 10:wr(a.type);break;case 22:case 23:is(a),xh(),s!==null&&D(Ka);break;case 24:wr(Qt)}}function fl(s,a){try{var c=a.updateQueue,d=c!==null?c.lastEffect:null;if(d!==null){var p=d.next;c=p;do{if((c.tag&s)===s){d=void 0;var v=c.create,C=c.inst;d=v(),C.destroy=d}c=c.next}while(c!==p)}}catch(k){pt(a,a.return,k)}}function ra(s,a,c){try{var d=a.updateQueue,p=d!==null?d.lastEffect:null;if(p!==null){var v=p.next;d=v;do{if((d.tag&s)===s){var C=d.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,p=a;var F=c,ne=k;try{ne()}catch(ce){pt(p,F,ce)}}}d=d.next}while(d!==v)}}catch(ce){pt(a,a.return,ce)}}function Cx(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{m0(a,c)}catch(d){pt(s,s.return,d)}}}function _x(s,a,c){c.props=Wa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(d){pt(s,a,d)}}function hl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var d=s.stateNode;break;case 30:d=s.stateNode;break;default:d=s.stateNode}typeof c=="function"?s.refCleanup=c(d):c.current=d}}catch(p){pt(s,a,p)}}function Xs(s,a){var c=s.ref,d=s.refCleanup;if(c!==null)if(typeof d=="function")try{d()}catch(p){pt(s,a,p)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(p){pt(s,a,p)}else c.current=null}function Ex(s){var a=s.type,c=s.memoizedProps,d=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&d.focus();break e;case"img":c.src?d.src=c.src:c.srcSet&&(d.srcset=c.srcSet)}}catch(p){pt(s,s.return,p)}}function Xh(s,a,c){try{var d=s.stateNode;cR(d,s.type,c,a),d[_n]=a}catch(p){pt(s,s.return,p)}}function Nx(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&da(s.type)||s.tag===4}function Wh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Nx(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&da(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Jh(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=Qe));else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Jh(s,a,c),s=s.sibling;s!==null;)Jh(s,a,c),s=s.sibling}function ru(s,a,c){var d=s.tag;if(d===5||d===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(d!==4&&(d===27&&da(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(ru(s,a,c),s=s.sibling;s!==null;)ru(s,a,c),s=s.sibling}function kx(s){var a=s.stateNode,c=s.memoizedProps;try{for(var d=s.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);yn(a,d,c),a[Ft]=s,a[_n]=c}catch(v){pt(s,s.return,v)}}var Er=!1,Jt=!1,em=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,hn=null;function Vk(s,a){if(s=s.containerInfo,wm=_u,s=Uy(s),Kf(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&d.rangeCount!==0){c=d.anchorNode;var p=d.anchorOffset,v=d.focusNode;d=d.focusOffset;try{c.nodeType,v.nodeType}catch{c=null;break e}var C=0,k=-1,F=-1,ne=0,ce=0,fe=s,se=null;t:for(;;){for(var oe;fe!==c||p!==0&&fe.nodeType!==3||(k=C+p),fe!==v||d!==0&&fe.nodeType!==3||(F=C+d),fe.nodeType===3&&(C+=fe.nodeValue.length),(oe=fe.firstChild)!==null;)se=fe,fe=oe;for(;;){if(fe===s)break t;if(se===c&&++ne===p&&(k=C),se===v&&++ce===d&&(F=C),(oe=fe.nextSibling)!==null)break;fe=se,se=fe.parentNode}fe=oe}c=k===-1||F===-1?null:{start:k,end:F}}else c=null}c=c||{start:0,end:0}}else c=null;for(Sm={focusedElem:s,selectionRange:c},_u=!1,hn=a;hn!==null;)if(a=hn,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,hn=s;else for(;hn!==null;){switch(a=hn,v=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c title"))),yn(v,d,c),v[Ft]=s,Ht(v),d=v;break e;case"link":var C=zb("link","href",p).get(d+(c.href||""));if(C){for(var k=0;kbt&&(C=bt,bt=Pe,Pe=C);var J=Iy(k,Pe),G=Iy(k,bt);if(J&&G&&(oe.rangeCount!==1||oe.anchorNode!==J.node||oe.anchorOffset!==J.offset||oe.focusNode!==G.node||oe.focusOffset!==G.offset)){var te=fe.createRange();te.setStart(J.node,J.offset),oe.removeAllRanges(),Pe>bt?(oe.addRange(te),oe.extend(G.node,G.offset)):(te.setEnd(G.node,G.offset),oe.addRange(te))}}}}for(fe=[],oe=k;oe=oe.parentNode;)oe.nodeType===1&&fe.push({element:oe,left:oe.scrollLeft,top:oe.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kc?32:c,$.T=null,c=om,om=null;var v=la,C=Tr;if(ln=0,to=la=null,Tr=0,(ft&6)!==0)throw Error(r(331));var k=ft;if(ft|=4,Px(v.current),$x(v,v.current,C,c),ft=k,xl(0,!1),de&&typeof de.onPostCommitFiberRoot=="function")try{de.onPostCommitFiberRoot(W,v)}catch{}return!0}finally{q.p=p,$.T=d,rb(s,a)}}function ib(s,a,c){a=xs(c,a),a=Ph(s.stateNode,a,2),s=ta(s,a,2),s!==null&&(vt(s,2),Ws(s))}function pt(s,a,c){if(s.tag===3)ib(s,s,c);else for(;a!==null;){if(a.tag===3){ib(a,s,c);break}else if(a.tag===1){var d=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof d.componentDidCatch=="function"&&(oa===null||!oa.has(d))){s=xs(c,s),c=ox(2),d=ta(a,c,2),d!==null&&(lx(c,d,a,s),vt(d,2),Ws(d));break}}a=a.return}}function dm(s,a,c){var d=s.pingCache;if(d===null){d=s.pingCache=new Bk;var p=new Set;d.set(a,p)}else p=d.get(a),p===void 0&&(p=new Set,d.set(a,p));p.has(c)||(sm=!0,p.add(c),s=Qk.bind(null,s,a,c),a.then(s,s))}function Qk(s,a,c){var d=s.pingCache;d!==null&&d.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,Et===s&&(nt&c)===c&&(Ut===4||Ut===3&&(nt&62914560)===nt&&300>At()-ou?(ft&2)===0&&no(s,0):rm|=c,eo===nt&&(eo=0)),Ws(s)}function ob(s,a){a===0&&(a=$t()),s=Va(s,a),s!==null&&(vt(s,a),Ws(s))}function Xk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),ob(s,c)}function Wk(s,a){var c=0;switch(s.tag){case 31:case 13:var d=s.stateNode,p=s.memoizedState;p!==null&&(c=p.retryLane);break;case 19:d=s.stateNode;break;case 22:d=s.stateNode._retryCache;break;default:throw Error(r(314))}d!==null&&d.delete(a),ob(s,c)}function Jk(s,a){return sn(s,a)}var mu=null,ro=null,fm=!1,pu=!1,hm=!1,ua=0;function Ws(s){s!==ro&&s.next===null&&(ro===null?mu=ro=s:ro=ro.next=s),pu=!0,fm||(fm=!0,tR())}function xl(s,a){if(!hm&&pu){hm=!0;do for(var c=!1,d=mu;d!==null;){if(s!==0){var p=d.pendingLanes;if(p===0)var v=0;else{var C=d.suspendedLanes,k=d.pingedLanes;v=(1<<31-xe(42|s)+1)-1,v&=p&~(C&~k),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(c=!0,db(d,v))}else v=nt,v=Le(d,d===Et?v:0,d.cancelPendingCommit!==null||d.timeoutHandle!==-1),(v&3)===0||dt(d,v)||(c=!0,db(d,v));d=d.next}while(c);hm=!1}}function eR(){lb()}function lb(){pu=fm=!1;var s=0;ua!==0&&dR()&&(s=ua);for(var a=At(),c=null,d=mu;d!==null;){var p=d.next,v=cb(d,a);v===0?(d.next=null,c===null?mu=p:c.next=p,p===null&&(ro=c)):(c=d,(s!==0||(v&3)!==0)&&(pu=!0)),d=p}ln!==0&&ln!==5||xl(s),ua!==0&&(ua=0)}function cb(s,a){for(var c=s.suspendedLanes,d=s.pingedLanes,p=s.expirationTimes,v=s.pendingLanes&-62914561;0k)break;var ce=F.transferSize,fe=F.initiatorType;ce&&xb(fe)&&(F=F.responseEnd,C+=ce*(F"u"?null:document;function Tb(s,a,c){var d=ao;if(d&&typeof a=="string"&&a){var p=On(a);p='link[rel="'+s+'"][href="'+p+'"]',typeof c=="string"&&(p+='[crossorigin="'+c+'"]'),Mb.has(p)||(Mb.add(p),s={rel:s,crossOrigin:c,href:a},d.querySelector(p)===null&&(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function bR(s){Or.D(s),Tb("dns-prefetch",s,null)}function wR(s,a){Or.C(s,a),Tb("preconnect",s,a)}function SR(s,a,c){Or.L(s,a,c);var d=ao;if(d&&s&&a){var p='link[rel="preload"][as="'+On(a)+'"]';a==="image"&&c&&c.imageSrcSet?(p+='[imagesrcset="'+On(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(p+='[imagesizes="'+On(c.imageSizes)+'"]')):p+='[href="'+On(s)+'"]';var v=p;switch(a){case"style":v=io(s);break;case"script":v=oo(s)}_s.has(v)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),_s.set(v,s),d.querySelector(p)!==null||a==="style"&&d.querySelector(jl(v))||a==="script"&&d.querySelector(Cl(v))||(a=d.createElement("link"),yn(a,"link",s),Ht(a),d.head.appendChild(a)))}}function jR(s,a){Or.m(s,a);var c=ao;if(c&&s){var d=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+On(d)+'"][href="'+On(s)+'"]',v=p;switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=oo(s)}if(!_s.has(v)&&(s=g({rel:"modulepreload",href:s},a),_s.set(v,s),c.querySelector(p)===null)){switch(d){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Cl(v)))return}d=c.createElement("link"),yn(d,"link",s),Ht(d),c.head.appendChild(d)}}}function CR(s,a,c){Or.S(s,a,c);var d=ao;if(d&&s){var p=Gr(d).hoistableStyles,v=io(s);a=a||"default";var C=p.get(v);if(!C){var k={loading:0,preload:null};if(C=d.querySelector(jl(v)))k.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=_s.get(v))&&Rm(s,c);var F=C=d.createElement("link");Ht(F),yn(F,"link",s),F._p=new Promise(function(ne,ce){F.onload=ne,F.onerror=ce}),F.addEventListener("load",function(){k.loading|=1}),F.addEventListener("error",function(){k.loading|=2}),k.loading|=4,bu(C,a,d)}C={type:"stylesheet",instance:C,count:1,state:k},p.set(v,C)}}}function _R(s,a){Or.X(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function ER(s,a){Or.M(s,a);var c=ao;if(c&&s){var d=Gr(c).hoistableScripts,p=oo(s),v=d.get(p);v||(v=c.querySelector(Cl(p)),v||(s=g({src:s,async:!0,type:"module"},a),(a=_s.get(p))&&Mm(s,a),v=c.createElement("script"),Ht(v),yn(v,"link",s),c.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},d.set(p,v))}}function Ob(s,a,c,d){var p=(p=re.current)?xu(p):null;if(!p)throw Error(r(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=io(c.href),c=Gr(p).hoistableStyles,d=c.get(a),d||(d={type:"style",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=io(c.href);var v=Gr(p).hoistableStyles,C=v.get(s);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(s,C),(v=p.querySelector(jl(s)))&&!v._p&&(C.instance=v,C.state.loading=5),_s.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},_s.set(s,c),v||NR(p,s,c,C.state))),a&&d===null)throw Error(r(528,""));return C}if(a&&d!==null)throw Error(r(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=oo(c),c=Gr(p).hoistableScripts,d=c.get(a),d||(d={type:"script",instance:null,count:0,state:null},c.set(a,d)),d):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,s))}}function io(s){return'href="'+On(s)+'"'}function jl(s){return'link[rel="stylesheet"]['+s+"]"}function Ab(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function NR(s,a,c,d){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?d.loading=1:(a=s.createElement("link"),d.preload=a,a.addEventListener("load",function(){return d.loading|=1}),a.addEventListener("error",function(){return d.loading|=2}),yn(a,"link",c),Ht(a),s.head.appendChild(a))}function oo(s){return'[src="'+On(s)+'"]'}function Cl(s){return"script[async]"+s}function Db(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var d=s.querySelector('style[data-href~="'+On(c.href)+'"]');if(d)return a.instance=d,Ht(d),d;var p=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return d=(s.ownerDocument||s).createElement("style"),Ht(d),yn(d,"style",p),bu(d,c.precedence,s),a.instance=d;case"stylesheet":p=io(c.href);var v=s.querySelector(jl(p));if(v)return a.state.loading|=4,a.instance=v,Ht(v),v;d=Ab(c),(p=_s.get(p))&&Rm(d,p),v=(s.ownerDocument||s).createElement("link"),Ht(v);var C=v;return C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),a.state.loading|=4,bu(v,c.precedence,s),a.instance=v;case"script":return v=oo(c.src),(p=s.querySelector(Cl(v)))?(a.instance=p,Ht(p),p):(d=c,(p=_s.get(v))&&(d=g({},c),Mm(d,p)),s=s.ownerDocument||s,p=s.createElement("script"),Ht(p),yn(p,"link",d),s.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(d=a.instance,a.state.loading|=4,bu(d,c.precedence,s));return a.instance}function bu(s,a,c){for(var d=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=d.length?d[d.length-1]:null,v=p,C=0;C title"):null)}function kR(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function $b(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function RR(s,a,c,d){if(c.type==="stylesheet"&&(typeof d.media!="string"||matchMedia(d.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var p=io(d.href),v=a.querySelector(jl(p));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=Su.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=v,Ht(v);return}v=a.ownerDocument||a,d=Ab(d),(p=_s.get(p))&&Rm(d,p),v=v.createElement("link"),Ht(v);var C=v;C._p=new Promise(function(k,F){C.onload=k,C.onerror=F}),yn(v,"link",d),c.instance=v}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=Su.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var Tm=0;function MR(s,a){return s.stylesheets&&s.count===0&&Cu(s,s.stylesheets),0Tm?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(d),clearTimeout(p)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cu(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var ju=null;function Cu(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,ju=new Map,a.forEach(TR,s),ju=null,Su.call(s))}function TR(s,a){if(!(a.state.loading&4)){var c=ju.get(s);if(c)var d=c.get(null);else{c=new Map,ju.set(s,c);for(var p=s.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Pm.exports=XR(),Pm.exports}var JR=WR(),To=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},eM=class extends To{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Fg=new eM,tM={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nM=class{#e=tM;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},ai=new nM;function sM(e){setTimeout(e,0)}var rM=typeof window>"u"||"Deno"in globalThis;function Fn(){}function aM(e,t){return typeof e=="function"?e(t):e}function Rp(e){return typeof e=="number"&&e>=0&&e!==1/0}function HS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Sa(e,t){return typeof e=="function"?e(t):e}function us(e,t){return typeof e=="function"?e(t):e}function ow(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:l,queryKey:u,stale:f}=e;if(u){if(r){if(t.queryHash!==Ig(u,t.options))return!1}else if(!ql(t.queryKey,u))return!1}if(n!=="all"){const h=t.isActive();if(n==="active"&&!h||n==="inactive"&&h)return!1}return!(typeof f=="boolean"&&t.isStale()!==f||i&&i!==t.state.fetchStatus||l&&!l(t))}function lw(e,t){const{exact:n,status:r,predicate:i,mutationKey:l}=e;if(l){if(!t.options.mutationKey)return!1;if(n){if(di(t.options.mutationKey)!==di(l))return!1}else if(!ql(t.options.mutationKey,l))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ig(e,t){return(t?.queryKeyHashFn||di)(e)}function di(e){return JSON.stringify(e,(t,n)=>Mp(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function ql(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ql(e[n],t[n])):!1}var iM=Object.prototype.hasOwnProperty;function qS(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cw(e)&&cw(t);if(!r&&!(Mp(e)&&Mp(t)))return t;const l=(r?e:Object.keys(e)).length,u=r?t:Object.keys(t),f=u.length,h=r?new Array(f):{};let m=0;for(let y=0;y{ai.setTimeout(t,e)})}function Tp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?qS(e,t):t}function lM(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function cM(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pg=Symbol();function BS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ug(e,t){return typeof e=="function"?e(...t):!!e}function uM(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Bl=(()=>{let e=()=>rM;return{isServer(){return e()},setIsServer(t){e=t}}})();function Op(){let e,t;const n=new Promise((i,l)=>{e=i,t=l});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var dM=sM;function fM(){let e=[],t=0,n=f=>{f()},r=f=>{f()},i=dM;const l=f=>{t?e.push(f):i(()=>{n(f)})},u=()=>{const f=e;e=[],f.length&&i(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:f=>{let h;t++;try{h=f()}finally{t--,t||u()}return h},batchCalls:f=>(...h)=>{l(()=>{f(...h)})},schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:f=>{i=f}}}var dn=fM(),hM=class extends To{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},gd=new hM;function mM(e){return Math.min(1e3*2**e,3e4)}function GS(e){return(e??"online")==="online"?gd.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function KS(e){let t=!1,n=0,r;const i=Op(),l=()=>i.status!=="pending",u=S=>{if(!l()){const E=new Ap(S);w(E),e.onCancel?.(E)}},f=()=>{t=!0},h=()=>{t=!1},m=()=>Fg.isFocused()&&(e.networkMode==="always"||gd.isOnline())&&e.canRun(),y=()=>GS(e.networkMode)&&e.canRun(),g=S=>{l()||(r?.(),i.resolve(S))},w=S=>{l()||(r?.(),i.reject(S))},x=()=>new Promise(S=>{r=E=>{(l()||m())&&S(E)},e.onPause?.()}).then(()=>{r=void 0,l()||e.onContinue?.()}),j=()=>{if(l())return;let S;const E=n===0?e.initialPromise:void 0;try{S=E??e.fn()}catch(_){S=Promise.reject(_)}Promise.resolve(S).then(g).catch(_=>{if(l())return;const N=e.retry??(Bl.isServer()?0:3),R=e.retryDelay??mM,T=typeof R=="function"?R(n,_):R,A=N===!0||typeof N=="number"&&nm()?void 0:x()).then(()=>{t?w(_):j()})})};return{promise:i,status:()=>i.status,cancel:u,continue:()=>(r?.(),i),cancelRetry:f,continueRetry:h,canStart:y,start:()=>(y()?j():x().then(j),i)}}var ZS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Rp(this.gcTime)&&(this.#e=ai.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Bl.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ai.clearTimeout(this.#e),this.#e=void 0)}};function pM(e){return{onFetch:(t,n)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[];let f={pages:[],pageParams:[]},h=0;const m=async()=>{let y=!1;const g=j=>{uM(j,()=>t.signal,()=>y=!0)},w=BS(t.options,t.fetchOptions),x=async(j,S,E)=>{if(y)return Promise.reject(t.signal.reason);if(S==null&&j.pages.length)return Promise.resolve(j);const N=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};return g(M),M})(),R=await w(N),{maxPages:T}=t.options,A=E?cM:lM;return{pages:A(j.pages,R,T),pageParams:A(j.pageParams,S,T)}};if(i&&l.length){const j=i==="backward",S=j?YS:Dp,E={pages:l,pageParams:u},_=S(r,E);f=await x(E,_,j)}else{const j=e??l.length;do{const S=h===0?u[0]??r.initialPageParam:Dp(r,f);if(h>0&&S==null)break;f=await x(f,S),h++}while(ht.options.persister?.(m,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=m}}}function Dp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function YS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gM(e,t){return t?Dp(e,t)!=null:!1}function vM(e,t){return!t||!e.getPreviousPageParam?!1:YS(e,t)!=null}var yM=class extends ZS{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e){super(),this.#i=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#a=e.client,this.#s=this.#a.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=fw(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fw(this.options);t.data!==void 0&&(this.setState(dw(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Tp(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Fn).catch(Fn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>us(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Sa(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!HS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#i||this.#u()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#u(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const h=this.observers.find(m=>m.options.queryFn);h&&this.setOptions(h.options)}const n=new AbortController,r=h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},i=()=>{const h=BS(this.options,t),y=(()=>{const g={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(g),g})();return this.#i=!1,this.options.persister?this.options.persister(h,y,this):h(y)},u=(()=>{const h={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};return r(h),h})();(this.#e==="infinite"?pM(this.options.pages):this.options.behavior)?.onFetch(u,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==u.fetchOptions?.meta)&&this.#l({type:"fetch",meta:u.fetchOptions?.meta}),this.#r=KS({initialPromise:t?.initialPromise,fn:u.fetchFn,onCancel:h=>{h instanceof Ap&&h.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(h,m)=>{this.#l({type:"failed",failureCount:h,error:m})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0});try{const h=await this.#r.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#s.config.onSuccess?.(h,this),this.#s.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof Ap){if(h.silent)return this.#r.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#l({type:"error",error:h}),this.#s.config.onError?.(h,this),this.#s.config.onSettled?.(this.state.data,h,this),h}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...QS(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...dw(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?r:void 0,r;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),dn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function QS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:GS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dw(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fw(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var XS=class extends To{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Op(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#s=void 0;#a;#r;#o;#i;#u;#l;#m;#d;#f;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),hw(this.#t,this.options)?this.#h():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof us(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!pd(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&mw(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||Sa(this.options.staleTime,this.#t)!==Sa(t.staleTime,this.#t))&&this.#g();const i=this.#v();r&&(this.#t!==n||us(this.options.enabled,this.#t)!==us(t.enabled,this.#t)||i!==this.#c)&&this.#y(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return bM(this,n)&&(this.#s=n,this.#r=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Fn)),t}#g(){this.#b();const e=Sa(this.options.staleTime,this.#t);if(Bl.isServer()||this.#s.isStale||!Rp(e))return;const n=HS(this.#s.dataUpdatedAt,e)+1;this.#d=ai.setTimeout(()=>{this.#s.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(Bl.isServer()||us(this.options.enabled,this.#t)===!1||!Rp(this.#c)||this.#c===0)&&(this.#f=ai.setInterval(()=>{(this.options.refetchIntervalInBackground||Fg.isFocused())&&this.#h()},this.#c))}#x(){this.#g(),this.#y(this.#v())}#b(){this.#d!==void 0&&(ai.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#f!==void 0&&(ai.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){const n=this.#t,r=this.options,i=this.#s,l=this.#a,u=this.#r,h=e!==n?e.state:this.#n,{state:m}=e;let y={...m},g=!1,w;if(t._optimisticResults){const H=this.hasListeners(),U=!H&&hw(e,t),Z=H&&mw(e,n,t,r);(U||Z)&&(y={...y,...QS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:x,errorUpdatedAt:j,status:S}=y;w=y.data;let E=!1;if(t.placeholderData!==void 0&&w===void 0&&S==="pending"){let H;i?.isPlaceholderData&&t.placeholderData===u?.placeholderData?(H=i.data,E=!0):H=typeof t.placeholderData=="function"?t.placeholderData(this.#m?.state.data,this.#m):t.placeholderData,H!==void 0&&(S="success",w=Tp(i?.data,H,t),g=!0)}if(t.select&&w!==void 0&&!E)if(i&&w===l?.data&&t.select===this.#u)w=this.#l;else try{this.#u=t.select,w=t.select(w),w=Tp(i?.data,w,t),this.#l=w,this.#i=null}catch(H){this.#i=H}this.#i&&(x=this.#i,w=this.#l,j=Date.now(),S="error");const _=y.fetchStatus==="fetching",N=S==="pending",R=S==="error",T=N&&_,A=w!==void 0,L={status:S,fetchStatus:y.fetchStatus,isPending:N,isSuccess:S==="success",isError:R,isInitialLoading:T,isLoading:T,data:w,dataUpdatedAt:y.dataUpdatedAt,error:x,errorUpdatedAt:j,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:y.dataUpdateCount>h.dataUpdateCount||y.errorUpdateCount>h.errorUpdateCount,isFetching:_,isRefetching:_&&!N,isLoadingError:R&&!A,isPaused:y.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:R&&A,isStale:Vg(e,t),refetch:this.refetch,promise:this.#o,isEnabled:us(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const H=L.data!==void 0,U=L.status==="error"&&!H,Z=ae=>{U?ae.reject(L.error):H&&ae.resolve(L.data)},X=()=>{const ae=this.#o=L.promise=Op();Z(ae)},Q=this.#o;switch(Q.status){case"pending":e.queryHash===n.queryHash&&Z(Q);break;case"fulfilled":(U||L.data!==Q.value)&&X();break;case"rejected":(!U||L.error!==Q.reason)&&X();break}}return L}updateResult(){const e=this.#s,t=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#r=this.options,this.#a.data!==void 0&&(this.#m=this.#t),pd(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#p.size)return!0;const l=new Set(i??this.#p);return this.options.throwOnError&&l.add("error"),Object.keys(this.#s).some(u=>{const f=u;return this.#s[f]!==e[f]&&l.has(f)})};this.#j({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#j(e){dn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xM(e,t){return us(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&us(t.retryOnMount,e)===!1)}function hw(e,t){return xM(e,t)||e.state.data!==void 0&&zp(e,t,t.refetchOnMount)}function zp(e,t,n){if(us(t.enabled,e)!==!1&&Sa(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vg(e,t)}return!1}function mw(e,t,n,r){return(e!==t||us(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vg(e,n)}function Vg(e,t){return us(t.enabled,e)!==!1&&e.isStaleByTime(Sa(t.staleTime,e))}function bM(e,t){return!pd(e.getCurrentResult(),t)}var wM=class extends XS{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:l,isError:u,isRefetchError:f}=r,h=n.fetchMeta?.fetchMore?.direction,m=u&&h==="forward",y=i&&h==="forward",g=u&&h==="backward",w=i&&h==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:gM(t,n.data),hasPreviousPage:vM(t,n.data),isFetchNextPageError:m,isFetchingNextPage:y,isFetchPreviousPageError:g,isFetchingPreviousPage:w,isRefetchError:f&&!m&&!g,isRefetching:l&&!y&&!w}}},SM=class extends ZS{#e;#t;#n;#s;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||WS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#a({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=KS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(l,u)=>{this.#a({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#a({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",i=!this.#s.canStart();try{if(r)t();else{this.#a({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const u=await this.options.onMutate?.(e,n);u!==this.state.context&&this.#a({type:"pending",context:u,variables:e,isPaused:i})}const l=await this.#s.start();return await this.#n.config.onSuccess?.(l,e,this.state.context,this,n),await this.options.onSuccess?.(l,e,this.state.context,n),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(l,null,e,this.state.context,n),this.#a({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,e,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onError?.(l,e,this.state.context,n)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,n)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,l,e,this.state.context,n)}catch(u){Promise.reject(u)}throw this.#a({type:"error",error:l}),l}finally{this.#n.runNext(this)}}#a(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),dn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function WS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jM=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new SM({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Ou(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ou(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Ou(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){dn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>lw(t,n))}findAll(e={}){return this.getAll().filter(t=>lw(e,t))}notify(e){dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return dn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Fn))))}};function Ou(e){return e.options.scope?.id}var CM=class extends To{#e;#t=void 0;#n;#s;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),pd(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&di(n.mutationKey)!==di(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#r(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#a(),this.#r()}mutate(t,n){return this.#s=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#a(){const t=this.#n?.state??WS();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#r(t){dn.batch(()=>{if(this.#s&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#s.onSuccess?.(t.data,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(t.data,null,n,r,i)}catch(l){Promise.reject(l)}}else if(t?.type==="error"){try{this.#s.onError?.(t.error,n,r,i)}catch(l){Promise.reject(l)}try{this.#s.onSettled?.(void 0,t.error,n,r,i)}catch(l){Promise.reject(l)}}}this.listeners.forEach(n=>{n(this.#t)})})}},_M=class extends To{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,i=t.queryHash??Ig(r,t);let l=this.get(i);return l||(l=new yM({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){dn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>ow(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ow(e,n)):t}notify(e){dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){dn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){dn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},EM=class{#e;#t;#n;#s;#a;#r;#o;#i;constructor(e={}){this.#e=e.queryCache||new _M,this.#t=e.mutationCache||new jM,this.#n=e.defaultOptions||{},this.#s=new Map,this.#a=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Fg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Sa(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),l=this.#e.get(r.queryHash)?.state.data,u=aM(t,l);if(u!==void 0)return this.#e.build(this,r).setData(u,{...n,manual:!0})}setQueriesData(e,t,n){return dn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;dn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return dn.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=dn.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Fn).catch(Fn)}invalidateQueries(e,t={}){return dn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=dn.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let l=i.fetch(void 0,n);return n.throwOnError||(l=l.catch(Fn)),i.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(r).then(Fn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Sa(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Fn).catch(Fn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Fn).catch(Fn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(di(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ql(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#a.set(di(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(r=>{ql(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ig(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},JS=b.createContext(void 0),mn=e=>{const t=b.useContext(JS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},NM=({client:e,children:t})=>(b.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(JS.Provider,{value:e,children:t})),ej=b.createContext(!1),kM=()=>b.useContext(ej);ej.Provider;function RM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var MM=b.createContext(RM()),TM=()=>b.useContext(MM),OM=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?Ug(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},AM=e=>{b.useEffect(()=>{e.clearReset()},[e])},DM=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Ug(n,[e.error,r])),zM=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},LM=(e,t)=>e.isLoading&&e.isFetching&&!t,$M=(e,t)=>e?.suspense&&t.isPending,pw=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tj(e,t,n){const r=kM(),i=TM(),l=mn(),u=l.defaultQueryOptions(e);l.getDefaultOptions().queries?._experimental_beforeQuery?.(u);const f=l.getQueryCache().get(u.queryHash),h=e.subscribed!==!1;u._optimisticResults=r?"isRestoring":h?"optimistic":void 0,zM(u),OM(u,i,f),AM(i);const m=!l.getQueryCache().get(u.queryHash),[y]=b.useState(()=>new t(l,u)),g=y.getOptimisticResult(u),w=!r&&h;if(b.useSyncExternalStore(b.useCallback(x=>{const j=w?y.subscribe(dn.batchCalls(x)):Fn;return y.updateResult(),j},[y,w]),()=>y.getCurrentResult(),()=>y.getCurrentResult()),b.useEffect(()=>{y.setOptions(u)},[u,y]),$M(u,g))throw pw(u,y,i);if(DM({result:g,errorResetBoundary:i,throwOnError:u.throwOnError,query:f,suspense:u.suspense}))throw g.error;return l.getDefaultOptions().queries?._experimental_afterQuery?.(u,g),u.experimental_prefetchInRender&&!Bl.isServer()&&LM(g,r)&&(m?pw(u,y,i):f?.promise)?.catch(Fn).finally(()=>{y.updateResult()}),u.notifyOnChangeProps?g:y.trackResult(g)}function rt(e,t){return tj(e,XS)}function FM(e,t){const n=mn(),[r]=b.useState(()=>new CM(n,e));b.useEffect(()=>{r.setOptions(e)},[r,e]);const i=b.useSyncExternalStore(b.useCallback(u=>r.subscribe(dn.batchCalls(u)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),l=b.useCallback((u,f)=>{r.mutate(u,f).catch(Fn)},[r]);if(i.error&&Ug(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:l,mutateAsync:i.mutate}}function IM(e,t){return tj(e,wM)}let gw=!1;function PM(e){const t=e.analytics;if(!t?.key||gw)return;gw=!0;const n=document.createElement("script");n.src=t.host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",n.async=!0,n.onload=()=>{const r=window.posthog;r&&(r.init(t.key,{api_host:t.host,defaults:"2026-05-30",capture_pageview:"history_change",session_recording:{maskAllInputs:!0,maskTextSelector:"*"}}),e.me&&r.identify(e.me.email,{email:e.me.email,name:e.me.name,...e.billing?{plan:e.billing.plan}:{}}))},document.head.appendChild(n)}function nj(e,t){window.posthog?.capture(e,t)}const UM=[[/^POST \/api\/projects$/,"project_created"],[/^DELETE \/api\/projects\//,"project_deleted"],[/^POST \/api\/p\/[^/]+\/restore$/,"file_restored"],[/^DELETE \/api\/shares\//,"share_revoked"],[/^PATCH \/api\/shares\//,"share_expiry_changed"],[/^POST \/api\/orgs\/[^/]+\/invites$/,"invite_created"],[/^DELETE \/api\/orgs\/[^/]+\/invites\//,"invite_revoked"],[/^POST \/api\/invites\//,"invite_accepted"],[/^PUT \/api\/p\/[^/]+\/permissions\/./,"project_access_granted"],[/^DELETE \/api\/p\/[^/]+\/permissions\/./,"project_access_revoked"],[/^POST \/api\/p\/[^/]+\/comments$/,"comment_created"],[/^POST \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_updated"],[/^DELETE \/api\/p\/[^/]+\/comments\/[^/]+$/,"comment_deleted"]];function Hd(e,t){const n=e+" "+t.split("?")[0],r=UM.find(([i])=>i.test(n));r&&nj(r[1])}const vw="bdrive:login-bounce",VM=3e4;function qd(){let e=0;try{e=Number(sessionStorage.getItem(vw)||0)}catch{}if(e&&Date.now()-e=500?"The server had a problem. Try again.":n?n[0].toUpperCase()+n.slice(1):"Something went wrong."}}class Hg extends Error{constructor(t,n,r=""){super(n),this.status=t,this.body=r,this.name="HttpError"}status;body}async function Oo(e){const t=await e.text();throw new Hg(e.status,HM(e.status,t),t)}async function We(e){const t=await fetch(e,{headers:{Accept:"application/json"}});return t.status===401&&qd(),t.ok||await Oo(t),t.json()}async function qM(e){const t=await fetch(e);return t.status===401&&qd(),t.ok||await Oo(t),t}async function en(e,t,n){const r={method:e};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const i=await fetch(t,r);return i.ok||await Oo(i),Hd(e,t),i.status===204?{}:i.json()}async function vd(e,t){const n=await fetch(e,{method:"POST",headers:{"X-Bdrive-Desktop":"1","Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)});return n.ok&&Hd("POST",e),n}async function Sn(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});return n.status===401&&qd(),n.ok||await Oo(n),Hd("POST",e),n.json()}async function BM(e,t,n,r=!1,i=!1,l=!1,u=!1){const f=await fetch(e,{method:"PUT",headers:{"Content-Type":"text/plain; charset=utf-8",...n?{"If-Match":n}:{},...u?{"If-None-Match":"*"}:{},...r?{"X-Bdrive-Confirm-Shrink":"1"}:{},...l?{"X-Bdrive-Park-On-Conflict":"1"}:{}},body:t,keepalive:!!(i&&new TextEncoder().encode(t).byteLength<=sj)});return f.status===401&&!i&&qd(),f.ok||await Oo(f),Hd("PUT",e),await f.json().catch(()=>({}))}const sj=6e4;async function PB(e,t,n=!1){const r=JSON.stringify(t),i=new TextEncoder().encode(r).byteLength,l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!!(n&&i<=sj)});return l.ok||await Oo(l),await l.json()}let Lp=null;function GM(){Lp??=We("/api/config")}function KM(){return rt({queryKey:["config"],queryFn:async()=>{const e=Lp;Lp=null;const t=await(e??We("/api/config"));if(t.auth.enabled&&!t.me){const n="bdrive:login-bounce";let r=0;try{r=Number(sessionStorage.getItem(n)||0)}catch{}if(r&&Date.now()-r<3e4)throw new Error("The server does not recognise your session, and signing in again did not help. It is probably having a bad moment — wait a few seconds and reload.");try{sessionStorage.setItem(n,String(Date.now()))}catch{}location.href="/auth/login?next="+encodeURIComponent(location.pathname+location.search),await new Promise(()=>{})}return PM(t),t},staleTime:1/0})}var rc=VS();const ZM=PS(rc);function yw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Eo(...e){return t=>{let n=!1;const r=e.map(i=>{const l=yw(i,t);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let i=0;i{let{children:i,...l}=n,u=null,f=!1;const h=[];xw(i)&&typeof Au=="function"&&(i=Au(i._payload)),b.Children.forEach(i,w=>{if(eT(w)){f=!0;const x=w;let j="child"in x.props?x.props.child:x.props.children;xw(j)&&typeof Au=="function"&&(j=Au(j._payload)),u=XM(x,j),h.push(u?.props?.children)}else h.push(w)}),u?u=b.cloneElement(u,void 0,h):!f&&b.Children.count(i)===1&&b.isValidElement(i)&&(u=i);const m=u?JM(u):void 0,y=Zt(r,m);if(!u){if(i||i===0)throw new Error(f?rT(e):sT(e));return i}const g=WM(l,u.props??{});return u.type!==b.Fragment&&(g.ref=r?y:m),b.cloneElement(u,g)});return t.displayName=`${e}.Slot`,t}var YM=No("Slot"),rj=Symbol.for("radix.slottable");function QM(e){const t=n=>"child"in n?n.children(n.child):n.children;return t.displayName=`${e}.Slottable`,t.__radixId=rj,t}var XM=(e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null};function WM(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...f)=>{const h=l(...f);return i(...f),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function JM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function eT(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===rj}var tT=Symbol.for("react.lazy");function xw(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tT&&"_payload"in e&&nT(e._payload)}function nT(e){return typeof e=="object"&&e!==null&&"then"in e}var sT=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,rT=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Au=Vd[" use ".trim().toString()],aT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=aT.reduce((e,t)=>{const n=No(`Primitive.${t}`),r=b.forwardRef((i,l)=>{const{asChild:u,...f}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...f,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function aj(e,t){e&&rc.flushSync(()=>e.dispatchEvent(t))}var iT=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),oT="VisuallyHidden",ij=b.forwardRef((e,t)=>o.jsx(lt.span,{...e,ref:t,style:{...iT,...e.style}}));ij.displayName=oT;var lT=ij;function Na(e,t=[]){let n=[];function r(l,u){const f=b.createContext(u);f.displayName=l+"Context";const h=n.length;n=[...n,u];const m=g=>{const{scope:w,children:x,...j}=g,S=w?.[e]?.[h]||f,E=b.useMemo(()=>j,Object.values(j));return o.jsx(S.Provider,{value:E,children:x})};m.displayName=l+"Provider";function y(g,w,x={}){const{optional:j=!1}=x,S=w?.[e]?.[h]||f,E=b.useContext(S);if(E)return E;if(u!==void 0)return u;if(!j)throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,y]}const i=()=>{const l=n.map(u=>b.createContext(u));return function(f){const h=f?.[e]||l;return b.useMemo(()=>({[`__scope${e}`]:{...f,[e]:h}}),[f,h])}};return i.scopeName=e,[r,cT(i,...t)]}function cT(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((f,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...f,...g}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}function oj(e){const t=e+"CollectionProvider",[n,r]=Na(t),[i,l]=n(t,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:E,children:_}=S,N=b.useRef(null),R=b.useRef(new Map).current;return o.jsx(i,{scope:E,itemMap:R,collectionRef:N,children:_})};u.displayName=t;const f=e+"CollectionSlot",h=No(f),m=b.forwardRef((S,E)=>{const{scope:_,children:N}=S,R=l(f,_),T=Zt(E,R.collectionRef);return o.jsx(h,{ref:T,children:N})});m.displayName=f;const y=e+"CollectionItemSlot",g="data-radix-collection-item",w=No(y),x=b.forwardRef((S,E)=>{const{scope:_,children:N,...R}=S,T=b.useRef(null),A=Zt(E,T),M=l(y,_);return b.useEffect(()=>(M.itemMap.set(T,{ref:T,...R}),()=>{M.itemMap.delete(T)})),o.jsx(w,{[g]:"",ref:A,children:N})});x.displayName=y;function j(S){const E=l(e+"CollectionConsumer",S);return b.useCallback(()=>{const N=E.collectionRef.current;if(!N)return[];const R=Array.from(N.querySelectorAll(`[${g}]`));return Array.from(E.itemMap.values()).sort((M,L)=>R.indexOf(M.ref.current)-R.indexOf(L.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:m,ItemSlot:x},j,r]}function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)}}var ar=globalThis?.document?b.useLayoutEffect:()=>{},uT=Vd[" useInsertionEffect ".trim().toString()]||ar;function ac({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=dT({defaultProp:t,onChange:n}),f=e!==void 0,h=f?e:i;{const y=b.useRef(e!==void 0);b.useEffect(()=>{const g=y.current;g!==f&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${f?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=f},[f,r])}const m=b.useCallback(y=>{if(f){const g=fT(y)?y(e):y;g!==e&&u.current?.(g)}else l(y)},[f,e,l,u]);return[h,m]}function dT({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),l=b.useRef(t);return uT(()=>{l.current=t},[t]),b.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function fT(e){return typeof e=="function"}function hT(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}var dr=e=>{const{present:t,children:n}=e,r=mT(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),l=pT(r.ref,gT(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:l}):null};dr.displayName="Presence";function mT(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),l=b.useRef("none"),u=b.useRef(void 0),f=e?"mounted":"unmounted",[h,m]=hT(f,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{h==="mounted"?(l.current=u.current??Tl(r.current),u.current=void 0):l.current="none"},[h]),ar(()=>{const y=r.current,g=i.current;if(g!==e){const x=l.current,j=Tl(y);e?(u.current=j,m("MOUNT")):j==="none"||y?.display==="none"?m("UNMOUNT"):m(g&&x!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,m]),ar(()=>{if(t){let y;const g=t.ownerDocument.defaultView??window,w=j=>{const E=Tl(r.current).includes(CSS.escape(j.animationName));if(j.target===t&&E&&(m("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",y=g.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},x=j=>{j.target===t&&(l.current=Tl(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",w),t.addEventListener("animationend",w),()=>{g.clearTimeout(y),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",w),t.removeEventListener("animationend",w)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:b.useCallback(y=>{if(y){const g=getComputedStyle(y);r.current=g,u.current=Tl(g)}else r.current=null;n(y)},[])}}function bw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pT(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const l=r.map(u=>{const f=bw(u,n);return!i&&typeof f=="function"&&(i=!0),f});if(i)return()=>{for(let u=0;u{}),yT=0;function ds(e){const[t,n]=b.useState(vT());return ar(()=>{n(r=>r??String(yT++))},[e]),t?`radix-${t}`:""}var xT=b.createContext(void 0);function lj(e){const t=b.useContext(xT);return e||t||"ltr"}function Pr(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>t.current?.(...n)),[])}var bT="DismissableLayer",$p="dismissableLayer.update",wT="dismissableLayer.pointerDownOutside",ST="dismissableLayer.focusOutside",ww,qg=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Bd=b.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,onDismiss:h,...m}=e,y=b.useContext(qg),[g,w]=b.useState(null),x=g?.ownerDocument??globalThis?.document,[,j]=b.useState({}),S=Zt(t,w),E=Array.from(y.layers),[_]=[...y.layersWithOutsidePointerEventsDisabled].slice(-1),N=_?E.indexOf(_):-1,R=g?E.indexOf(g):-1,T=y.layersWithOutsidePointerEventsDisabled.size>0,A=R>=N,M=b.useRef(!1),L=NT(X=>{l?.(X),f?.(X),X.defaultPrevented||h?.()},{ownerDocument:x,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:y.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(X=>{if(!(X instanceof Node))return!1;const Q=[...y.branches].some(ae=>ae.contains(X));return A&&!Q},[y.branches,A])}),H=kT(X=>{if(r&&M.current)return;const Q=X.target;[...y.branches].some(le=>le.contains(Q))||(u?.(X),f?.(X),X.defaultPrevented||h?.())},x),U=g?R===E.length-1:!1,Z=Pr(X=>{X.key==="Escape"&&(i?.(X),!X.defaultPrevented&&h&&(X.preventDefault(),h()))});return b.useEffect(()=>{if(U)return x.addEventListener("keydown",Z,{capture:!0}),()=>x.removeEventListener("keydown",Z,{capture:!0})},[x,U,Z]),b.useEffect(()=>{if(g)return n&&(y.layersWithOutsidePointerEventsDisabled.size===0&&(ww=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),y.layersWithOutsidePointerEventsDisabled.add(g)),y.layers.add(g),Sw(),()=>{n&&(y.layersWithOutsidePointerEventsDisabled.delete(g),y.layersWithOutsidePointerEventsDisabled.size===0&&(x.body.style.pointerEvents=ww))}},[g,x,n,y]),b.useEffect(()=>()=>{g&&(y.layers.delete(g),y.layersWithOutsidePointerEventsDisabled.delete(g),Sw())},[g,y]),b.useEffect(()=>{const X=()=>j({});return document.addEventListener($p,X),()=>document.removeEventListener($p,X)},[]),o.jsx(lt.div,{...m,ref:S,style:{pointerEvents:T?A?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,L.onPointerDownCapture)})});Bd.displayName=bT;var jT="DismissableLayerBranch",CT=b.forwardRef((e,t)=>{const n=b.useContext(qg),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(lt.div,{...e,ref:i})});CT.displayName=jT;function _T(){const e=b.useContext(qg),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var ET=()=>!0;function NT(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:l,shouldHandlePointerDownOutside:u=ET}=t,f=Pr(e),h=b.useRef(!1),m=b.useRef(!1),y=b.useRef(new Map),g=b.useRef(()=>{});return b.useEffect(()=>{function w(){m.current=!1,i.current=!1,y.current.clear()}function x(){return Array.from(y.current.values()).some(Boolean)}function j(R){if(!m.current)return;const T=R.target;T instanceof Node&&[...l].some(M=>M.contains(T))||y.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{m.current&&g.current()},0)}function S(R){m.current&&y.current.set(R.type,!1)}const E=R=>{if(R.target&&!h.current){let T=function(){n.removeEventListener("click",g.current);const M=x();w(),M||cj(wT,f,A,{discrete:!0})};if(!u(R.target)){n.removeEventListener("click",g.current),w(),h.current=!1;return}const A={originalEvent:R};m.current=!0,i.current=r&&R.button===0,y.current.clear(),!r||R.button!==0?T():(n.removeEventListener("click",g.current),g.current=T,n.addEventListener("click",g.current,{once:!0}))}else n.removeEventListener("click",g.current),w();h.current=!1},_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of _)n.addEventListener(R,j,!0),n.addEventListener(R,S);const N=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(N),n.removeEventListener("pointerdown",E),n.removeEventListener("click",g.current);for(const R of _)n.removeEventListener(R,j,!0),n.removeEventListener(R,S)}},[n,f,r,i,l,u]),{onPointerDownCapture:()=>h.current=!0}}function kT(e,t=globalThis?.document){const n=Pr(e),r=b.useRef(!1);return b.useEffect(()=>{const i=l=>{l.target&&!r.current&&cj(ST,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Sw(){const e=new CustomEvent($p);document.dispatchEvent(e)}function cj(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?aj(i,l):i.dispatchEvent(l)}var qm="focusScope.autoFocusOnMount",Bm="focusScope.autoFocusOnUnmount",jw={bubbles:!1,cancelable:!0},RT="FocusScope",Bg=b.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[f,h]=b.useState(null),m=Pr(i),y=Pr(l),g=b.useRef(null),w=Zt(t,h),x=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let S=function(R){if(x.paused||!f)return;const T=R.target;f.contains(T)?g.current=T:xa(g.current,{select:!0})},E=function(R){if(x.paused||!f)return;const T=R.relatedTarget;T!==null&&(f.contains(T)||xa(g.current,{select:!0}))},_=function(R){if(document.activeElement===document.body)for(const A of R)A.removedNodes.length>0&&xa(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",E);const N=new MutationObserver(_);return f&&N.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",E),N.disconnect()}}},[r,f,x.paused]),b.useEffect(()=>{if(f){_w.add(x);const S=document.activeElement;if(!f.contains(S)){const _=new CustomEvent(qm,jw);f.addEventListener(qm,m),f.dispatchEvent(_),_.defaultPrevented||(MT(zT(uj(f)),{select:!0}),document.activeElement===S&&xa(f))}return()=>{f.removeEventListener(qm,m),setTimeout(()=>{const _=new CustomEvent(Bm,jw);f.addEventListener(Bm,y),f.dispatchEvent(_),_.defaultPrevented||xa(S??document.body,{select:!0}),f.removeEventListener(Bm,y),_w.remove(x)},0)}}},[f,m,y,x]);const j=b.useCallback(S=>{if(!n&&!r||x.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const N=S.currentTarget,[R,T]=TT(N);R&&T?!S.shiftKey&&_===T?(S.preventDefault(),n&&xa(R,{select:!0})):S.shiftKey&&_===R&&(S.preventDefault(),n&&xa(T,{select:!0})):_===N&&S.preventDefault()}},[n,r,x.paused]);return o.jsx(lt.div,{tabIndex:-1,...u,ref:w,onKeyDown:j})});Bg.displayName=RT;function MT(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(xa(r,{select:t}),document.activeElement!==n)return}function TT(e){const t=uj(e),n=Cw(t,e),r=Cw(t.reverse(),e);return[n,r]}function uj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cw(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):OT(r,{upTo:t})))return r}function OT(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function AT(e){return e instanceof HTMLInputElement&&"select"in e}function xa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&AT(e)&&t&&e.select()}}var _w=DT();function DT(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Ew(e,t),e.unshift(t)},remove(t){e=Ew(e,t),e[0]?.resume()}}}function Ew(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zT(e){return e.filter(t=>t.tagName!=="A")}var LT="Portal",Gd=b.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=b.useState(!1);ar(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?rc.createPortal(o.jsx(lt.div,{...r,ref:t}),u):null});Gd.displayName=LT;var Du=0,co=null;function dj(){b.useEffect(()=>{co||(co={start:Nw(),end:Nw()});const{start:e,end:t}=co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Du++,()=>{Du===1&&(co?.start.remove(),co?.end.remove(),co=null),Du=Math.max(0,Du-1)}},[])}function Nw(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var sr=function(){return sr=Object.assign||function(t){for(var n,r=1,i=arguments.length;r"u")return JT;var t=eO(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},nO=pj(),So="data-scroll-locked",sO=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,f=e.gap;return n===void 0&&(n="margin"),`
   .`.concat(FT,` {
    overflow: hidden `).concat(r,`;
    padding-right: `).concat(f,"px ").concat(r,`;
@@ -47,10 +47,10 @@ Error generating stack: `+d.message+`
 `)},Rw=function(){var e=parseInt(document.body.getAttribute(So)||"0",10);return isFinite(e)?e:0},rO=function(){b.useEffect(function(){return document.body.setAttribute(So,(Rw()+1).toString()),function(){var e=Rw()-1;e<=0?document.body.removeAttribute(So):document.body.setAttribute(So,e.toString())}},[])},aO=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;rO();var l=b.useMemo(function(){return tO(i)},[i]);return b.createElement(nO,{styles:sO(l,!t,i,n?"":"!important")})},Fp=!1;if(typeof window<"u")try{var zu=Object.defineProperty({},"passive",{get:function(){return Fp=!0,!0}});window.addEventListener("test",zu,zu),window.removeEventListener("test",zu,zu)}catch{Fp=!1}var uo=Fp?{passive:!1}:!1,iO=function(e){return e.tagName==="TEXTAREA"},gj=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!iO(e)&&n[t]==="visible")},oO=function(e){return gj(e,"overflowY")},lO=function(e){return gj(e,"overflowX")},Mw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=vj(e,r);if(i){var l=yj(e,r),u=l[1],f=l[2];if(u>f)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},cO=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},uO=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vj=function(e,t){return e==="v"?oO(t):lO(t)},yj=function(e,t){return e==="v"?cO(t):uO(t)},dO=function(e,t){return e==="h"&&t==="rtl"?-1:1},fO=function(e,t,n,r,i){var l=dO(e,window.getComputedStyle(t).direction),u=l*r,f=n.target,h=t.contains(f),m=!1,y=u>0,g=0,w=0;do{if(!f)break;var x=yj(e,f),j=x[0],S=x[1],E=x[2],_=S-E-l*j;(j||_)&&vj(e,f)&&(g+=_,w+=j);var N=f.parentNode;f=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!h&&f!==document.body||h&&(t.contains(f)||t===f));return(y&&Math.abs(g)<1||!y&&Math.abs(w)<1)&&(m=!0),m},Lu=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Tw=function(e){return[e.deltaX,e.deltaY]},Ow=function(e){return e&&"current"in e?e.current:e},hO=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mO=function(e){return`
   .block-interactivity-`.concat(e,` {pointer-events: none;}
   .allow-interactivity-`).concat(e,` {pointer-events: all;}
-`)},pO=0,fo=[];function gO(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(pO++)[0],l=b.useState(pj)[0],u=b.useRef(e);b.useEffect(function(){u.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var S=$T([e.lockRef.current],(e.shards||[]).map(Ow),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var f=b.useCallback(function(S,E){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var _=Lu(S),N=n.current,R="deltaX"in S?S.deltaX:N[0]-_[0],T="deltaY"in S?S.deltaY:N[1]-_[1],A,M=S.target,L=Math.abs(R)>Math.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return fO(Q,E,S,Q==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!fo.length||fo[fo.length-1]!==l)){var _="deltaY"in E?Tw(E):Lu(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=Lu(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,Lu(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return fo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,uo),document.addEventListener("touchmove",h,uo),document.addEventListener("touchstart",y,uo),function(){fo=fo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,uo),document.removeEventListener("touchmove",h,uo),document.removeEventListener("touchstart",y,uo)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Gg=b.forwardRef(function(e,t){return b.createElement(Kd,sr({},e,{ref:t,sideCar:yO}))});Gg.classNames=Kd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ho=new WeakMap,$u=new WeakMap,Fu={},Ym=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Fu[n]||(Fu[n]=new WeakMap);var l=Fu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(ho.get(w)||0)+1,E=(l.get(w)||0)+1;ho.set(w,S),l.set(w,E),u.push(w),S===1&&j&&$u.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Ym++,function(){u.forEach(function(g){var w=ho.get(g)-1,x=l.get(g)-1;ho.set(g,w),l.set(g,x),w||($u.has(g)||g.removeAttribute(r),$u.delete(g)),x||g.removeAttribute(n)}),Ym--,Ym||(ho=new WeakMap,ho=new WeakMap,$u=new WeakMap,Fu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Zd="Dialog",[wj]=Na(Zd),[SO,Vs]=wj(Zd),Kg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=ac({prop:r,defaultProp:i??!1,onChange:l,caller:Zd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:ds(),titleId:ds(),descriptionId:ds(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Kg.displayName=Zd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Sj,n),l=Zt(t,i.triggerRef);return o.jsx(lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Wg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Zg="DialogPortal",[CO,jj]=wj(Zg,{forceMount:void 0}),Yg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Zg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:u})}))})};Yg.displayName=Zg;var yd="DialogOverlay",Qg=b.forwardRef((e,t)=>{const n=jj(yd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(yd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Qg.displayName=yd;var _O=No("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(yd,n),l=_T(),u=Zt(t,l);return o.jsx(Gg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(lt.div,{"data-state":Wg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),ko="DialogContent",Xg=b.forwardRef((e,t)=>{const n=jj(ko,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(ko,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Xg.displayName=ko;var NO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(null),i=Zt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(ko,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(Bg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Bd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Wg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(_j,n);return o.jsx(lt.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Nj,n);return o.jsx(lt.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Rj,n);return o.jsx(lt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Wg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],ja=Math.min,$r=Math.max,xd=Math.round,Iu=Math.floor,Fr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return $r(e,ja(t,n))}function Ur(e,t){return typeof e=="function"?e(t):e}function Ca(e){return e.split("-")[0]}function Ao(e){return e.split("-")[1]}function Jg(e){return e==="x"?"y":"x"}function ev(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function tv(e){return Jg(rr(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ao(e),i=tv(e),l=ev(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=bd(u)),[u,bd(u)]}function AO(e){const t=bd(e);return[Ip(e),t,Ip(t)]}function Ip(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ao(e);let l=LO(Ca(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Ip)))),l}function bd(e){const t=Ca(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function wd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=tv(t),f=ev(u),h=Ca(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ao(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Ur(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=wd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=wd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ur(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=tv(i),j=ev(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=ja(g[_],U),X=ja(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Q),be=!h.arrow&&Ao(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ur(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ca(n),f=Ao(n),h=rr(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Ur(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ur(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=rr(i),x=Jg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ur(e,t),w={x:i,y:l},x=rr(u),j=Jg(x);let S=w[j],E=w[x];const _=Ur(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ca(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ur(e,t),h=await i.detectOverflow(t,f),m=Ca(n),y=Ao(n),g=rr(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=ja(x-h[j],E),R=ja(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*$r(h.left,h.right):M=x-2*$r(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Yd(){return typeof window<"u"}function Do(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Hr(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Yd()?e instanceof Node||e instanceof Jn(e).Node:!1}function lr(e){return Yd()?e instanceof Element||e instanceof Jn(e).Element:!1}function ka(e){return Yd()?e instanceof HTMLElement||e instanceof Jn(e).HTMLElement:!1}function Fw(e){return!Yd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Jn(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Do(e))}function Xd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ti=e=>!!e&&e!=="none";let Qm;function nv(e){const t=lr(e)?cr(e):e;return ti(t.transform)||ti(t.translate)||ti(t.scale)||ti(t.rotate)||ti(t.perspective)||!sv()&&(ti(t.backdropFilter)||ti(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=fi(e);for(;ka(t)&&!Gl(t);){if(nv(t))return t;if(Xd(t))return null;t=fi(t)}return null}function sv(){return Qm==null&&(Qm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Qm}function Gl(e){return/^(html|body|#document)$/.test(Do(e))}function cr(e){return Jn(e).getComputedStyle(e)}function Wd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fi(e){if(Do(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Hr(e);return Fw(t)?t.host:t}function zj(e){const t=fi(e);return Gl(t)?(e.ownerDocument||e).body:ka(t)&&Qd(t)?t:zj(t)}function Kl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Jn(i);if(l){const f=Pp(u);return t.concat(u,u.visualViewport||[],Qd(i)?i:[],f&&n?Kl(f):[])}else return t.concat(i,Kl(i,[],n))}function Pp(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=ka(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=xd(n)!==l||xd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function rv(e){return lr(e)?e:e.contextElement}function jo(e){const t=rv(e);if(!ka(t))return Fr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?xd(n.width):n.width)/r,f=(l?xd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Fr(0);function $j(e){const t=Jn(e);return!sv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Jn(e)}function hi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=rv(e);let u=Fr(1);t&&(r?lr(r)&&(u=jo(r)):u=jo(e));const f=tA(l,n,r)?$j(l):Fr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Jn(l),x=lr(r)?Jn(r):r;let j=w,S=Pp(j);for(;S&&x!==j;){const E=jo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Jn(S),S=Pp(j)}}return wd({width:y,height:g,x:h,y:m})}function Jd(e,t){const n=Wd(e).scrollLeft;return t?t.left+n:hi(Hr(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Jd(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Hr(r),f=t?Xd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Fr(1);const y=Fr(0),g=ka(r);if((g||!l)&&((Do(r)!=="body"||Qd(u))&&(h=Wd(r)),g)){const x=hi(r);m=jo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Fr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Wd(e),n=e.ownerDocument.body,r=$r(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=$r(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+Jd(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=$r(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Jn(e),l=Hr(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!sv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(Jd(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=hi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=jo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Hr(e));else if(lr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Kl(e,[],!1).filter(f=>lr(f)&&Do(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?fi(e):e;for(;lr(u)&&!Gl(u);){const f=cr(u),h=nv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=fi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Xd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Jn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=rv(e),y=i||l?[...m?Kl(m):[],...t?Kl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?hi(e):null;h&&E();function E(){const _=hi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},rd=CA?b.useLayoutEffect:_A;function Sd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Sd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!Sd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Wm(e){const t=b.useRef(e);return rd(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);Sd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Wm(h),X=Wm(i),Q=Wm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};X.current&&(V.platform=X.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!Sd(H.current,K)&&(H.current=K,rc.flushSync(()=>{g(K)}))})},[w,t,n,X,Q]);rd(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);rd(()=>(le.current=!0,()=>{le.current=!1}),[]),rd(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(lt.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,av="Popper",[Hj,ef]=Na(av),[$A,qj]=Hj(av),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=av;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Zt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&ov(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(lt.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var iv="PopperContent",[FA,IA]=Hj(iv),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(iv,n),[_,N]=b.useState(null),R=Zt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(UA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:Se,availableWidth:ve,availableHeight:Me})=>{const{width:Ye,height:ht}=Se.reference,tt=we.floating.style;tt.setProperty("--radix-popper-available-width",`${ve}px`),tt.setProperty("--radix-popper-available-height",`${Me}px`),tt.setProperty("--radix-popper-anchor-width",`${Ye}px`),tt.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=ov($),D=Pr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(lt.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=iv;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=ov(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function ov(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Jm=!1;function HA(){const[e,t]=b.useState(Jm);return b.useEffect(()=>{Jm||(Jm=!0,t(!0))},[]),e}var tC=Vd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,ep="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},ic="RovingFocusGroup",[Up,nC,ZA]=oj(ic),[YA,sC]=Na(ic,[ZA]),[QA,XA]=YA(ic),rC=b.forwardRef((e,t)=>o.jsx(Up.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Up.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=ic;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Zt(t,w),j=lj(l),[S,E]=ac({prop:u,defaultProp:f??null,onChange:h,caller:ic}),[_,N]=b.useState(!1),R=Pr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(ep,R),()=>H.removeEventListener(ep,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(lt.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(ep,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ds(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Up.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(lt.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Vp=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Vp,"ArrowRight"],rtl:[...Vp,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oc="Menu",[Zl,cD,uD]=oj(oc),[bi,tf]=Na(oc,[uD,ef,sC]),nf=ef(),cC=sC(),[dD,wi]=bi(oc),[fD,lc]=bi(oc),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=nf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Pr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=oc;var hD="MenuAnchor",lv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(Wj,{...i,...r,ref:t})});lv.displayName=hD;var cv="MenuPortal",[mD,dC]=bi(cv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=wi(cv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};fC.displayName=cv;var Ts="MenuContent",[pD,uv]=bi(Ts),hC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=wi(Ts,e.__scopeMenu),u=lc(Ts,e.__scopeMenu);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(dv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu);return o.jsx(dv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=No("MenuContent.ScrollLock"),dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=wi(Ts,n),_=lc(Ts,n),N=nf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Zt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),X=b.useRef(0),Q=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Gg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Q.current?.side&&OD(ee,Q.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:b.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(Bg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Yl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Ts;var xD="MenuGroup",fv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"group",...r,ref:t})});fv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{...r,ref:t})});mC.displayName=bD;var jd="MenuItem",Hw="menu.itemSelect",sf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=lc(jd,e.__scopeMenu),f=uv(jd,e.__scopeMenu),h=Zt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Vp.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});sf.displayName=jd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=uv(jd,n),f=cC(n),h=b.useRef(null),m=Zt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Zl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(lt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Yl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Yl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(sf,{role:"menuitemcheckbox","aria-checked":Cd(n)?"mixed":n,...i,ref:t,"data-state":mv(n),onSelect:Ue(i.onSelect,()=>r?.(Cd(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=bi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Pr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(fv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(sf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":mv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var hv="MenuItemIndicator",[wC,CD]=bi(hv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(hv,n);return o.jsx(dr,{present:r||Cd(l.checked)||l.checked===!0,children:o.jsx(lt.span,{...i,ref:t,"data-state":mv(l.checked)})})});SC.displayName=hv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=bi(ND),$l="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=wi($l,e.__scopeMenu),r=lc($l,e.__scopeMenu),i=_C($l,e.__scopeMenu),l=uv($l,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Zt(t,i.onTriggerChange);return o.jsx(lv,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Yl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Yl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=$l;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=wi(Ts,e.__scopeMenu),f=lc(Ts,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Zt(t,m);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:o.jsx(dv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function Cd(e){return e==="indeterminate"}function mv(e){return Cd(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Yl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=lv,OC=fC,AC=hC,DC=fv,zC=mC,LC=sf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,rf="ContextMenu",[AD]=Na(rf,[tf]),Un=tf(),[DD,BC]=AD(rf),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=ac({prop:i,defaultProp:!1,onChange:r,caller:rf}),y=Un(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=rf;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Un(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(lt.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Pu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Pu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Pu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Pu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Pu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,af="DropdownMenu",[lz]=Na(af,[tf]),Vn=tf(),[cz,e_]=lz(af),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Vn(t),m=b.useRef(null),[y,g]=ac({prop:i,defaultProp:l??!1,onChange:u,caller:af});return o.jsx(cz,{scope:t,triggerId:ds(),triggerRef:m,contentId:ds(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=af;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Vn(n),f=Zt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(lt.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Vn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Vn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(lt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(lt.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[of]=Na("Tooltip",[ef]),lf=ef(),p_="TooltipProvider",Hz=700,Hp="tooltip.open",[qz,pv]=of(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Ql="Tooltip",[Bz,cc]=of(Ql),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=pv(Ql,e.__scopeTooltip),m=lf(t),[y,g]=b.useState(null),w=ds(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=ac({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Hp))):h.onClose(),l?.(L)},caller:Ql}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Ql;var qp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cc(qp,n),l=pv(qp,n),u=lf(n),f=b.useRef(null),h=Zt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(lt.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=qp;var gv="TooltipPortal",[Gz,Kz]=of(gv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=cc(gv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};x_.displayName=gv;var Ro="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(Ro,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=cc(Ro,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=cc(Ro,e.__scopeTooltip),r=pv(Ro,e.__scopeTooltip),i=b.useRef(null),l=Zt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=of(Ql,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=cc(Ro,n),m=lf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Hp,y),()=>document.removeEventListener(Hp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=Ro;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=lf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),_d="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(_d),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(_d):e.slice(t).join(_d),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];vv(i,n,r,t)}return n},vv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){vv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(_d),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},Bp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+Bp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],ln=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,va=e=>A4.test(e),Xe=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),tp=e=>e.endsWith("%")&&Xe(e.slice(0,-1)),Ar=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),yv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Re(e)&&!Te(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ra(e,z_,yv),Re=e=>M_.test(e),ni=e=>Ra(e,L_,I4),Zw=e=>Ra(e,W4,Xe),B4=e=>Ra(e,F_,O_),G4=e=>Ra(e,$_,yv),Yw=e=>Ra(e,A_,yv),K4=e=>Ra(e,D_,U4),Uu=e=>Ra(e,I_,P4),Te=e=>T_.test(e),Ol=e=>Si(e,L_),Z4=e=>Si(e,$_),Qw=e=>Si(e,A_),Y4=e=>Si(e,z_),Q4=e=>Si(e,D_),Vu=e=>Si(e,I_,!0),X4=e=>Si(e,F_,!0),Ra=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Si=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=ln("color"),t=ln("font"),n=ln("text"),r=ln("font-weight"),i=ln("tracking"),l=ln("leading"),u=ln("breakpoint"),f=ln("container"),h=ln("spacing"),m=ln("radius"),y=ln("shadow"),g=ln("inset-shadow"),w=ln("text-shadow"),x=ln("drop-shadow"),j=ln("blur"),S=ln("perspective"),E=ln("aspect"),_=ln("ease"),N=ln("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Te,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Te,Re,h],U=()=>[va,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Te,Re],X=()=>["auto",{span:["full",Js,Te,Re]},Js,Te,Re],Q=()=>[Js,"auto",Te,Re],ae=()=>["auto","min","max","fr",Te,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[va,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[va,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[va,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Te,Re],O=()=>[...T(),Qw,Yw,{position:[Te,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Te,Re]}],P=()=>[tp,Ol,ni],I=()=>["","none","full",m,Te,Re],re=()=>["",Xe,Ol,ni],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>[Xe,tp,Qw,Yw],ve=()=>["","none",j,Te,Re],Me=()=>["none",Xe,Te,Re],Ye=()=>["none",Xe,Te,Re],ht=()=>[Xe,Te,Re],tt=()=>[va,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ar],breakpoint:[Ar],color:[O_],container:[Ar],"drop-shadow":[Ar],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ar],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ar],shadow:[Ar],spacing:["px",Xe],text:[Ar],"text-shadow":[Ar],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",va,Re,Te,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Te,Re]}],"container-named":[H4],columns:[{columns:[Xe,Re,Te,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Te,Re]}],basis:[{basis:[va,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,va,"auto","initial","none",Re]}],grow:[{grow:["",Xe,Te,Re]}],shrink:[{shrink:["",Xe,Te,Re]}],order:[{order:[Js,"first","last","none",Te,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ol,ni]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tp,Re]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Te,Re]}],"line-clamp":[{"line-clamp":[Xe,"none",Te,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Te,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Te,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Te,ni]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Xe,"auto",Te,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Te,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Te,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Te,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Te,Re],radial:["",Te,Re],conic:[Js,Te,Re]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Te,Re]}],"outline-w":[{outline:["",Xe,Ol,ni]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Vu,Uu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Vu,Uu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Xe,ni]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Vu,Uu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Xe,Te,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Se()}],"mask-image-linear-to-pos":[{"mask-linear-to":Se()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":Se()}],"mask-image-t-to-pos":[{"mask-t-to":Se()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":Se()}],"mask-image-r-to-pos":[{"mask-r-to":Se()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":Se()}],"mask-image-b-to-pos":[{"mask-b-to":Se()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":Se()}],"mask-image-l-to-pos":[{"mask-l-to":Se()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":Se()}],"mask-image-x-to-pos":[{"mask-x-to":Se()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":Se()}],"mask-image-y-to-pos":[{"mask-y-to":Se()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Te,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":Se()}],"mask-image-radial-to-pos":[{"mask-radial-to":Se()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Se()}],"mask-image-conic-to-pos":[{"mask-conic-to":Se()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Te,Re]}],filter:[{filter:["","none",Te,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Xe,Te,Re]}],contrast:[{contrast:[Xe,Te,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Vu,Uu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Xe,Te,Re]}],"hue-rotate":[{"hue-rotate":[Xe,Te,Re]}],invert:[{invert:["",Xe,Te,Re]}],saturate:[{saturate:[Xe,Te,Re]}],sepia:[{sepia:["",Xe,Te,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Te,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Te,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Te,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Te,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Te,Re]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Te,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Te,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Te,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Te,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Te,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Te,Re]}],ease:[{ease:["linear","initial",_,Te,Re]}],delay:[{delay:[Xe,Te,Re]}],animate:[{animate:["none",N,Te,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Te,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Ye()}],"scale-x":[{"scale-x":Ye()}],"scale-y":[{"scale-y":Ye()}],"scale-z":[{"scale-z":Ye()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Te,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:tt()}],"translate-x":[{"translate-x":tt()}],"translate-y":[{"translate-y":tt()}],"translate-z":[{"translate-z":tt()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Te,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Te,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Te,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Xe,Ol,ni,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function at(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function cf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function uf({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function df({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:at("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Gp=new Set;function n3(e){return Gp.add(e),()=>Gp.delete(e)}function Co(e){for(const t of Gp)t(e)}const ii=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Dr=/\.html?$/i,ad=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Xl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function mi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Mn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Kp="(min-width: 1400px)";function ff(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function xv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var np={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...np,width:t??m??np.width,height:t??m??np.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],bv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],wv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=Sv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),pi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}pi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function fs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),pi(),e&&window.innerWidth<=Sv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const Sv=900;function pi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=Sv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Zp="bdrive.sidebarWidth",aE=210,iE=480;function id(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function sp(e){try{e===null?localStorage.removeItem(Zp):localStorage.setItem(Zp,String(e))}catch{}}const Yp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Yp(m.clientX-l),id(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&sp(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{id(null),sp(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Yp(u+l);id(f),sp(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Zp));e&&id(Yp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",pi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){fs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:bv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:wv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Qp={folder:bv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:wv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ci({name:e,className:t}){const n=e??"",r=Object.hasOwn(Qp,n)?Qp[n]:bv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function jv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function bo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&pi()}function oi(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:fs}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(Cv,{id:"rail-search",icon:"search",label:"Search",hint:Xl?"⌘K":"Ctrl+K",onClick:()=>Co()}),t]})}function Cv(e){return o.jsxs(cf,{delayDuration:100,children:[o.jsx(uf,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(df,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function hf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(jv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function li(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Xl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Xp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Xp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Xp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Wn=new xL,bL=(e,t)=>{const n=t?.id||Xp++;return Wn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Wn.toasts,CL=()=>Wn.getActiveToasts(),Ww=Object.assign(SL,{success:Wn.success,info:Wn.info,warning:Wn.warning,error:Wn.error,custom:Wn.custom,message:Wn.message,promise:Wn.promise,dismiss:Wn.dismiss,loading:Wn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Hu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function er(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[Se,ve]=ye.useState(!1),[Me,Ye]=ye.useState(!1),[ht,tt]=ye.useState(0),[es,Fe]=ye.useState(0),ot=ye.useRef(g.duration||Q||Jw),Yt=ye.useRef(null),Nt=ye.useRef(null),dn=_===0,jt=_+1<=S,Lt=g.type,ts=g.dismissible!==!1,At=g.className||"",sn=g.descriptionClassName||"",ns=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),hr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hs=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),ms=ye.useRef(0),Tn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,dt,Et)=>Et>=ns?Le:Le+dt.height,0),[E,ns]),xe=yL(),je=g.invert||y,_e=Lt==="loading";Tn.current=ye.useMemo(()=>ns*le+me,[ns,me]),ye.useEffect(()=>{ot.current=Hs},[Hs]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=Nt.current;if(Le){const dt=Le.getBoundingClientRect().height;return Fe(dt),j(Et=>[{toastId:g.id,height:dt,position:g.position},...Et]),()=>j(Et=>Et.filter($t=>$t.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=Nt.current,dt=Le.style.height;Le.style.height="auto";const Et=Le.getBoundingClientRect().height;Le.style.height=dt,Fe(Et),j($t=>$t.find(vt=>vt.toastId===g.id)?$t.map(vt=>vt.toastId===g.id?{...vt,height:Et}:vt):[{toastId:g.id,height:Et,position:g.position},...$t])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ae=ye.useCallback(()=>{re(!0),tt(Tn.current),j(Le=>Le.filter(dt=>dt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Tn]);ye.useEffect(()=>{if(g.promise&&Lt==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ae()},ot.current)),()=>clearTimeout(Le)},[R,x,g,Lt,xe,Ae]),ye.useEffect(()=>{g.delete&&(Ae(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ae,g.delete]);function Ke(){var Le;if(q?.loading){var dt;return ye.createElement("div",{className:er($?.loader,g==null||(dt=g.classNames)==null?void 0:dt.loader,"sonner-loader"),"data-visible":Lt==="loading"},q.loading)}return ye.createElement(fL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Lt==="loading"})}const Ct=g.icon||q?.[Lt]||uL(Lt);var rn,Dt;return ye.createElement("li",{tabIndex:0,ref:Nt,className:er(Z,At,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Lt],g==null||(n=g.classNames)==null?void 0:n[Lt]),"data-sonner-toast":"","data-rich-colors":(rn=g.richColors)!=null?rn:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Me,"data-removed":I,"data-visible":jt,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":dn,"data-swiping":he,"data-dismissible":ts,"data-type":Lt,"data-invert":je,"data-swipe-out":Se,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Tn.current}px`,"--initial-height":be?"auto":`${es}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ts||(Yt.current=new Date,tt(Tn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,dt,Et;if(Se||!ts)return;Y.current=null;const $t=Number(((Le=Nt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Hn=Number(((dt=Nt.current)==null?void 0:dt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vt=new Date().getTime()-((Et=Yt.current)==null?void 0:Et.getTime()),fn=ee==="x"?$t:Hn,mr=Math.abs(fn)/vt;if(Math.abs(fn)>=ML||mr>.11){tt(Tn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?$t>0?"right":"left":Hn>0?"down":"up"),Ae(),ve(!0);return}else{var Cn,an;(Cn=Nt.current)==null||Cn.style.setProperty("--swipe-amount-x","0px"),(an=Nt.current)==null||an.style.setProperty("--swipe-amount-y","0px")}Ye(!1),we(!1),K(null)},onPointerMove:Le=>{var dt,Et,$t;if(!Y.current||!ts||((dt=window.getSelection())==null?void 0:dt.toString().length)>0)return;const vt=Le.clientY-Y.current.y,fn=Le.clientX-Y.current.x;var mr;const Cn=(mr=e.swipeDirections)!=null?mr:OL(ae);!ee&&(Math.abs(fn)>1||Math.abs(vt)>1)&&K(Math.abs(fn)>Math.abs(vt)?"x":"y");let an={x:0,y:0};const qr=qn=>1/(1.5+Math.abs(qn)/20);if(ee==="y"){if(Cn.includes("top")||Cn.includes("bottom"))if(Cn.includes("top")&&vt<0||Cn.includes("bottom")&&vt>0)an.y=vt;else{const qn=vt*qr(vt);an.y=Math.abs(qn)0)an.x=fn;else{const qn=fn*qr(fn);an.x=Math.abs(qn)0||Math.abs(an.y)>0)&&Ye(!0),(Et=Nt.current)==null||Et.style.setProperty("--swipe-amount-x",`${an.x}px`),($t=Nt.current)==null||$t.style.setProperty("--swipe-amount-y",`${an.y}px`)}},hr&&!g.jsx&&Lt!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ts?()=>{}:()=>{Ae(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Lt||g.icon||g.promise)&&g.icon!==null&&(q?.[Lt]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||Ke():null,g.type!=="loading"?Ct:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,sn,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&Hu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{Hu(g.cancel)&&ts&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ae())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&Hu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{Hu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ae())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Wn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Wn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,Se)=>{var ve,Me;return ye.createElement(AL,{key:we.id,icons:T,index:Se,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Me=_?.closeButton)!=null?Me:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ye=>Ye.position==we.position),heights:Z.filter(Ye=>Ye.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Ed="bdrive-theme",Wp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function _v(){try{const e=localStorage.getItem(Ed);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function od(){const e=LL(_v()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Wp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Ed):localStorage.setItem(Ed,e)}catch{}od()}let t1=!1;function IL(){if(!t1){t1=!0,od();try{window.matchMedia(lE).addEventListener("change",()=>{_v()==="system"&&od()})}catch{}window.addEventListener("storage",e=>{(e.key===Ed||e.key===null)&&od()})}}function PL(e){return window.addEventListener(Wp,e),()=>window.removeEventListener(Wp,e)}function n1(){return`${_v()}:${$L()}`}function Ev(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=Ev();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:at(qL({variant:t,size:n,className:e})),...i})}function uc({...e}){return o.jsx(Kg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Yg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Qg,{"data-slot":"dialog-overlay",className:at("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function dc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Xg,{"data-slot":"dialog-content",className:at("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zo({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:at("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:at("text-sm text-muted-foreground",e),...t})}let uE=null,ld=[];function fc(e){uE=e,ld.forEach(t=>t())}function Wl(e,t,n="",r="OK",i={}){return new Promise(l=>fc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>fc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(ld.push(n),()=>{ld=ld.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{fc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(uc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(dc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{fc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{fc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let Nd=null,cd=[];const Nv=e=>{Nd=e,cd.forEach(t=>t())};function VB(e,t){Nv({...t,path:e,from:t})}function HB(e){Nd?.from===e&&Nv(null)}function XL(){const e=b.useSyncExternalStore(f=>(cd.push(f),()=>{cd=cd.filter(h=>h!==f)}),()=>Nd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),Nd===e&&Nv(null)}},u=()=>{l(e.keep)};return o.jsx(uc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(dc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:mi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":mi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>We("/api/projects")};function WL(e){return rt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=mn();return()=>e.fetchQuery(dE)}function fE(e){return rt({queryKey:["orgs"],queryFn:()=>We("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function kv(e){return rt({queryKey:["permissions",e],queryFn:()=>We(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return rt({queryKey:["folders",e],queryFn:()=>We(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return rt({queryKey:["shares",e],queryFn:()=>We(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return rt({queryKey:["admin","pending"],queryFn:()=>We("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function mf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Jp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Jp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Jp,e)?Jp[e]:void 0}const Rv=["q","user","actor","device","range","since","until"];function Mv(e){return!!e&&Rv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of Rv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Tv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of Rv){const y=r?.get(m);y&&(h[m]=y)}if(Mv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=mf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?mf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function $n(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function cn(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=mf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Ov="POP";const eg=new Set;function xE(){for(const e of eg)e()}window.addEventListener("popstate",()=>{Ov="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Ov=t?.replace?"REPLACE":"PUSH",xE())}function Av(){return b.useSyncExternalStore(e=>(eg.add(e),()=>{eg.delete(e)}),()=>location.pathname+location.search)}function c$(){return Ov}function Pn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function si({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function ba(e,t){return typeof e=="function"?e(t):e}function hs(e,t){return n=>{t.setState(r=>({...r,[e]:ba(n,r[e])}))}}function pf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.lengthMath.abs(T)?"h":"v";if("touches"in S&&L==="h"&&M.type==="range")return!1;var H=window.getSelection(),U=H&&H.anchorNode,Z=U?U===M||U.contains(M):!1;if(Z)return!1;var X=Mw(L,M);if(!X)return!0;if(X?A=L:(A=L==="v"?"h":"v",X=Mw(L,M)),!X)return!1;if(!r.current&&"changedTouches"in S&&(R||T)&&(r.current=A),!A)return!0;var Q=r.current||A;return fO(Q,E,S,Q==="h"?R:T)},[]),h=b.useCallback(function(S){var E=S;if(!(!fo.length||fo[fo.length-1]!==l)){var _="deltaY"in E?Tw(E):Lu(E),N=t.current.filter(function(A){return A.name===E.type&&(A.target===E.target||E.target===A.shadowParent)&&hO(A.delta,_)})[0];if(N&&N.should){E.cancelable&&E.preventDefault();return}if(!N){var R=(u.current.shards||[]).map(Ow).filter(Boolean).filter(function(A){return A.contains(E.target)}),T=R.length>0?f(E,R[0]):!u.current.noIsolation;T&&E.cancelable&&E.preventDefault()}}},[]),m=b.useCallback(function(S,E,_,N){var R={name:S,delta:E,target:_,should:N,shadowParent:vO(_)};t.current.push(R),setTimeout(function(){t.current=t.current.filter(function(T){return T!==R})},1)},[]),y=b.useCallback(function(S){n.current=Lu(S),r.current=void 0},[]),g=b.useCallback(function(S){m(S.type,Tw(S),S.target,f(S,e.lockRef.current))},[]),w=b.useCallback(function(S){m(S.type,Lu(S),S.target,f(S,e.lockRef.current))},[]);b.useEffect(function(){return fo.push(l),e.setCallbacks({onScrollCapture:g,onWheelCapture:g,onTouchMoveCapture:w}),document.addEventListener("wheel",h,uo),document.addEventListener("touchmove",h,uo),document.addEventListener("touchstart",y,uo),function(){fo=fo.filter(function(S){return S!==l}),document.removeEventListener("wheel",h,uo),document.removeEventListener("touchmove",h,uo),document.removeEventListener("touchstart",y,uo)}},[]);var x=e.removeScrollBar,j=e.inert;return b.createElement(b.Fragment,null,j?b.createElement(l,{styles:mO(i)}):null,x?b.createElement(aO,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function vO(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const yO=GT(mj,gO);var Gg=b.forwardRef(function(e,t){return b.createElement(Kd,sr({},e,{ref:t,sideCar:yO}))});Gg.classNames=Kd.classNames;var xO=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ho=new WeakMap,$u=new WeakMap,Fu={},Ym=0,xj=function(e){return e&&(e.host||xj(e.parentNode))},bO=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},wO=function(e,t,n,r){var i=bO(t,Array.isArray(e)?e:[e]);Fu[n]||(Fu[n]=new WeakMap);var l=Fu[n],u=[],f=new Set,h=new Set(i),m=function(g){!g||f.has(g)||(f.add(g),m(g.parentNode))};i.forEach(m);var y=function(g){!g||h.has(g)||Array.prototype.forEach.call(g.children,function(w){if(f.has(w))y(w);else try{var x=w.getAttribute(r),j=x!==null&&x!=="false",S=(ho.get(w)||0)+1,E=(l.get(w)||0)+1;ho.set(w,S),l.set(w,E),u.push(w),S===1&&j&&$u.set(w,!0),E===1&&w.setAttribute(n,"true"),j||w.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",w,_)}})};return y(t),f.clear(),Ym++,function(){u.forEach(function(g){var w=ho.get(g)-1,x=l.get(g)-1;ho.set(g,w),l.set(g,x),w||($u.has(g)||g.removeAttribute(r),$u.delete(g)),x||g.removeAttribute(n)}),Ym--,Ym||(ho=new WeakMap,ho=new WeakMap,$u=new WeakMap,Fu={})}},bj=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=xO(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),wO(r,i,n,"aria-hidden")):function(){return null}},Zd="Dialog",[wj]=Na(Zd),[SO,Vs]=wj(Zd),Kg=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:l,modal:u=!0}=e,f=b.useRef(null),h=b.useRef(null),[m,y]=ac({prop:r,defaultProp:i??!1,onChange:l,caller:Zd});return o.jsx(SO,{scope:t,triggerRef:f,contentRef:h,contentId:ds(),titleId:ds(),descriptionId:ds(),open:m,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),modal:u,children:n})};Kg.displayName=Zd;var Sj="DialogTrigger",jO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Sj,n),l=Zt(t,i.triggerRef);return o.jsx(lt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Wg(i.open),...r,ref:l,onClick:Ue(e.onClick,i.onOpenToggle)})});jO.displayName=Sj;var Zg="DialogPortal",[CO,jj]=wj(Zg,{forceMount:void 0}),Yg=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,l=Vs(Zg,t);return o.jsx(CO,{scope:t,forceMount:n,children:b.Children.map(r,u=>o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:u})}))})};Yg.displayName=Zg;var yd="DialogOverlay",Qg=b.forwardRef((e,t)=>{const n=jj(yd,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(yd,e.__scopeDialog);return l.modal?o.jsx(dr,{present:r||l.open,children:o.jsx(EO,{...i,ref:t})}):null});Qg.displayName=yd;var _O=No("DialogOverlay.RemoveScroll"),EO=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(yd,n),l=_T(),u=Zt(t,l);return o.jsx(Gg,{as:_O,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(lt.div,{"data-state":Wg(i.open),...r,ref:u,style:{pointerEvents:"auto",...r.style}})})}),ko="DialogContent",Xg=b.forwardRef((e,t)=>{const n=jj(ko,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,l=Vs(ko,e.__scopeDialog);return o.jsx(dr,{present:r||l.open,children:l.modal?o.jsx(NO,{...i,ref:t}):o.jsx(kO,{...i,ref:t})})});Xg.displayName=ko;var NO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(null),i=Zt(t,n.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(Cj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Ue(e.onCloseAutoFocus,l=>{l.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&l.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault())})}),kO=b.forwardRef((e,t)=>{const n=Vs(ko,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return o.jsx(Cj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{e.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||n.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:l=>{e.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=l.target;n.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})}),Cj=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:l,...u}=e,f=Vs(ko,n);return dj(),o.jsx(o.Fragment,{children:o.jsx(Bg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:l,children:o.jsx(Bd,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Wg(f.open),...u,ref:t,deferPointerDownOutside:!0,onDismiss:()=>f.onOpenChange(!1)})})})}),_j="DialogTitle",Ej=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(_j,n);return o.jsx(lt.h2,{id:i.titleId,...r,ref:t})});Ej.displayName=_j;var Nj="DialogDescription",kj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Nj,n);return o.jsx(lt.p,{id:i.descriptionId,...r,ref:t})});kj.displayName=Nj;var Rj="DialogClose",Mj=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Vs(Rj,n);return o.jsx(lt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>i.onOpenChange(!1))})});Mj.displayName=Rj;function Wg(e){return e?"open":"closed"}function RO(e){const[t,n]=b.useState(void 0);return ar(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const l=i[0];let u,f;if("borderBoxSize"in l){const h=l.borderBoxSize,m=Array.isArray(h)?h[0]:h;u=m.inlineSize,f=m.blockSize}else u=e.offsetWidth,f=e.offsetHeight;n({width:u,height:f})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const MO=["top","right","bottom","left"],ja=Math.min,$r=Math.max,xd=Math.round,Iu=Math.floor,Fr=e=>({x:e,y:e}),TO={left:"right",right:"left",bottom:"top",top:"bottom"};function Tj(e,t,n){return $r(e,ja(t,n))}function Ur(e,t){return typeof e=="function"?e(t):e}function Ca(e){return e.split("-")[0]}function Ao(e){return e.split("-")[1]}function Jg(e){return e==="x"?"y":"x"}function ev(e){return e==="y"?"height":"width"}function rr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function tv(e){return Jg(rr(e))}function OO(e,t,n){n===void 0&&(n=!1);const r=Ao(e),i=tv(e),l=ev(i);let u=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[l]>t.floating[l]&&(u=bd(u)),[u,bd(u)]}function AO(e){const t=bd(e);return[Ip(e),t,Ip(t)]}function Ip(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Aw=["left","right"],Dw=["right","left"],DO=["top","bottom"],zO=["bottom","top"];function LO(e,t,n){switch(e){case"top":case"bottom":return n?t?Dw:Aw:t?Aw:Dw;case"left":case"right":return t?DO:zO;default:return[]}}function $O(e,t,n,r){const i=Ao(e);let l=LO(Ca(e),n==="start",r);return i&&(l=l.map(u=>u+"-"+i),t&&(l=l.concat(l.map(Ip)))),l}function bd(e){const t=Ca(e);return TO[t]+e.slice(t.length)}function FO(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function Oj(e){return typeof e!="number"?FO(e):{top:e,right:e,bottom:e,left:e}}function wd(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function zw(e,t,n){let{reference:r,floating:i}=e;const l=rr(t),u=tv(t),f=ev(u),h=Ca(t),m=l==="y",y=r.x+r.width/2-i.width/2,g=r.y+r.height/2-i.height/2,w=r[f]/2-i[f]/2;let x;switch(h){case"top":x={x:y,y:r.y-i.height};break;case"bottom":x={x:y,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:g};break;case"left":x={x:r.x-i.width,y:g};break;default:x={x:r.x,y:r.y}}const j=Ao(t);return j&&(x[u]+=w*(j==="end"?1:-1)*(n&&m?-1:1)),x}async function IO(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:l,rects:u,elements:f,strategy:h}=e,{boundary:m="clippingAncestors",rootBoundary:y="viewport",elementContext:g="floating",altBoundary:w=!1,padding:x=0}=Ur(t,e),j=Oj(x),E=f[w?g==="floating"?"reference":"floating":g],_=wd(await l.getClippingRect({element:(n=await(l.isElement==null?void 0:l.isElement(E)))==null||n?E:E.contextElement||await(l.getDocumentElement==null?void 0:l.getDocumentElement(f.floating)),boundary:m,rootBoundary:y,strategy:h})),N=g==="floating"?{x:r,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f.floating)),T=await(l.isElement==null?void 0:l.isElement(R))&&await(l.getScale==null?void 0:l.getScale(R))||{x:1,y:1},A=wd(l.convertOffsetParentRelativeRectToViewportRelativeRect?await l.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:N,offsetParent:R,strategy:h}):N);return{top:(_.top-A.top+j.top)/T.y,bottom:(A.bottom-_.bottom+j.bottom)/T.y,left:(_.left-A.left+j.left)/T.x,right:(A.right-_.right+j.right)/T.x}}const PO=50,UO=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:l=[],platform:u}=n,f=u.detectOverflow?u:{...u,detectOverflow:IO},h=await(u.isRTL==null?void 0:u.isRTL(t));let m=await u.getElementRects({reference:e,floating:t,strategy:i}),{x:y,y:g}=zw(m,r,h),w=r,x=0;const j={};for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:l,platform:u,elements:f,middlewareData:h}=t,{element:m,padding:y=0}=Ur(e,t)||{};if(m==null)return{};const g=Oj(y),w={x:n,y:r},x=tv(i),j=ev(x),S=await u.getDimensions(m),E=x==="y",_=E?"top":"left",N=E?"bottom":"right",R=E?"clientHeight":"clientWidth",T=l.reference[j]+l.reference[x]-w[x]-l.floating[j],A=w[x]-l.reference[x],M=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m));let L=M?M[R]:0;(!L||!await(u.isElement==null?void 0:u.isElement(M)))&&(L=f.floating[R]||l.floating[j]);const H=T/2-A/2,U=L/2-S[j]/2-1,Z=ja(g[_],U),X=ja(g[N],U),Q=L-S[j]-X,ae=L/2-S[j]/2+H,le=Tj(Z,ae,Q),be=!h.arrow&&Ao(i)!=null&&ae!==le&&l.reference[j]/2-(aele<=0)){var X,Q;const le=(((X=l.flip)==null?void 0:X.index)||0)+1,be=L[le];if(be&&(!(g==="alignment"?N!==rr(be):!1)||Z.every(V=>rr(V.placement)===N?V.overflows[0]>0:!0)))return{data:{index:le,overflows:Z},reset:{placement:be}};let $=(Q=Z.filter(q=>q.overflows[0]<=0).sort((q,V)=>q.overflows[1]-V.overflows[1])[0])==null?void 0:Q.placement;if(!$)switch(x){case"bestFit":{var ae;const q=(ae=Z.filter(V=>{if(M){const ee=rr(V.placement);return ee===N||ee==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(ee=>ee>0).reduce((ee,K)=>ee+K,0)]).sort((V,ee)=>V[1]-ee[1])[0])==null?void 0:ae[0];q&&($=q);break}case"initialPlacement":$=f;break}if(i!==$)return{reset:{placement:$}}}return{}}}};function Lw(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $w(e){return MO.some(t=>e[t]>=0)}const qO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...l}=Ur(e,t);switch(i){case"referenceHidden":{const u=await r.detectOverflow(t,{...l,elementContext:"reference"}),f=Lw(u,n.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:$w(f)}}}case"escaped":{const u=await r.detectOverflow(t,{...l,altBoundary:!0}),f=Lw(u,n.floating);return{data:{escapedOffsets:f,escaped:$w(f)}}}default:return{}}}}},Aj=new Set(["left","top"]);async function BO(e,t){const{placement:n,platform:r,elements:i}=e,l=await(r.isRTL==null?void 0:r.isRTL(i.floating)),u=Ca(n),f=Ao(n),h=rr(n)==="y",m=Aj.has(u)?-1:1,y=l&&h?-1:1,g=Ur(t,e);let{mainAxis:w,crossAxis:x,alignmentAxis:j}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return f&&typeof j=="number"&&(x=f==="end"?j*-1:j),h?{x:x*y,y:w*m}:{x:w*m,y:x*y}}const GO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:l,placement:u,middlewareData:f}=t,h=await BO(t,e);return u===((n=f.offset)==null?void 0:n.placement)&&(r=f.arrow)!=null&&r.alignmentOffset?{}:{x:i+h.x,y:l+h.y,data:{...h,placement:u}}}}},KO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:l}=t,{mainAxis:u=!0,crossAxis:f=!1,limiter:h={fn:N=>{let{x:R,y:T}=N;return{x:R,y:T}}},...m}=Ur(e,t),y={x:n,y:r},g=await l.detectOverflow(t,m),w=rr(i),x=Jg(w);let j=y[x],S=y[w];const E=(N,R)=>Tj(R+g[N==="y"?"top":"left"],R,R-g[N==="y"?"bottom":"right"]);u&&(j=E(x,j)),f&&(S=E(w,S));const _=h.fn({...t,[x]:j,[w]:S});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[x]:u,[w]:f}}}}}},ZO=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:l,placement:u,rects:f,middlewareData:h}=t,{offset:m=0,mainAxis:y=!0,crossAxis:g=!0}=Ur(e,t),w={x:i,y:l},x=rr(u),j=Jg(x);let S=w[j],E=w[x];const _=Ur(m,t),N=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(y){const A=j==="y"?"height":"width",M=f.reference[j]-f.floating[A]+N.mainAxis,L=f.reference[j]+f.reference[A]-N.mainAxis;SL&&(S=L)}if(g){var R,T;const A=j==="y"?"width":"height",M=Aj.has(Ca(u)),L=f.reference[x]-f.floating[A]+(M&&((R=h.offset)==null?void 0:R[x])||0)+(M?0:N.crossAxis),H=f.reference[x]+f.reference[A]+(M?0:((T=h.offset)==null?void 0:T[x])||0)-(M?N.crossAxis:0);EH&&(E=H)}return{[j]:S,[x]:E}}}},YO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:l}=t,{apply:u=()=>{},...f}=Ur(e,t),h=await i.detectOverflow(t,f),m=Ca(n),y=Ao(n),g=rr(n)==="y",{width:w,height:x}=r.floating;let j,S;m==="top"||m==="bottom"?(j=m,S=y===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(S=m,j=y==="end"?"top":"bottom");const E=x-h.top-h.bottom,_=w-h.left-h.right,N=ja(x-h[j],E),R=ja(w-h[S],_),T=t.middlewareData.shift,A=!T;let M=N,L=R;T!=null&&T.enabled.x&&(L=_),T!=null&&T.enabled.y&&(M=E),A&&!y&&(g?L=w-2*$r(h.left,h.right):M=x-2*$r(h.top,h.bottom)),await u({...t,availableWidth:L,availableHeight:M});const H=await i.getDimensions(l.floating);return w!==H.width||x!==H.height?{reset:{rects:!0}}:{}}}};function Yd(){return typeof window<"u"}function Do(e){return Dj(e)?(e.nodeName||"").toLowerCase():"#document"}function Jn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Hr(e){var t;return(t=(Dj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dj(e){return Yd()?e instanceof Node||e instanceof Jn(e).Node:!1}function lr(e){return Yd()?e instanceof Element||e instanceof Jn(e).Element:!1}function ka(e){return Yd()?e instanceof HTMLElement||e instanceof Jn(e).HTMLElement:!1}function Fw(e){return!Yd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Jn(e).ShadowRoot}function Qd(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=cr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function QO(e){return/^(table|td|th)$/.test(Do(e))}function Xd(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const XO=/transform|translate|scale|rotate|perspective|filter/,WO=/paint|layout|strict|content/,ti=e=>!!e&&e!=="none";let Qm;function nv(e){const t=lr(e)?cr(e):e;return ti(t.transform)||ti(t.translate)||ti(t.scale)||ti(t.rotate)||ti(t.perspective)||!sv()&&(ti(t.backdropFilter)||ti(t.filter))||XO.test(t.willChange||"")||WO.test(t.contain||"")}function JO(e){let t=fi(e);for(;ka(t)&&!Gl(t);){if(nv(t))return t;if(Xd(t))return null;t=fi(t)}return null}function sv(){return Qm==null&&(Qm=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Qm}function Gl(e){return/^(html|body|#document)$/.test(Do(e))}function cr(e){return Jn(e).getComputedStyle(e)}function Wd(e){return lr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function fi(e){if(Do(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fw(e)&&e.host||Hr(e);return Fw(t)?t.host:t}function zj(e){const t=fi(e);return Gl(t)?(e.ownerDocument||e).body:ka(t)&&Qd(t)?t:zj(t)}function Kl(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=zj(e),l=i===((r=e.ownerDocument)==null?void 0:r.body),u=Jn(i);if(l){const f=Pp(u);return t.concat(u,u.visualViewport||[],Qd(i)?i:[],f&&n?Kl(f):[])}else return t.concat(i,Kl(i,[],n))}function Pp(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lj(e){const t=cr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=ka(e),l=i?e.offsetWidth:n,u=i?e.offsetHeight:r,f=xd(n)!==l||xd(r)!==u;return f&&(n=l,r=u),{width:n,height:r,$:f}}function rv(e){return lr(e)?e:e.contextElement}function jo(e){const t=rv(e);if(!ka(t))return Fr(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:l}=Lj(t);let u=(l?xd(n.width):n.width)/r,f=(l?xd(n.height):n.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const eA=Fr(0);function $j(e){const t=Jn(e);return!sv()||!t.visualViewport?eA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Jn(e)}function hi(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),l=rv(e);let u=Fr(1);t&&(r?lr(r)&&(u=jo(r)):u=jo(e));const f=tA(l,n,r)?$j(l):Fr(0);let h=(i.left+f.x)/u.x,m=(i.top+f.y)/u.y,y=i.width/u.x,g=i.height/u.y;if(l&&r){const w=Jn(l),x=lr(r)?Jn(r):r;let j=w,S=Pp(j);for(;S&&x!==j;){const E=jo(S),_=S.getBoundingClientRect(),N=cr(S),R=_.left+(S.clientLeft+parseFloat(N.paddingLeft))*E.x,T=_.top+(S.clientTop+parseFloat(N.paddingTop))*E.y;h*=E.x,m*=E.y,y*=E.x,g*=E.y,h+=R,m+=T,j=Jn(S),S=Pp(j)}}return wd({width:y,height:g,x:h,y:m})}function Jd(e,t){const n=Wd(e).scrollLeft;return t?t.left+n:hi(Hr(e)).left+n}function Fj(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Jd(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const l=i==="fixed",u=Hr(r),f=t?Xd(t.floating):!1;if(r===u||f&&l)return n;let h={scrollLeft:0,scrollTop:0},m=Fr(1);const y=Fr(0),g=ka(r);if((g||!l)&&((Do(r)!=="body"||Qd(u))&&(h=Wd(r)),g)){const x=hi(r);m=jo(r),y.x=x.x+r.clientLeft,y.y=x.y+r.clientTop}const w=u&&!g&&!l?Fj(u,h):Fr(0);return{width:n.width*m.x,height:n.height*m.y,x:n.x*m.x-h.scrollLeft*m.x+y.x+w.x,y:n.y*m.y-h.scrollTop*m.y+y.y+w.y}}function sA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function rA(e){const t=Wd(e),n=e.ownerDocument.body,r=$r(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=$r(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let l=-t.scrollLeft+Jd(e);const u=-t.scrollTop;return cr(n).direction==="rtl"&&(l+=$r(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:l,y:u}}const aA=25;function iA(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Jn(e),l=Hr(e),u=i.visualViewport;let f=l.clientWidth,h=l.clientHeight,m=0,y=0;if(u){const w=!sv()||t==="fixed";r?w||(m=-u.offsetLeft,y=-u.offsetTop):(f=u.width,h=u.height,w&&(m=u.offsetLeft,y=u.offsetTop))}if(Jd(l)<=0){const w=l.ownerDocument,x=w.body,j=getComputedStyle(x),S=w.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,E=Math.abs(l.clientWidth-x.clientWidth-S),_=getComputedStyle(l).scrollbarGutter==="stable both-edges"?E/2:E;_<=aA&&(f-=_)}return{width:f,height:h,x:m,y}}function oA(e,t){const n=hi(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,l=jo(e),u=e.clientWidth*l.x,f=e.clientHeight*l.y,h=i*l.x,m=r*l.y;return{width:u,height:f,x:h,y:m}}function Iw(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=iA(e,n,t);else if(t==="document")r=rA(Hr(e));else if(lr(t))r=oA(t,n);else{const i=$j(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return wd(r)}function lA(e,t){const n=t.get(e);if(n)return n;let r=Kl(e,[],!1).filter(f=>lr(f)&&Do(f)!=="body"),i=null;const l=cr(e).position==="fixed";let u=l?fi(e):e;for(;lr(u)&&!Gl(u);){const f=cr(u),h=nv(u),m=i?i.position:l?"fixed":"";!h&&(m==="fixed"||m==="absolute"&&f.position==="static")?r=r.filter(g=>g!==u):i=f,u=fi(u)}return t.set(e,r),r}function cA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const u=[...n==="clippingAncestors"?Xd(t)?[]:lA(t,this._c):[].concat(n),r],f=Iw(t,u[0],i);let h=f.top,m=f.right,y=f.bottom,g=f.left;for(let w=1;w{f(!1,1e-7)},1e3)}L=!1}try{r=new IntersectionObserver(H,{...M,root:l.ownerDocument})}catch{r=new IntersectionObserver(H,M)}r.observe(e)}const h=Jn(e),m=()=>f(n);return h.addEventListener("resize",m),f(!0),()=>{h.removeEventListener("resize",m),u()}}function gA(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:l=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:h=!1}=r,m=rv(e),y=i||l?[...m?Kl(m):[],...t?Kl(t):[]]:[];y.forEach(_=>{i&&_.addEventListener("scroll",n),l&&_.addEventListener("resize",n)});const g=m&&f?pA(m,n,l):null;let w=-1,x=null;u&&(x=new ResizeObserver(_=>{let[N]=_;N&&N.target===m&&x&&t&&(x.unobserve(t),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=x)==null||R.observe(t)})),n()}),m&&!h&&x.observe(m),t&&x.observe(t));let j,S=h?hi(e):null;h&&E();function E(){const _=hi(e);S&&!Pj(S,_)&&n(),S=_,j=requestAnimationFrame(E)}return n(),()=>{var _;y.forEach(N=>{i&&N.removeEventListener("scroll",n),l&&N.removeEventListener("resize",n)}),g?.(),(_=x)==null||_.disconnect(),x=null,h&&cancelAnimationFrame(j)}}const vA=GO,yA=KO,xA=HO,bA=YO,wA=qO,Uw=VO,SA=ZO,jA=(e,t,n)=>{const r=new Map,i=n??{},l={...mA,...i.platform,_c:r};return UO(e,t,{...i,platform:l})};var CA=typeof document<"u",_A=function(){},rd=CA?b.useLayoutEffect:_A;function Sd(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Sd(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const l=i[r];if(!(l==="_owner"&&e.$$typeof)&&!Sd(e[l],t[l]))return!1}return!0}return e!==e&&t!==t}function Uj(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vw(e,t){const n=Uj(e);return Math.round(t*n)/n}function Wm(e){const t=b.useRef(e);return rd(()=>{t.current=e}),t}function EA(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:l,floating:u}={},transform:f=!0,whileElementsMounted:h,open:m}=e,[y,g]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[w,x]=b.useState(r);Sd(w,r)||x(r);const[j,S]=b.useState(null),[E,_]=b.useState(null),N=b.useCallback(V=>{V!==M.current&&(M.current=V,S(V))},[]),R=b.useCallback(V=>{V!==L.current&&(L.current=V,_(V))},[]),T=l||j,A=u||E,M=b.useRef(null),L=b.useRef(null),H=b.useRef(y),U=h!=null,Z=Wm(h),X=Wm(i),Q=Wm(m),ae=b.useCallback(()=>{if(!M.current||!L.current)return;const V={placement:t,strategy:n,middleware:w};X.current&&(V.platform=X.current),jA(M.current,L.current,V).then(ee=>{const K={...ee,isPositioned:Q.current!==!1};le.current&&!Sd(H.current,K)&&(H.current=K,rc.flushSync(()=>{g(K)}))})},[w,t,n,X,Q]);rd(()=>{m===!1&&H.current.isPositioned&&(H.current.isPositioned=!1,g(V=>({...V,isPositioned:!1})))},[m]);const le=b.useRef(!1);rd(()=>(le.current=!0,()=>{le.current=!1}),[]),rd(()=>{if(T&&(M.current=T),A&&(L.current=A),T&&A){if(Z.current)return Z.current(T,A,ae);ae()}},[T,A,ae,Z,U]);const be=b.useMemo(()=>({reference:M,floating:L,setReference:N,setFloating:R}),[N,R]),$=b.useMemo(()=>({reference:T,floating:A}),[T,A]),q=b.useMemo(()=>{const V={position:n,left:0,top:0};if(!$.floating)return V;const ee=Vw($.floating,y.x),K=Vw($.floating,y.y);return f?{...V,transform:"translate("+ee+"px, "+K+"px)",...Uj($.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:K}},[n,f,$.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:ae,refs:be,elements:$,floatingStyles:q}),[y,ae,be,$,q])}const NA=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Uw({element:r.current,padding:i}).fn(n):{}:r?Uw({element:r,padding:i}).fn(n):{}}}},kA=(e,t)=>{const n=vA(e);return{name:n.name,fn:n.fn,options:[e,t]}},RA=(e,t)=>{const n=yA(e);return{name:n.name,fn:n.fn,options:[e,t]}},MA=(e,t)=>({fn:SA(e).fn,options:[e,t]}),TA=(e,t)=>{const n=xA(e);return{name:n.name,fn:n.fn,options:[e,t]}},OA=(e,t)=>{const n=bA(e);return{name:n.name,fn:n.fn,options:[e,t]}},AA=(e,t)=>{const n=wA(e);return{name:n.name,fn:n.fn,options:[e,t]}},DA=(e,t)=>{const n=NA(e);return{name:n.name,fn:n.fn,options:[e,t]}};var zA="Arrow",Vj=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...l}=e;return o.jsx(lt.svg,{...l,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vj.displayName=zA;var LA=Vj,av="Popper",[Hj,ef]=Na(av),[$A,qj]=Hj(av),Bj=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[l,u]=b.useState(void 0);return o.jsx($A,{scope:t,anchor:r,onAnchorChange:i,placementState:l,setPlacementState:u,children:n})};Bj.displayName=av;var Gj="PopperAnchor",Kj=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,l=qj(Gj,n),u=b.useRef(null),f=l.onAnchorChange,h=b.useCallback(j=>{u.current=j,j&&f(j)},[f]),m=Zt(t,h),y=b.useRef(null);b.useEffect(()=>{if(!r)return;const j=y.current;y.current=r.current,j!==y.current&&f(y.current)});const g=l.placementState&&ov(l.placementState),w=g?.[0],x=g?.[1];return r?null:o.jsx(lt.div,{"data-radix-popper-side":w,"data-radix-popper-align":x,...i,ref:m})});Kj.displayName=Gj;var iv="PopperContent",[FA,IA]=Hj(iv),Zj=b.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:l="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:h=!0,collisionBoundary:m=[],collisionPadding:y=0,sticky:g="partial",hideWhenDetached:w=!1,updatePositionStrategy:x="optimized",onPlaced:j,...S}=e,E=qj(iv,n),[_,N]=b.useState(null),R=Zt(t,N),[T,A]=b.useState(null),M=RO(T),L=M?.width??0,H=M?.height??0,U=r+(l!=="center"?"-"+l:""),Z=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},X=Array.isArray(m)?m:[m],Q=X.length>0,ae={padding:Z,boundary:X.filter(UA),altBoundary:Q},{refs:le,floatingStyles:be,placement:$,isPositioned:q,middlewareData:V}=EA({strategy:"fixed",placement:U,whileElementsMounted:(...we)=>gA(...we,{animationFrame:x==="always"}),elements:{reference:E.anchor},middleware:[kA({mainAxis:i+H,alignmentAxis:u}),h&&RA({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?MA():void 0,...ae}),h&&TA({...ae}),OA({...ae,apply:({elements:we,rects:Se,availableWidth:ve,availableHeight:Me})=>{const{width:Ye,height:ht}=Se.reference,tt=we.floating.style;tt.setProperty("--radix-popper-available-width",`${ve}px`),tt.setProperty("--radix-popper-available-height",`${Me}px`),tt.setProperty("--radix-popper-anchor-width",`${Ye}px`),tt.setProperty("--radix-popper-anchor-height",`${ht}px`)}}),T&&DA({element:T,padding:f}),VA({arrowWidth:L,arrowHeight:H}),w&&AA({strategy:"referenceHidden",...ae,boundary:Q?ae.boundary:void 0})]}),ee=E.setPlacementState;ar(()=>(ee($),()=>{ee(void 0)}),[$,ee]);const[K,O]=ov($),D=Pr(j);ar(()=>{q&&D?.()},[q,D]);const B=V.arrow?.x,P=V.arrow?.y,I=V.arrow?.centerOffset!==0,[re,he]=b.useState();return ar(()=>{_&&he(window.getComputedStyle(_).zIndex)},[_]),o.jsx("div",{ref:le.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:q?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(FA,{scope:n,placedSide:K,placedAlign:O,onArrowChange:A,arrowX:B,arrowY:P,shouldHideArrow:I,children:o.jsx(lt.div,{"data-side":K,"data-align":O,...S,ref:R,style:{...S.style,animation:q?void 0:"none"}})})})});Zj.displayName=iv;var Yj="PopperArrow",PA={top:"bottom",right:"left",bottom:"top",left:"right"},Qj=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,l=IA(Yj,r),u=PA[l.placedSide];return o.jsx("span",{ref:l.onArrowChange,style:{position:"absolute",left:l.arrowX,top:l.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[l.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[l.placedSide],visibility:l.shouldHideArrow?"hidden":void 0},children:o.jsx(LA,{...i,ref:n,style:{...i.style,display:"block"}})})});Qj.displayName=Yj;function UA(e){return e!==null}var VA=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,u=i.arrow?.centerOffset!==0,f=u?0:e.arrowWidth,h=u?0:e.arrowHeight,[m,y]=ov(n),g={start:"0%",center:"50%",end:"100%"}[y],w=(i.arrow?.x??0)+f/2,x=(i.arrow?.y??0)+h/2;let j="",S="";return m==="bottom"?(j=u?g:`${w}px`,S=`${-h}px`):m==="top"?(j=u?g:`${w}px`,S=`${r.floating.height+h}px`):m==="right"?(j=`${-h}px`,S=u?g:`${x}px`):m==="left"&&(j=`${r.floating.width+h}px`,S=u?g:`${x}px`),{data:{x:j,y:S}}}});function ov(e){const[t,n="center"]=e.split("-");return[t,n]}var Xj=Bj,Wj=Kj,Jj=Zj,eC=Qj,Jm=!1;function HA(){const[e,t]=b.useState(Jm);return b.useEffect(()=>{Jm||(Jm=!0,t(!0))},[]),e}var tC=Vd[" useSyncExternalStore ".trim().toString()];function qA(){return()=>{}}function BA(){return tC(qA,()=>!0,()=>!1)}var GA=typeof tC=="function"?BA:HA,ep="rovingFocusGroup.onEntryFocus",KA={bubbles:!1,cancelable:!0},ic="RovingFocusGroup",[Up,nC,ZA]=oj(ic),[YA,sC]=Na(ic,[ZA]),[QA,XA]=YA(ic),rC=b.forwardRef((e,t)=>o.jsx(Up.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Up.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(WA,{...e,ref:t})})}));rC.displayName=ic;var WA=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:l,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:h,onEntryFocus:m,preventScrollOnEntryFocus:y=!1,...g}=e,w=b.useRef(null),x=Zt(t,w),j=lj(l),[S,E]=ac({prop:u,defaultProp:f??null,onChange:h,caller:ic}),[_,N]=b.useState(!1),R=Pr(m),T=nC(n),A=b.useRef(!1),[M,L]=b.useState(0);return b.useEffect(()=>{const H=w.current;if(H)return H.addEventListener(ep,R),()=>H.removeEventListener(ep,R)},[R]),o.jsx(QA,{scope:n,orientation:r,dir:j,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(H=>E(H),[E]),onItemShiftTab:b.useCallback(()=>N(!0),[]),onFocusableItemAdd:b.useCallback(()=>L(H=>H+1),[]),onFocusableItemRemove:b.useCallback(()=>L(H=>H-1),[]),children:o.jsx(lt.div,{tabIndex:_||M===0?-1:0,"data-orientation":r,...g,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{A.current=!0}),onFocus:Ue(e.onFocus,H=>{const U=!A.current;if(H.target===H.currentTarget&&U&&!_){const Z=new CustomEvent(ep,KA);if(H.currentTarget.dispatchEvent(Z),!Z.defaultPrevented){const X=T().filter($=>$.focusable),Q=X.find($=>$.active),ae=X.find($=>$.id===S),be=[Q,ae,...X].filter(Boolean).map($=>$.ref.current);oC(be,y)}}A.current=!1}),onBlur:Ue(e.onBlur,()=>N(!1))})})}),aC="RovingFocusGroupItem",iC=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:l,children:u,...f}=e,h=ds(),m=l||h,y=XA(aC,n),g=y.currentTabStopId===m,w=nC(n),{onFocusableItemAdd:x,onFocusableItemRemove:j,currentTabStopId:S}=y,E=GA();return ar(()=>{if(!(!E||!r))return x(),()=>j()},[E,r,x,j]),b.useEffect(()=>{if(!(E||!r))return x(),()=>j()},[E,r,x,j]),o.jsx(Up.ItemSlot,{scope:n,id:m,focusable:r,active:i,children:o.jsx(lt.span,{tabIndex:g?0:-1,"data-orientation":y.orientation,...f,ref:t,onMouseDown:Ue(e.onMouseDown,_=>{r?y.onItemFocus(m):_.preventDefault()}),onFocus:Ue(e.onFocus,()=>y.onItemFocus(m)),onKeyDown:Ue(e.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){y.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const N=tD(_,y.orientation,y.dir);if(N!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let T=w().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(_.currentTarget);T=y.loop?nD(T,A+1):T.slice(A+1)}setTimeout(()=>oC(T))}}),children:typeof u=="function"?u({isCurrentTabStop:g,hasTabStop:S!=null}):u})})});iC.displayName=aC;var JA={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function eD(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function tD(e,t,n){const r=eD(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JA[r]}function oC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function nD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var sD=rC,rD=iC,Vp=["Enter"," "],aD=["ArrowDown","PageUp","Home"],lC=["ArrowUp","PageDown","End"],iD=[...aD,...lC],oD={ltr:[...Vp,"ArrowRight"],rtl:[...Vp,"ArrowLeft"]},lD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oc="Menu",[Zl,cD,uD]=oj(oc),[bi,tf]=Na(oc,[uD,ef,sC]),nf=ef(),cC=sC(),[dD,wi]=bi(oc),[fD,lc]=bi(oc),uC=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:l,modal:u=!0}=e,f=nf(t),[h,m]=b.useState(null),y=b.useRef(!1),g=Pr(l),w=lj(i);return b.useEffect(()=>{const x=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),b.useEffect(()=>{if(!n)return;const x=()=>g(!1);return window.addEventListener("blur",x),()=>window.removeEventListener("blur",x)},[n,g]),o.jsx(Xj,{...f,children:o.jsx(dD,{scope:t,open:n,onOpenChange:g,content:h,onContentChange:m,children:o.jsx(fD,{scope:t,onClose:b.useCallback(()=>g(!1),[g]),isUsingKeyboardRef:y,dir:w,modal:u,children:r})})})};uC.displayName=oc;var hD="MenuAnchor",lv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(Wj,{...i,...r,ref:t})});lv.displayName=hD;var cv="MenuPortal",[mD,dC]=bi(cv,{forceMount:void 0}),fC=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,l=wi(cv,t);return o.jsx(mD,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};fC.displayName=cv;var Ts="MenuContent",[pD,uv]=bi(Ts),hC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,l=wi(Ts,e.__scopeMenu),u=lc(Ts,e.__scopeMenu);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||l.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:u.modal?o.jsx(gD,{...i,ref:t}):o.jsx(vD,{...i,ref:t})})})})}),gD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu),r=b.useRef(null),i=Zt(t,r);return b.useEffect(()=>{const l=r.current;if(l)return bj(l)},[]),o.jsx(dv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vD=b.forwardRef((e,t)=>{const n=wi(Ts,e.__scopeMenu);return o.jsx(dv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yD=No("MenuContent.ScrollLock"),dv=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:h,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,disableOutsideScroll:j,...S}=e,E=wi(Ts,n),_=lc(Ts,n),N=nf(n),R=cC(n),T=cD(n),[A,M]=b.useState(null),L=b.useRef(null),H=Zt(t,L,E.onContentChange),U=b.useRef(0),Z=b.useRef(""),X=b.useRef(0),Q=b.useRef(null),ae=b.useRef("right"),le=b.useRef(0),be=j?Gg:b.Fragment,$=j?{as:yD,allowPinchZoom:!0}:void 0,q=ee=>{const K=Z.current+ee,O=T().filter(he=>!he.disabled),D=document.activeElement,B=O.find(he=>he.ref.current===D)?.textValue,P=O.map(he=>he.textValue),I=MD(P,K,B),re=O.find(he=>he.textValue===I)?.ref.current;(function he(we){Z.current=we,window.clearTimeout(U.current),we!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),re&&setTimeout(()=>re.focus())};b.useEffect(()=>()=>window.clearTimeout(U.current),[]),dj();const V=b.useCallback(ee=>ae.current===Q.current?.side&&OD(ee,Q.current?.area),[]);return o.jsx(pD,{scope:n,searchRef:Z,onItemEnter:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),onItemLeave:b.useCallback(ee=>{V(ee)||(L.current?.focus(),M(null))},[V]),onTriggerLeave:b.useCallback(ee=>{V(ee)&&ee.preventDefault()},[V]),pointerGraceTimerRef:X,onPointerGraceIntentChange:b.useCallback(ee=>{Q.current=ee},[]),children:o.jsx(be,{...$,children:o.jsx(Bg,{asChild:!0,trapped:i,onMountAutoFocus:Ue(l,ee=>{ee.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:m,onPointerDownOutside:y,onFocusOutside:g,onInteractOutside:w,onDismiss:x,children:o.jsx(sD,{asChild:!0,...R,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:M,onEntryFocus:Ue(h,ee=>{_.isUsingKeyboardRef.current||ee.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Jj,{role:"menu","aria-orientation":"vertical","data-state":RC(E.open),"data-radix-menu-content":"",dir:_.dir,...N,...S,ref:H,style:{outline:"none",...S.style},onKeyDown:Ue(S.onKeyDown,ee=>{const O=ee.target.closest("[data-radix-menu-content]")===ee.currentTarget,D=ee.ctrlKey||ee.altKey||ee.metaKey,B=ee.key.length===1;O&&(ee.key==="Tab"&&ee.preventDefault(),!D&&B&&q(ee.key));const P=L.current;if(ee.target!==P||!iD.includes(ee.key))return;ee.preventDefault();const re=T().filter(he=>!he.disabled).map(he=>he.ref.current);lC.includes(ee.key)&&re.reverse(),kD(re)}),onBlur:Ue(e.onBlur,ee=>{ee.currentTarget.contains(ee.target)||(window.clearTimeout(U.current),Z.current="")}),onPointerMove:Ue(e.onPointerMove,Yl(ee=>{const K=ee.target,O=le.current!==ee.clientX;if(ee.currentTarget.contains(K)&&O){const D=ee.clientX>le.current?"right":"left";ae.current=D,le.current=ee.clientX}}))})})})})})})});hC.displayName=Ts;var xD="MenuGroup",fv=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"group",...r,ref:t})});fv.displayName=xD;var bD="MenuLabel",mC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{...r,ref:t})});mC.displayName=bD;var jd="MenuItem",Hw="menu.itemSelect",sf=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,l=b.useRef(null),u=lc(jd,e.__scopeMenu),f=uv(jd,e.__scopeMenu),h=Zt(t,l),m=b.useRef(!1),y=()=>{const g=l.current;if(!n&&g){const w=new CustomEvent(Hw,{bubbles:!0,cancelable:!0});g.addEventListener(Hw,x=>r?.(x),{once:!0}),aj(g,w),w.defaultPrevented?m.current=!1:u.onClose()}};return o.jsx(pC,{...i,ref:h,disabled:n,onClick:Ue(e.onClick,y),onPointerDown:g=>{e.onPointerDown?.(g),m.current=!0},onPointerUp:Ue(e.onPointerUp,g=>{m.current||g.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,g=>{n||g.target!==g.currentTarget||f.searchRef.current!==""&&g.key===" "||Vp.includes(g.key)&&(g.currentTarget.click(),g.preventDefault())})})});sf.displayName=jd;var pC=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...l}=e,u=uv(jd,n),f=cC(n),h=b.useRef(null),m=Zt(t,h),[y,g]=b.useState(!1),[w,x]=b.useState("");return b.useEffect(()=>{const j=h.current;j&&x((j.textContent??"").trim())},[l.children]),o.jsx(Zl.ItemSlot,{scope:n,disabled:r,textValue:i??w,children:o.jsx(rD,{asChild:!0,...f,focusable:!r,children:o.jsx(lt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...l,ref:m,onPointerMove:Ue(e.onPointerMove,Yl(j=>{r?u.onItemLeave(j):(u.onItemEnter(j),j.defaultPrevented||j.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Yl(j=>u.onItemLeave(j))),onFocus:Ue(e.onFocus,()=>g(!0)),onBlur:Ue(e.onBlur,()=>g(!1))})})})}),wD="MenuCheckboxItem",gC=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o.jsx(wC,{scope:e.__scopeMenu,checked:n,children:o.jsx(sf,{role:"menuitemcheckbox","aria-checked":Cd(n)?"mixed":n,...i,ref:t,"data-state":mv(n),onSelect:Ue(i.onSelect,()=>r?.(Cd(n)?!0:!n),{checkForDefaultPrevented:!1})})})});gC.displayName=wD;var vC="MenuRadioGroup",[SD,jD]=bi(vC,{value:void 0,onValueChange:()=>{}}),yC=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,l=Pr(r);return o.jsx(SD,{scope:e.__scopeMenu,value:n,onValueChange:l,children:o.jsx(fv,{...i,ref:t})})});yC.displayName=vC;var xC="MenuRadioItem",bC=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=jD(xC,e.__scopeMenu),l=n===i.value;return o.jsx(wC,{scope:e.__scopeMenu,checked:l,children:o.jsx(sf,{role:"menuitemradio","aria-checked":l,...r,ref:t,"data-state":mv(l),onSelect:Ue(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});bC.displayName=xC;var hv="MenuItemIndicator",[wC,CD]=bi(hv,{checked:!1}),SC=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,l=CD(hv,n);return o.jsx(dr,{present:r||Cd(l.checked)||l.checked===!0,children:o.jsx(lt.span,{...i,ref:t,"data-state":mv(l.checked)})})});SC.displayName=hv;var _D="MenuSeparator",jC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(lt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});jC.displayName=_D;var ED="MenuArrow",CC=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=nf(n);return o.jsx(eC,{...i,...r,ref:t})});CC.displayName=ED;var ND="MenuSub",[UB,_C]=bi(ND),$l="MenuSubTrigger",EC=b.forwardRef((e,t)=>{const n=wi($l,e.__scopeMenu),r=lc($l,e.__scopeMenu),i=_C($l,e.__scopeMenu),l=uv($l,e.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:h}=l,m={__scopeMenu:e.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);b.useEffect(()=>y,[y]),b.useEffect(()=>{const w=f.current;return()=>{window.clearTimeout(w),h(null)}},[f,h]);const g=Zt(t,i.onTriggerChange);return o.jsx(lv,{asChild:!0,...m,children:o.jsx(pC,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":RC(n.open),...e,ref:g,onClick:w=>{e.onClick?.(w),!(e.disabled||w.defaultPrevented)&&(w.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Yl(w=>{l.onItemEnter(w),!w.defaultPrevented&&!e.disabled&&!n.open&&!u.current&&(l.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{n.onOpenChange(!0),y()},100))})),onPointerLeave:Ue(e.onPointerLeave,Yl(w=>{y();const x=n.content?.getBoundingClientRect();if(x){const j=n.content?.dataset.side,S=j==="right",E=S?-5:5,_=x[S?"left":"right"],N=x[S?"right":"left"];l.onPointerGraceIntentChange({area:[{x:w.clientX+E,y:w.clientY},{x:_,y:x.top},{x:N,y:x.top},{x:N,y:x.bottom},{x:_,y:x.bottom}],side:j}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(w),w.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,w=>{e.disabled||w.target!==w.currentTarget||l.searchRef.current!==""&&w.key===" "||oD[r.dir].includes(w.key)&&(n.onOpenChange(!0),n.content?.focus(),w.preventDefault())})})})});EC.displayName=$l;var NC="MenuSubContent",kC=b.forwardRef((e,t)=>{const n=dC(Ts,e.__scopeMenu),{forceMount:r=n.forceMount,align:i="start",...l}=e,u=wi(Ts,e.__scopeMenu),f=lc(Ts,e.__scopeMenu),h=_C(NC,e.__scopeMenu),m=b.useRef(null),y=Zt(t,m);return o.jsx(Zl.Provider,{scope:e.__scopeMenu,children:o.jsx(dr,{present:r||u.open,children:o.jsx(Zl.Slot,{scope:e.__scopeMenu,children:o.jsx(dv,{id:h.contentId,"aria-labelledby":h.triggerId,...l,ref:y,align:i,side:f.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:g=>{f.isUsingKeyboardRef.current&&m.current?.focus(),g.preventDefault()},onCloseAutoFocus:g=>g.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,g=>{g.target!==h.trigger&&u.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,g=>{f.onClose(),g.preventDefault()}),onKeyDown:Ue(e.onKeyDown,g=>{const w=g.currentTarget.contains(g.target),x=lD[f.dir].includes(g.key);w&&x&&(u.onOpenChange(!1),h.trigger?.focus(),g.preventDefault())})})})})})});kC.displayName=NC;function RC(e){return e?"open":"closed"}function Cd(e){return e==="indeterminate"}function mv(e){return Cd(e)?"indeterminate":e?"checked":"unchecked"}function kD(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RD(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function MD(e,t,n){const i=t.length>1&&Array.from(t).every(m=>m===t[0])?t[0]:t,l=n?e.indexOf(n):-1;let u=RD(e,Math.max(l,0));i.length===1&&(u=u.filter(m=>m!==n));const h=u.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return h!==n?h:void 0}function TD(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function OD(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TD(n,t)}function Yl(e){return t=>t.pointerType==="mouse"?e(t):void 0}var MC=uC,TC=lv,OC=fC,AC=hC,DC=fv,zC=mC,LC=sf,$C=gC,FC=yC,IC=bC,PC=SC,UC=jC,VC=CC,HC=EC,qC=kC,rf="ContextMenu",[AD]=Na(rf,[tf]),Un=tf(),[DD,BC]=AD(rf),GC=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,dir:l,modal:u=!0}=e,f=b.useRef(!1);{const g=b.useRef(!1);b.useEffect(()=>{i===!0&&!f.current&&!g.current&&(g.current=!0,console.warn("ContextMenu: The `open` prop has been set to `true` before the user has interacted with the trigger, so its position is indeterminate. This is likely unintended and will result in the menu being anchored to the top-left corner of the viewport."))},[i])}const[h,m]=ac({prop:i,defaultProp:!1,onChange:r,caller:rf}),y=Un(t);return o.jsx(DD,{scope:t,open:h,onOpenChange:m,modal:u,hasInteractedRef:f,children:o.jsx(MC,{...y,dir:l,open:h,onOpenChange:m,modal:u,children:n})})};GC.displayName=rf;var KC="ContextMenuTrigger",ZC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,l=BC(KC,n),u=Un(n),[f,h]=b.useState({x:0,y:0}),m=b.useMemo(()=>({current:{getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...f})}}),[f]),y=b.useRef(0),g=b.useCallback(()=>window.clearTimeout(y.current),[]),w=x=>{l.hasInteractedRef.current=!0,h({x:x.clientX,y:x.clientY}),l.onOpenChange(!0)};return b.useEffect(()=>g,[g]),b.useEffect(()=>{r&&g()},[r,g]),o.jsxs(o.Fragment,{children:[o.jsx(TC,{...u,virtualRef:m}),o.jsx(lt.span,{"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:Ue(e.onContextMenu,x=>{g(),w(x),x.preventDefault()}),onPointerDown:r?e.onPointerDown:Ue(e.onPointerDown,Pu(x=>{g(),l.open&&l.onOpenChange(!1),y.current=window.setTimeout(()=>w(x),700)})),onPointerMove:r?e.onPointerMove:Ue(e.onPointerMove,Pu(g)),onPointerCancel:r?e.onPointerCancel:Ue(e.onPointerCancel,Pu(g)),onPointerUp:r?e.onPointerUp:Ue(e.onPointerUp,Pu(g))})]})});ZC.displayName=KC;var zD="ContextMenuPortal",YC=e=>{const{__scopeContextMenu:t,...n}=e,r=Un(t);return o.jsx(OC,{...r,...n})};YC.displayName=zD;var QC="ContextMenuContent",XC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=BC(QC,n),l=Un(n),u=b.useRef(!1);return o.jsx(AC,{...l,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:f=>{e.onCloseAutoFocus?.(f),!f.defaultPrevented&&u.current&&f.preventDefault(),u.current=!1},onInteractOutside:f=>{e.onInteractOutside?.(f),!f.defaultPrevented&&!i.modal&&(u.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});XC.displayName=QC;var LD="ContextMenuGroup",$D=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(DC,{...i,...r,ref:t})});$D.displayName=LD;var FD="ContextMenuLabel",ID=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(zC,{...i,...r,ref:t})});ID.displayName=FD;var PD="ContextMenuItem",WC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(LC,{...i,...r,ref:t})});WC.displayName=PD;var UD="ContextMenuCheckboxItem",VD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx($C,{...i,...r,ref:t})});VD.displayName=UD;var HD="ContextMenuRadioGroup",qD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(FC,{...i,...r,ref:t})});qD.displayName=HD;var BD="ContextMenuRadioItem",GD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(IC,{...i,...r,ref:t})});GD.displayName=BD;var KD="ContextMenuItemIndicator",ZD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(PC,{...i,...r,ref:t})});ZD.displayName=KD;var YD="ContextMenuSeparator",JC=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(UC,{...i,...r,ref:t})});JC.displayName=YD;var QD="ContextMenuArrow",XD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(VC,{...i,...r,ref:t})});XD.displayName=QD;var WD="ContextMenuSubTrigger",JD=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(HC,{...i,...r,ref:t})});JD.displayName=WD;var ez="ContextMenuSubContent",tz=b.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Un(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tz.displayName=ez;function Pu(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var nz=GC,sz=ZC,rz=YC,az=XC,iz=WC,oz=JC,af="DropdownMenu",[lz]=Na(af,[tf]),Vn=tf(),[cz,e_]=lz(af),t_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:l,onOpenChange:u,modal:f=!0}=e,h=Vn(t),m=b.useRef(null),[y,g]=ac({prop:i,defaultProp:l??!1,onChange:u,caller:af});return o.jsx(cz,{scope:t,triggerId:ds(),triggerRef:m,contentId:ds(),open:y,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(w=>!w),[g]),modal:f,children:o.jsx(MC,{...h,open:y,onOpenChange:g,dir:r,modal:f,children:n})})};t_.displayName=af;var n_="DropdownMenuTrigger",s_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,l=e_(n_,n),u=Vn(n),f=Zt(t,l.triggerRef);return o.jsx(TC,{asChild:!0,...u,children:o.jsx(lt.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:f,onPointerDown:Ue(e.onPointerDown,h=>{!r&&h.button===0&&h.ctrlKey===!1&&(l.onOpenToggle(),l.open||h.preventDefault())}),onKeyDown:Ue(e.onKeyDown,h=>{r||(["Enter"," "].includes(h.key)&&l.onOpenToggle(),h.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(h.key)&&h.preventDefault())})})})});s_.displayName=n_;var uz="DropdownMenuPortal",r_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Vn(t);return o.jsx(OC,{...r,...n})};r_.displayName=uz;var a_="DropdownMenuContent",i_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=e_(a_,n),l=Vn(n),u=b.useRef(!1);return o.jsx(AC,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,f=>{u.current||i.triggerRef.current?.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,f=>{const h=f.detail.originalEvent,m=h.button===0&&h.ctrlKey===!0,y=h.button===2||m;(!i.modal||y)&&(u.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});i_.displayName=a_;var dz="DropdownMenuGroup",fz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(DC,{...i,...r,ref:t})});fz.displayName=dz;var hz="DropdownMenuLabel",o_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(zC,{...i,...r,ref:t})});o_.displayName=hz;var mz="DropdownMenuItem",l_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(LC,{...i,...r,ref:t})});l_.displayName=mz;var pz="DropdownMenuCheckboxItem",gz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx($C,{...i,...r,ref:t})});gz.displayName=pz;var vz="DropdownMenuRadioGroup",c_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(FC,{...i,...r,ref:t})});c_.displayName=vz;var yz="DropdownMenuRadioItem",u_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(IC,{...i,...r,ref:t})});u_.displayName=yz;var xz="DropdownMenuItemIndicator",d_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(PC,{...i,...r,ref:t})});d_.displayName=xz;var bz="DropdownMenuSeparator",f_=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(UC,{...i,...r,ref:t})});f_.displayName=bz;var wz="DropdownMenuArrow",Sz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(VC,{...i,...r,ref:t})});Sz.displayName=wz;var jz="DropdownMenuSubTrigger",Cz=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(HC,{...i,...r,ref:t})});Cz.displayName=jz;var _z="DropdownMenuSubContent",Ez=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Vn(n);return o.jsx(qC,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Ez.displayName=_z;var Nz=t_,kz=s_,Rz=r_,Mz=i_,Tz=o_,Oz=l_,Az=c_,Dz=u_,zz=d_,Lz=f_,$z="Label",h_=b.forwardRef((e,t)=>o.jsx(lt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));h_.displayName=$z;var Fz=h_,Iz="Separator",qw="horizontal",Pz=["horizontal","vertical"],m_=b.forwardRef((e,t)=>{const{decorative:n,orientation:r=qw,...i}=e,l=Uz(r)?r:qw,f=n?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return o.jsx(lt.div,{"data-orientation":l,...f,...i,ref:t})});m_.displayName=Iz;function Uz(e){return Pz.includes(e)}var Vz=m_,[of]=Na("Tooltip",[ef]),lf=ef(),p_="TooltipProvider",Hz=700,Hp="tooltip.open",[qz,pv]=of(p_),g_=e=>{const{__scopeTooltip:t,delayDuration:n=Hz,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:l}=e,u=b.useRef(!0),f=b.useRef(!1),h=b.useRef(0);return b.useEffect(()=>{const m=h.current;return()=>window.clearTimeout(m)},[]),o.jsx(qz,{scope:t,isOpenDelayedRef:u,delayDuration:n,onOpen:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),u.current=!1)},[r]),onClose:b.useCallback(()=>{r<=0||(window.clearTimeout(h.current),h.current=window.setTimeout(()=>u.current=!0,r))},[r]),isPointerInTransitRef:f,onPointerInTransitChange:b.useCallback(m=>{f.current=m},[]),disableHoverableContent:i,children:l})};g_.displayName=p_;var Ql="Tooltip",[Bz,cc]=of(Ql),v_=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:l,disableHoverableContent:u,delayDuration:f}=e,h=pv(Ql,e.__scopeTooltip),m=lf(t),[y,g]=b.useState(null),w=ds(),x=b.useRef(0),j=u??h.disableHoverableContent,S=f??h.delayDuration,E=b.useRef(!1),[_,N]=ac({prop:r,defaultProp:i??!1,onChange:L=>{L?(h.onOpen(),document.dispatchEvent(new CustomEvent(Hp))):h.onClose(),l?.(L)},caller:Ql}),R=b.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),T=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,E.current=!1,N(!0)},[N]),A=b.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),M=b.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{E.current=!0,N(!0),x.current=0},S)},[S,N]);return b.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),o.jsx(Xj,{...m,children:o.jsx(Bz,{scope:t,contentId:w,open:_,stateAttribute:R,trigger:y,onTriggerChange:g,onTriggerEnter:b.useCallback(()=>{h.isOpenDelayedRef.current?M():T()},[h.isOpenDelayedRef,M,T]),onTriggerLeave:b.useCallback(()=>{j?A():(window.clearTimeout(x.current),x.current=0)},[A,j]),onOpen:T,onClose:A,disableHoverableContent:j,children:n})})};v_.displayName=Ql;var qp="TooltipTrigger",y_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=cc(qp,n),l=pv(qp,n),u=lf(n),f=b.useRef(null),h=Zt(t,f,i.onTriggerChange),m=b.useRef(!1),y=b.useRef(!1),g=b.useCallback(()=>m.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),o.jsx(Wj,{asChild:!0,...u,children:o.jsx(lt.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:h,onPointerMove:Ue(e.onPointerMove,w=>{w.pointerType!=="touch"&&!y.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Ue(e.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Ue(e.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:Ue(e.onFocus,()=>{m.current||i.onOpen()}),onBlur:Ue(e.onBlur,i.onClose),onClick:Ue(e.onClick,i.onClose)})})});y_.displayName=qp;var gv="TooltipPortal",[Gz,Kz]=of(gv,{forceMount:void 0}),x_=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,l=cc(gv,t);return o.jsx(Gz,{scope:t,forceMount:n,children:o.jsx(dr,{present:n||l.open,children:o.jsx(Gd,{asChild:!0,container:i,children:r})})})};x_.displayName=gv;var Ro="TooltipContent",b_=b.forwardRef((e,t)=>{const n=Kz(Ro,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...l}=e,u=cc(Ro,e.__scopeTooltip);return o.jsx(dr,{present:r||u.open,children:u.disableHoverableContent?o.jsx(w_,{side:i,...l,ref:t}):o.jsx(Zz,{side:i,...l,ref:t})})}),Zz=b.forwardRef((e,t)=>{const n=cc(Ro,e.__scopeTooltip),r=pv(Ro,e.__scopeTooltip),i=b.useRef(null),l=Zt(t,i),[u,f]=b.useState(null),{trigger:h,onClose:m}=n,y=i.current,{onPointerInTransitChange:g}=r,w=b.useCallback(()=>{f(null),g(!1)},[g]),x=b.useCallback((j,S)=>{const E=j.currentTarget,_={x:j.clientX,y:j.clientY},N=Wz(_,E.getBoundingClientRect()),R=Jz(_,N),T=e4(S.getBoundingClientRect()),A=n4([...R,...T]);f(A),g(!0)},[g]);return b.useEffect(()=>()=>w(),[w]),b.useEffect(()=>{if(h&&y){const j=E=>x(E,y),S=E=>x(E,h);return h.addEventListener("pointerleave",j),y.addEventListener("pointerleave",S),()=>{h.removeEventListener("pointerleave",j),y.removeEventListener("pointerleave",S)}}},[h,y,x,w]),b.useEffect(()=>{if(u){const j=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},N=h?.contains(E)||y?.contains(E),R=!t4(_,u);N?w():R&&(w(),m())};return document.addEventListener("pointermove",j),()=>document.removeEventListener("pointermove",j)}},[h,y,u,m,w]),o.jsx(w_,{...e,ref:l})}),[Yz,Qz]=of(Ql,{isInside:!1}),Xz=QM("TooltipContent"),w_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:l,onPointerDownOutside:u,...f}=e,h=cc(Ro,n),m=lf(n),{onClose:y}=h;return b.useEffect(()=>(document.addEventListener(Hp,y),()=>document.removeEventListener(Hp,y)),[y]),b.useEffect(()=>{if(h.trigger){const g=w=>{w.target instanceof Node&&w.target.contains(h.trigger)&&y()};return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[h.trigger,y]),o.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:g=>g.preventDefault(),onDismiss:y,children:o.jsxs(Jj,{"data-state":h.stateAttribute,...m,...f,ref:t,style:{...f.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o.jsx(Xz,{children:r}),o.jsx(Yz,{scope:n,isInside:!0,children:o.jsx(lT,{id:h.contentId,role:"tooltip",children:i||r})})]})})});b_.displayName=Ro;var S_="TooltipArrow",j_=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=lf(n);return Qz(S_,n).isInside?null:o.jsx(eC,{...i,...r,ref:t})});j_.displayName=S_;function Wz(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),l=Math.abs(t.left-e.x);switch(Math.min(n,r,i,l)){case l:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Jz(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function e4(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function t4(e,t){const{x:n,y:r}=e;let i=!1;for(let l=0,u=t.length-1;lr!=w>r&&n<(g-m)*(r-y)/(w-y)+m&&(i=!i)}return i}function n4(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),s4(t)}function s4(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const l=t[t.length-1],u=t[t.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const l=n[n.length-1],u=n[n.length-2];if((l.x-u.x)*(i.y-u.y)>=(l.y-u.y)*(i.x-u.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var r4=g_,a4=v_,i4=y_,o4=x_,l4=b_,c4=j_;function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const n=new Array(e.length+t.length);for(let r=0;r({classGroupId:e,validator:t}),E_=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),_d="-",Bw=[],f4="arbitrary..",h4=e=>{const t=p4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return m4(u);const f=u.split(_d),h=f[0]===""&&f.length>1?1:0;return N_(f,h,t)},getConflictingClassGroupIds:(u,f)=>{if(f){const h=r[u],m=n[u];return h?m?u4(m,h):h:m||Bw}return n[u]||Bw}}},N_=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const i=e[t],l=n.nextPart.get(i);if(l){const m=N_(e,t+1,l);if(m)return m}const u=n.validators;if(u===null)return;const f=t===0?e.join(_d):e.slice(t).join(_d),h=u.length;for(let m=0;me.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?f4+r:void 0})(),p4=e=>{const{theme:t,classGroups:n}=e;return g4(n,t)},g4=(e,t)=>{const n=E_();for(const r in e){const i=e[r];vv(i,n,r,t)}return n},vv=(e,t,n,r)=>{const i=e.length;for(let l=0;l{if(typeof e=="string"){y4(e,t,n);return}if(typeof e=="function"){x4(e,t,n,r);return}b4(e,t,n,r)},y4=(e,t,n)=>{const r=e===""?t:k_(t,e);r.classGroupId=n},x4=(e,t,n,r)=>{if(w4(e)){vv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(d4(n,e))},b4=(e,t,n,r)=>{const i=Object.entries(e),l=i.length;for(let u=0;u{let n=e;const r=t.split(_d),i=r.length;for(let l=0;l"isThemeGetter"in e&&e.isThemeGetter===!0,S4=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(l,u)=>{n[l]=u,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(l){let u=n[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return i(l,u),u},set(l,u){l in n?n[l]=u:i(l,u)}}},Bp="!",Gw=":",j4=[],Kw=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),C4=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=i=>{const l=[];let u=0,f=0,h=0,m;const y=i.length;for(let S=0;Sh?m-h:void 0;return Kw(l,x,w,j)};if(t){const i=t+Gw,l=r;r=u=>u.startsWith(i)?l(u.slice(i.length)):Kw(j4,!1,u,void 0,!0)}if(n){const i=r;r=l=>n({className:l,parseClassName:i})}return r},_4=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let i=[];for(let l=0;l0&&(i.sort(),r.push(...i),i=[]),r.push(u)):i.push(u)}return i.length>0&&(i.sort(),r.push(...i)),r}},E4=e=>({cache:S4(e.cacheSize),parseClassName:C4(e),sortModifiers:_4(e),postfixLookupClassGroupIds:N4(e),...h4(e)}),N4=e=>{const t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let r=0;r{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:l,postfixLookupClassGroupIds:u}=t,f=[],h=e.trim().split(k4);let m="";for(let y=h.length-1;y>=0;y-=1){const g=h[y],{isExternal:w,modifiers:x,hasImportantModifier:j,baseClassName:S,maybePostfixModifierPosition:E}=n(g);if(w){m=g+(m.length>0?" "+m:m);continue}let _=!!E,N;if(_){const L=S.substring(0,E);N=r(L);const H=N&&u[N]?r(S):void 0;H&&H!==N&&(N=H,_=!1)}else N=r(S);if(!N){if(!_){m=g+(m.length>0?" "+m:m);continue}if(N=r(S),!N){m=g+(m.length>0?" "+m:m);continue}_=!1}const R=x.length===0?"":x.length===1?x[0]:l(x).join(":"),T=j?R+Bp:R,A=T+N;if(f.indexOf(A)>-1)continue;f.push(A);const M=i(N,_);for(let L=0;L0?" "+m:m)}return m},M4=(...e)=>{let t=0,n,r,i="";for(;t{if(typeof e=="string")return e;let t,n="";for(let r=0;r{let n,r,i,l;const u=h=>{const m=t.reduce((y,g)=>g(y),e());return n=E4(m),r=n.cache.get,i=n.cache.set,l=f,f(h)},f=h=>{const m=r(h);if(m)return m;const y=R4(h,n);return i(h,y),y};return l=u,(...h)=>l(M4(...h))},O4=[],cn=e=>{const t=n=>n[e]||O4;return t.isThemeGetter=!0,t},M_=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,T_=/^\((?:(\w[\w-]*):)?(.+)\)$/i,A4=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D4=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,z4=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,L4=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$4=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,F4=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,va=e=>A4.test(e),Xe=e=>!!e&&!Number.isNaN(Number(e)),Js=e=>!!e&&Number.isInteger(Number(e)),tp=e=>e.endsWith("%")&&Xe(e.slice(0,-1)),Ar=e=>D4.test(e),O_=()=>!0,I4=e=>z4.test(e)&&!L4.test(e),yv=()=>!1,P4=e=>$4.test(e),U4=e=>F4.test(e),V4=e=>!Re(e)&&!Te(e),H4=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),q4=e=>Ra(e,z_,yv),Re=e=>M_.test(e),ni=e=>Ra(e,L_,I4),Zw=e=>Ra(e,W4,Xe),B4=e=>Ra(e,F_,O_),G4=e=>Ra(e,$_,yv),Yw=e=>Ra(e,A_,yv),K4=e=>Ra(e,D_,U4),Uu=e=>Ra(e,I_,P4),Te=e=>T_.test(e),Ol=e=>Si(e,L_),Z4=e=>Si(e,$_),Qw=e=>Si(e,A_),Y4=e=>Si(e,z_),Q4=e=>Si(e,D_),Vu=e=>Si(e,I_,!0),X4=e=>Si(e,F_,!0),Ra=(e,t,n)=>{const r=M_.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Si=(e,t,n=!1)=>{const r=T_.exec(e);return r?r[1]?t(r[1]):n:!1},A_=e=>e==="position"||e==="percentage",D_=e=>e==="image"||e==="url",z_=e=>e==="length"||e==="size"||e==="bg-size",L_=e=>e==="length",W4=e=>e==="number",$_=e=>e==="family-name",F_=e=>e==="number"||e==="weight",I_=e=>e==="shadow",J4=()=>{const e=cn("color"),t=cn("font"),n=cn("text"),r=cn("font-weight"),i=cn("tracking"),l=cn("leading"),u=cn("breakpoint"),f=cn("container"),h=cn("spacing"),m=cn("radius"),y=cn("shadow"),g=cn("inset-shadow"),w=cn("text-shadow"),x=cn("drop-shadow"),j=cn("blur"),S=cn("perspective"),E=cn("aspect"),_=cn("ease"),N=cn("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],A=()=>[...T(),Te,Re],M=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],H=()=>[Te,Re,h],U=()=>[va,"full","auto",...H()],Z=()=>[Js,"none","subgrid",Te,Re],X=()=>["auto",{span:["full",Js,Te,Re]},Js,Te,Re],Q=()=>[Js,"auto",Te,Re],ae=()=>["auto","min","max","fr",Te,Re],le=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],$=()=>["auto",...H()],q=()=>[va,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...H()],V=()=>[va,"screen","full","dvw","lvw","svw","min","max","fit",...H()],ee=()=>[va,"screen","full","lh","dvh","lvh","svh","min","max","fit",...H()],K=()=>[e,Te,Re],O=()=>[...T(),Qw,Yw,{position:[Te,Re]}],D=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Y4,q4,{size:[Te,Re]}],P=()=>[tp,Ol,ni],I=()=>["","none","full",m,Te,Re],re=()=>["",Xe,Ol,ni],he=()=>["solid","dashed","dotted","double"],we=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>[Xe,tp,Qw,Yw],ve=()=>["","none",j,Te,Re],Me=()=>["none",Xe,Te,Re],Ye=()=>["none",Xe,Te,Re],ht=()=>[Xe,Te,Re],tt=()=>[va,"full",...H()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ar],breakpoint:[Ar],color:[O_],container:[Ar],"drop-shadow":[Ar],ease:["in","out","in-out"],font:[V4],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ar],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ar],shadow:[Ar],spacing:["px",Xe],text:[Ar],"text-shadow":[Ar],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",va,Re,Te,E]}],container:["container"],"container-type":[{"@container":["","normal","size",Te,Re]}],"container-named":[H4],columns:[{columns:[Xe,Re,Te,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:A()}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:U()}],"inset-x":[{"inset-x":U()}],"inset-y":[{"inset-y":U()}],start:[{"inset-s":U(),start:U()}],end:[{"inset-e":U(),end:U()}],"inset-bs":[{"inset-bs":U()}],"inset-be":[{"inset-be":U()}],top:[{top:U()}],right:[{right:U()}],bottom:[{bottom:U()}],left:[{left:U()}],visibility:["visible","invisible","collapse"],z:[{z:[Js,"auto",Te,Re]}],basis:[{basis:[va,"full","auto",f,...H()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,va,"auto","initial","none",Re]}],grow:[{grow:["",Xe,Te,Re]}],shrink:[{shrink:["",Xe,Te,Re]}],order:[{order:[Js,"first","last","none",Te,Re]}],"grid-cols":[{"grid-cols":Z()}],"col-start-end":[{col:X()}],"col-start":[{"col-start":Q()}],"col-end":[{"col-end":Q()}],"grid-rows":[{"grid-rows":Z()}],"row-start-end":[{row:X()}],"row-start":[{"row-start":Q()}],"row-end":[{"row-end":Q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...le(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...le()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":le()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:H()}],px:[{px:H()}],py:[{py:H()}],ps:[{ps:H()}],pe:[{pe:H()}],pbs:[{pbs:H()}],pbe:[{pbe:H()}],pt:[{pt:H()}],pr:[{pr:H()}],pb:[{pb:H()}],pl:[{pl:H()}],m:[{m:$()}],mx:[{mx:$()}],my:[{my:$()}],ms:[{ms:$()}],me:[{me:$()}],mbs:[{mbs:$()}],mbe:[{mbe:$()}],mt:[{mt:$()}],mr:[{mr:$()}],mb:[{mb:$()}],ml:[{ml:$()}],"space-x":[{"space-x":H()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":H()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...V()]}],"min-inline-size":[{"min-inline":["auto",...V()]}],"max-inline-size":[{"max-inline":["none",...V()]}],"block-size":[{block:["auto",...ee()]}],"min-block-size":[{"min-block":["auto",...ee()]}],"max-block-size":[{"max-block":["none",...ee()]}],w:[{w:[f,"screen",...q()]}],"min-w":[{"min-w":[f,"screen","none",...q()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh",...q()]}],"font-size":[{text:["base",n,Ol,ni]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,X4,B4]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",tp,Re]}],"font-family":[{font:[Z4,G4,t]}],"font-features":[{"font-features":[Re]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Te,Re]}],"line-clamp":[{"line-clamp":[Xe,"none",Te,Zw]}],leading:[{leading:[l,...H()]}],"list-image":[{"list-image":["none",Te,Re]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Te,Re]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...he(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Te,ni]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[Xe,"auto",Te,Re]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:H()}],"tab-size":[{tab:[Js,Te,Re]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Te,Re]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Te,Re]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:O()}],"bg-repeat":[{bg:D()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Js,Te,Re],radial:["",Te,Re],conic:[Js,Te,Re]},Q4,K4]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":re()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...he(),"hidden","none"]}],"divide-style":[{divide:[...he(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...he(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Te,Re]}],"outline-w":[{outline:["",Xe,Ol,ni]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","none",y,Vu,Uu]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",g,Vu,Uu]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:re()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[Xe,ni]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",w,Vu,Uu]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[Xe,Te,Re]}],"mix-blend":[{"mix-blend":[...we(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":we()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":Se()}],"mask-image-linear-to-pos":[{"mask-linear-to":Se()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":Se()}],"mask-image-t-to-pos":[{"mask-t-to":Se()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":Se()}],"mask-image-r-to-pos":[{"mask-r-to":Se()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":Se()}],"mask-image-b-to-pos":[{"mask-b-to":Se()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":Se()}],"mask-image-l-to-pos":[{"mask-l-to":Se()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":Se()}],"mask-image-x-to-pos":[{"mask-x-to":Se()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":Se()}],"mask-image-y-to-pos":[{"mask-y-to":Se()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[Te,Re]}],"mask-image-radial-from-pos":[{"mask-radial-from":Se()}],"mask-image-radial-to-pos":[{"mask-radial-to":Se()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":T()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":Se()}],"mask-image-conic-to-pos":[{"mask-conic-to":Se()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:O()}],"mask-repeat":[{mask:D()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Te,Re]}],filter:[{filter:["","none",Te,Re]}],blur:[{blur:ve()}],brightness:[{brightness:[Xe,Te,Re]}],contrast:[{contrast:[Xe,Te,Re]}],"drop-shadow":[{"drop-shadow":["","none",x,Vu,Uu]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",Xe,Te,Re]}],"hue-rotate":[{"hue-rotate":[Xe,Te,Re]}],invert:[{invert:["",Xe,Te,Re]}],saturate:[{saturate:[Xe,Te,Re]}],sepia:[{sepia:["",Xe,Te,Re]}],"backdrop-filter":[{"backdrop-filter":["","none",Te,Re]}],"backdrop-blur":[{"backdrop-blur":ve()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Te,Re]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Te,Re]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Te,Re]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Te,Re]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Te,Re]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Te,Re]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Te,Re]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Te,Re]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":H()}],"border-spacing-x":[{"border-spacing-x":H()}],"border-spacing-y":[{"border-spacing-y":H()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Te,Re]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Te,Re]}],ease:[{ease:["linear","initial",_,Te,Re]}],delay:[{delay:[Xe,Te,Re]}],animate:[{animate:["none",N,Te,Re]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Te,Re]}],"perspective-origin":[{"perspective-origin":A()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Ye()}],"scale-x":[{"scale-x":Ye()}],"scale-y":[{"scale-y":Ye()}],"scale-z":[{"scale-z":Ye()}],"scale-3d":["scale-3d"],skew:[{skew:ht()}],"skew-x":[{"skew-x":ht()}],"skew-y":[{"skew-y":ht()}],transform:[{transform:[Te,Re,"","none","gpu","cpu"]}],"transform-origin":[{origin:A()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:tt()}],"translate-x":[{"translate-x":tt()}],"translate-y":[{"translate-y":tt()}],"translate-z":[{"translate-z":tt()}],"translate-none":["translate-none"],zoom:[{zoom:[Js,Te,Re]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Te,Re]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":H()}],"scroll-mx":[{"scroll-mx":H()}],"scroll-my":[{"scroll-my":H()}],"scroll-ms":[{"scroll-ms":H()}],"scroll-me":[{"scroll-me":H()}],"scroll-mbs":[{"scroll-mbs":H()}],"scroll-mbe":[{"scroll-mbe":H()}],"scroll-mt":[{"scroll-mt":H()}],"scroll-mr":[{"scroll-mr":H()}],"scroll-mb":[{"scroll-mb":H()}],"scroll-ml":[{"scroll-ml":H()}],"scroll-p":[{"scroll-p":H()}],"scroll-px":[{"scroll-px":H()}],"scroll-py":[{"scroll-py":H()}],"scroll-ps":[{"scroll-ps":H()}],"scroll-pe":[{"scroll-pe":H()}],"scroll-pbs":[{"scroll-pbs":H()}],"scroll-pbe":[{"scroll-pbe":H()}],"scroll-pt":[{"scroll-pt":H()}],"scroll-pr":[{"scroll-pr":H()}],"scroll-pb":[{"scroll-pb":H()}],"scroll-pl":[{"scroll-pl":H()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Te,Re]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[Xe,Ol,ni,Zw]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},e3=T4(J4);function at(...e){return e3(__(e))}function t3({delayDuration:e=0,...t}){return o.jsx(r4,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function cf({...e}){return o.jsx(a4,{"data-slot":"tooltip",...e})}function uf({...e}){return o.jsx(i4,{"data-slot":"tooltip-trigger",...e})}function df({className:e,sideOffset:t=0,children:n,...r}){return o.jsx(o4,{children:o.jsxs(l4,{"data-slot":"tooltip-content",sideOffset:t,className:at("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...r,children:[n,o.jsx(c4,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}const Gp=new Set;function n3(e){return Gp.add(e),()=>Gp.delete(e)}function Co(e){for(const t of Gp)t(e)}const ii=/\.(md|markdown)$/i,P_=/\.(png|jpe?g|gif|svg|webp|ico|bmp|avif)$/i,Dr=/\.html?$/i,ad=/\.pdf$/i,U_=/\.(csv|tsv)$/i,s3=/\.(txt|log|json|ya?ml|toml|csv|go|py|js|ts|jsx|tsx|sh|bash|zsh|rb|rs|c|h|cpp|java|kt|swift|sql|css|xml|ini|conf|env|mod|sum|jsonl)$/i,Xl=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"");function mi(e){if(e<1024)return e+" B";const t=["KB","MB","GB","TB"];let n=-1;do e/=1024,n++;while(e>=1024&&nr.path.toLowerCase()===n||r.path.toLowerCase()===n+".md")||t.find(r=>{const i=r.name.toLowerCase();return i===n||i===n+".md"})}async function Mn(e){try{if(navigator.clipboard)return await navigator.clipboard.writeText(e),!0}catch{}return!1}const H_="bdrive.lastProject";function a3(){try{return localStorage.getItem(H_)||""}catch{return""}}function i3(e){try{localStorage.setItem(H_,e)}catch{}}const Kp="(min-width: 1400px)";function ff(e){return e.user_name?`${e.user_name} <${e.user}>`:e.user||e.author||"unknown"}function xv(e){return e.user_name?e.user_name:e.user?e.user.split("@")[0]||e.user:e.author||"unknown"}function q_(e,t){const n=new Date(e);if(isNaN(n.getTime()))return"";const r=new Intl.DateTimeFormat(t,{month:"short",day:"numeric",year:"numeric"}).format(n),i=new Intl.DateTimeFormat(t,{hour:"numeric",minute:"2-digit"}).format(n);return r+" · "+i}const B_=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const o3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const l3=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Xw=e=>{const t=l3(e);return t.charAt(0).toUpperCase()+t.slice(1)};var np={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const c3=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},u3=b.createContext({}),d3=()=>b.useContext(u3),f3=b.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:l,iconNode:u,...f},h)=>{const{size:m=24,strokeWidth:y=2,absoluteStrokeWidth:g=!1,color:w="currentColor",className:x=""}=d3()??{},j=r??g?Number(n??y)*24/Number(t??m):n??y;return b.createElement("svg",{ref:h,...np,width:t??m??np.width,height:t??m??np.height,stroke:e??w,strokeWidth:j,className:B_("lucide",x,i),...!l&&!c3(f)&&{"aria-hidden":"true"},...f},[...u.map(([S,E])=>b.createElement(S,E)),...Array.isArray(l)?l:[l]])});const Ce=(e,t)=>{const n=b.forwardRef(({className:r,...i},l)=>b.createElement(f3,{ref:l,iconNode:t,className:B_(`lucide-${o3(Xw(e))}`,`lucide-${e}`,r),...i}));return n.displayName=Xw(e),n};const h3=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],m3=Ce("activity",h3);const p3=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],g3=Ce("archive",p3);const v3=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],y3=Ce("arrow-down-wide-narrow",v3);const x3=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],b3=Ce("beaker",x3);const w3=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],S3=Ce("bell-off",w3);const j3=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],C3=Ce("book-open",j3);const _3=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],E3=Ce("briefcase",_3);const N3=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],k3=Ce("bug",N3);const R3=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],M3=Ce("building-2",R3);const T3=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],G_=Ce("calendar",T3);const O3=[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14.639V21",key:"1s85h0"}],["path",{d:"M20 10.656V21",key:"q45596"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18.463V21",key:"1otddq"}],["path",{d:"M8 14.656V21",key:"1t2idw"}]],A3=Ce("chart-no-axes-combined",O3);const D3=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],z3=Ce("check",D3);const L3=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],$3=Ce("chevron-down",L3);const F3=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],I3=Ce("chevron-left",F3);const P3=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],U3=Ce("chevron-right",P3);const V3=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],H3=Ce("chevrons-up-down",V3);const q3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],B3=Ce("circle-check",q3);const G3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K3=Ce("circle",G3);const Z3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],K_=Ce("clock",Z3);const Y3=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q3=Ce("code",Y3);const X3=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],W3=Ce("compass",X3);const J3=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],e5=Ce("copy",J3);const t5=[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]],n5=Ce("corner-up-left",t5);const s5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],r5=Ce("credit-card",s5);const a5=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],i5=Ce("database",a5);const o5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],l5=Ce("download",o5);const c5=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],u5=Ce("ellipsis",c5);const d5=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f5=Ce("eye",d5);const h5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],m5=Ce("file-plus",h5);const p5=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Z_=Ce("file-text",p5);const g5=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],v5=Ce("flag",g5);const y5=[["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3",key:"128dxu"}],["path",{d:"m14.305 19.53.923-.382",key:"3m78fa"}],["path",{d:"m15.228 16.852-.923-.383",key:"npixar"}],["path",{d:"m16.852 15.228-.383-.923",key:"5xggr7"}],["path",{d:"m16.852 20.772-.383.924",key:"dpfhf9"}],["path",{d:"m19.148 15.228.383-.923",key:"1reyyz"}],["path",{d:"m19.53 21.696-.382-.924",key:"1goivc"}],["path",{d:"m20.772 16.852.924-.383",key:"htqkph"}],["path",{d:"m20.772 19.148.924.383",key:"9w9pjp"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]],x5=Ce("folder-cog",y5);const b5=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],w5=Ce("folder-open",b5);const S5=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],bv=Ce("folder",S5);const j5=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],C5=Ce("gauge",j5);const _5=[["path",{d:"m14 13-8.381 8.38a1 1 0 0 1-3.001-3l8.384-8.381",key:"pgg06f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m21.5 10.5-8-8",key:"a17d9x"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m8.5 7.5 8 8",key:"1oyaui"}]],E5=Ce("gavel",_5);const N5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Y_=Ce("globe",N5);const k5=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],R5=Ce("graduation-cap",k5);const M5=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],T5=Ce("heart",M5);const O5=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],A5=Ce("history",O5);const D5=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],z5=Ce("house",D5);const L5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],$5=Ce("image",L5);const F5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],I5=Ce("info",F5);const P5=[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]],U5=Ce("laptop-minimal",P5);const V5=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],H5=Ce("layout-dashboard",V5);const q5=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],B5=Ce("lightbulb",q5);const G5=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],K5=Ce("link",G5);const Z5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Y5=Ce("loader-circle",Z5);const Q5=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],Q_=Ce("lock",Q5);const X5=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W5=Ce("log-out",X5);const J5=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],e6=Ce("maximize-2",J5);const t6=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],n6=Ce("megaphone",t6);const s6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],r6=Ce("menu",s6);const a6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],i6=Ce("message-square",a6);const o6=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],l6=Ce("minimize-2",o6);const c6=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],u6=Ce("monitor",c6);const d6=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],f6=Ce("moon",d6);const h6=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],m6=Ce("music",h6);const p6=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],g6=Ce("octagon-x",p6);const v6=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],y6=Ce("package",v6);const x6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],b6=Ce("panel-left",x6);const w6=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],S6=Ce("pen-line",w6);const j6=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],C6=Ce("pencil",j6);const _6=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],E6=Ce("plug",_6);const N6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],k6=Ce("plus",N6);const R6=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],M6=Ce("printer",R6);const T6=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],O6=Ce("rocket",T6);const A6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],X_=Ce("search",A6);const D6=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],z6=Ce("settings",D6);const L6=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],$6=Ce("share-2",L6);const F6=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],W_=Ce("shield",F6);const I6=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],P6=Ce("sparkles",I6);const U6=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],J_=Ce("square-terminal",U6);const V6=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],eE=Ce("star",V6);const H6=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],q6=Ce("sun",H6);const B6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],G6=Ce("tag",B6);const K6=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Z6=Ce("trash-2",K6);const Y6=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tE=Ce("triangle-alert",Y6);const Q6=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X6=Ce("upload",Q6);const W6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],wv=Ce("users",W6);const J6=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],eL=Ce("wrench",J6);const tL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nE=Ce("x",tL),sE="bdrive.sbCollapsed";function rE(){window.innerWidth<=Sv?nL():sL(!document.body.classList.contains("sb-collapsed"))}function nL(){const e=!document.body.classList.contains("sb-open");document.body.classList.toggle("sb-open"),pi(),e?document.getElementById("sidebar")?.querySelector(rL)?.focus():document.getElementById("menu-btn")?.focus()}function sL(e){document.body.classList.toggle("sb-collapsed",e);try{localStorage.setItem(sE,e?"1":"0")}catch{}pi()}const rL='a[href], button:not(:disabled), select, input, [tabindex]:not([tabindex="-1"])';function fs(){const e=document.body.classList.contains("sb-open");document.body.classList.remove("sb-open"),pi(),e&&window.innerWidth<=Sv&&document.getElementById("menu-btn")?.focus()}function aL(e){const t=e;if(!t||typeof t.tagName!="string")return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable?!0:!!t.closest?.(".cm-editor")}const Sv=900;function pi(){const e=document.getElementById("sidebar");if(!e)return;const t=window.innerWidth<=Sv,n=document.body.classList.contains("sb-open"),r=document.body.classList.contains("sb-collapsed"),i=t?!n:r;t&&!n?e.setAttribute("inert",""):e.removeAttribute("inert");const l=document.getElementById("main");l&&(n&&t?l.setAttribute("inert",""):l.removeAttribute("inert")),e.setAttribute("aria-modal",String(n&&t)),document.getElementById("menu-btn")?.setAttribute("aria-expanded",String(!i))}const Zp="bdrive.sidebarWidth",aE=210,iE=480;function id(e){const t=document.documentElement.style;e===null?t.removeProperty("--sb-w"):t.setProperty("--sb-w",`${e}px`)}function sp(e){try{e===null?localStorage.removeItem(Zp):localStorage.setItem(Zp,String(e))}catch{}}const Yp=e=>Math.round(Math.min(iE,Math.max(aE,e)));function iL(){const e=r=>{if(r.button!==0)return;r.preventDefault();const i=r.currentTarget,l=i.parentElement.getBoundingClientRect().left;i.setPointerCapture(r.pointerId),document.body.classList.add("sb-resizing");let u=null;const f=m=>{u=Yp(m.clientX-l),id(u)},h=()=>{i.removeEventListener("pointermove",f),i.removeEventListener("pointerup",h),i.removeEventListener("pointercancel",h),document.body.classList.remove("sb-resizing"),u!==null&&sp(u)};i.addEventListener("pointermove",f),i.addEventListener("pointerup",h),i.addEventListener("pointercancel",h)},t=()=>{id(null),sp(null)},n=r=>{const i=r.shiftKey?32:8,l=r.key==="ArrowLeft"?-i:r.key==="ArrowRight"?i:0;if(!l)return;r.preventDefault();const u=document.getElementById("sidebar").getBoundingClientRect().width,f=Yp(u+l);id(f),sp(f)};return o.jsx("div",{id:"sb-resize",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar","aria-valuemin":aE,"aria-valuemax":iE,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:e,onDoubleClick:t,onKeyDown:n})}if(typeof window<"u"){try{const e=Number(localStorage.getItem(Zp));e&&id(Yp(e))}catch{}try{document.body&&localStorage.getItem(sE)==="1"&&document.body.classList.add("sb-collapsed")}catch{}window.addEventListener("resize",pi),window.addEventListener("keydown",e=>{if(e.key==="Escape"&&document.body.classList.contains("sb-open")){fs();return}const t=e.key.toLowerCase();if((e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(t==="b"||t==="\\")){if(t==="b"&&aL(e.target))return;e.preventDefault(),rE()}})}const oL={alert:tE,building:M3,card:r5,check:z3,chev:U3,chevd:$3,chevl:I3,clock:K_,copy:e5,doc:Z_,dots:u5,download:l5,expand:e6,folder:bv,dashboard:H5,activity:m3,insights:A3,fileplus:m5,sort:y3,folderopen:w5,home:z5,laptop:U5,star:eE,system:x5,gear:z6,globe:Y_,hist:A5,link:K5,lock:Q_,menu:r6,comment:i6,plug:E6,plus:k6,power:W5,printer:M6,search:X_,share:$6,sidebar:b6,shield:W_,shrink:l6,terminal:J_,trash:Z6,upload:X6,users:wv,x:nE,pencil:C6,eye:f5,tag:G6,jump:n5,sparkle:P6,calendar:G_};function ge({name:e}){const t=oL[e];return t?o.jsx(t,{className:"ico","aria-hidden":"true"}):null}const Qp={folder:bv,"book-open":C3,"file-text":Z_,"pen-line":S6,users:wv,briefcase:E3,megaphone:n6,rocket:O6,lightbulb:B5,flag:v5,star:eE,heart:T5,code:Q3,"square-terminal":J_,bug:k3,wrench:eL,database:i5,package:y6,beaker:b3,gauge:C5,shield:W_,lock:Q_,gavel:E5,globe:Y_,compass:W3,calendar:G_,clock:K_,"graduation-cap":R5,image:$5,music:m6};function ci({name:e,className:t}){const n=e??"",r=Object.hasOwn(Qp,n)?Qp[n]:bv;return o.jsx(r,{className:t,"aria-hidden":"true"})}function jv({size:e=22}){return o.jsxs("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"currentColor",role:"img","aria-label":"BearDrive",children:[o.jsx("rect",{x:"4",y:"4",width:"5.6",height:"24"}),o.jsx("rect",{x:"11.2",y:"4",width:"14.4",height:"11.2"}),o.jsx("rect",{x:"11.2",y:"16.8",width:"16.8",height:"11.2"})]})}function bo(e){const t=["page",e.width??"app",e.className].filter(Boolean).join(" ");return o.jsx("div",{className:t,style:e.style,children:e.children})}function lL(e){e&&pi()}function oi(e){return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:"sb-backdrop",onClick:fs}),o.jsxs("aside",{id:"sidebar",ref:lL,children:[e.vault,e.projectsNav,e.tree??o.jsx("nav",{id:"tree","aria-label":"Files"}),e.orgBar,o.jsx(iL,{}),o.jsx("div",{id:"rail",children:e.rail??o.jsx(oE,{})})]}),o.jsxs("main",{id:"main",children:[e.topbar,e.exit,o.jsx("article",{id:"content",ref:e.contentRef,onScroll:e.onContentScroll,children:e.children})]})]})}function oE({top:e,children:t}){return o.jsxs(o.Fragment,{children:[e??o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(Cv,{id:"rail-search",icon:"search",label:"Search",hint:Xl?"⌘K":"Ctrl+K",onClick:()=>Co()}),t]})}function Cv(e){return o.jsxs(cf,{delayDuration:100,children:[o.jsx(uf,{asChild:!0,children:o.jsxs("button",{id:e.id,className:"rail-btn"+(e.active?" active":""),"aria-label":e.label,onClick:e.onClick,children:[o.jsx(ge,{name:e.icon}),e.badge?o.jsx("span",{className:"rail-badge"+(e.danger?" danger":""),children:e.badge}):null]})}),o.jsxs(df,{side:"right",className:"tipcard",sideOffset:8,children:[e.label,e.hint&&o.jsx("span",{className:"tip-hint",children:e.hint})]})]})}function hf(e){const{name:t,onHome:n,showSignout:r,beta:i}=e;return o.jsxs("header",{id:"vault",children:[o.jsx("span",{id:"vault-badge",children:o.jsx(jv,{size:22})}),o.jsx("span",{id:"vault-name",className:n?"vault-link":void 0,onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:l=>{n&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n())},children:t}),i&&o.jsx("span",{id:"vault-beta",children:"Beta"}),r&&o.jsx("div",{className:"vault-actions",children:o.jsx("a",{id:"signout",href:"/auth/logout",title:"Sign out","aria-label":"Sign out",children:o.jsx(ge,{name:"power"})})})]})}function li(e){return o.jsxs("header",{id:"topbar",children:[o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"menu-btn",className:"icon-btn","aria-label":"Toggle sidebar","aria-controls":"sidebar","aria-expanded":"false",onClick:rE,children:o.jsx(ge,{name:"sidebar"})})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Toggle sidebar ",o.jsx("kbd",{children:Xl?"⌘B":"Ctrl+B"})]})]}),e.nav,o.jsx("span",{id:"crumb",children:e.crumb}),o.jsx("span",{id:"meta",children:e.meta}),e.actions]})}function cL(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const uL=e=>{switch(e){case"success":return hL;case"info":return pL;case"warning":return mL;case"error":return gL;default:return null}},dL=Array(12).fill(0),fL=({visible:e,className:t})=>ye.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ye.createElement("div",{className:"sonner-spinner"},dL.map((n,r)=>ye.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),hL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),mL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),pL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),gL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ye.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),vL=ye.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ye.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ye.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),yL=()=>{const[e,t]=ye.useState(document.hidden);return ye.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Xp=1;class xL{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,l=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Xp++,u=this.toasts.find(h=>h.id===l),f=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(l)&&this.dismissedToasts.delete(l),u?this.toasts=this.toasts.map(h=>h.id===l?(this.publish({...h,...t,id:l,title:r}),{...h,...t,id:l,dismissible:f,title:r}):h):this.addToast({title:r,...i,dismissible:f,id:l}),l},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let l=r!==void 0,u;const f=i.then(async m=>{if(u=["resolve",m],ye.isValidElement(m))l=!1,this.create({id:r,type:"default",message:m});else if(wL(m)&&!m.ok){l=!1;const g=typeof n.error=="function"?await n.error(`HTTP error! status: ${m.status}`):n.error,w=typeof n.description=="function"?await n.description(`HTTP error! status: ${m.status}`):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(m instanceof Error){l=!1;const g=typeof n.error=="function"?await n.error(m):n.error,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"error",description:w,...j})}else if(n.success!==void 0){l=!1;const g=typeof n.success=="function"?await n.success(m):n.success,w=typeof n.description=="function"?await n.description(m):n.description,j=typeof g=="object"&&!ye.isValidElement(g)?g:{message:g};this.create({id:r,type:"success",description:w,...j})}}).catch(async m=>{if(u=["reject",m],n.error!==void 0){l=!1;const y=typeof n.error=="function"?await n.error(m):n.error,g=typeof n.description=="function"?await n.description(m):n.description,x=typeof y=="object"&&!ye.isValidElement(y)?y:{message:y};this.create({id:r,type:"error",description:g,...x})}}).finally(()=>{l&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),h=()=>new Promise((m,y)=>f.then(()=>u[0]==="reject"?y(u[1]):m(u[1])).catch(y));return typeof r!="string"&&typeof r!="number"?{unwrap:h}:Object.assign(r,{unwrap:h})},this.custom=(t,n)=>{const r=n?.id||Xp++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Wn=new xL,bL=(e,t)=>{const n=t?.id||Xp++;return Wn.addToast({title:e,...t,id:n}),n},wL=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",SL=bL,jL=()=>Wn.toasts,CL=()=>Wn.getActiveToasts(),Ww=Object.assign(SL,{success:Wn.success,info:Wn.info,warning:Wn.warning,error:Wn.error,custom:Wn.custom,message:Wn.message,promise:Wn.promise,dismiss:Wn.dismiss,loading:Wn.loading},{getHistory:jL,getToasts:CL});cL("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Hu(e){return e.label!==void 0}const _L=3,EL="24px",NL="16px",Jw=4e3,kL=356,RL=14,ML=45,TL=200;function er(...e){return e.filter(Boolean).join(" ")}function OL(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const AL=e=>{var t,n,r,i,l,u,f,h,m;const{invert:y,toast:g,unstyled:w,interacting:x,setHeights:j,visibleToasts:S,heights:E,index:_,toasts:N,expanded:R,removeToast:T,defaultRichColors:A,closeButton:M,style:L,cancelButtonStyle:H,actionButtonStyle:U,className:Z="",descriptionClassName:X="",duration:Q,position:ae,gap:le,expandByDefault:be,classNames:$,icons:q,closeButtonAriaLabel:V="Close toast"}=e,[ee,K]=ye.useState(null),[O,D]=ye.useState(null),[B,P]=ye.useState(!1),[I,re]=ye.useState(!1),[he,we]=ye.useState(!1),[Se,ve]=ye.useState(!1),[Me,Ye]=ye.useState(!1),[ht,tt]=ye.useState(0),[es,Fe]=ye.useState(0),ot=ye.useRef(g.duration||Q||Jw),Yt=ye.useRef(null),jt=ye.useRef(null),sn=_===0,Ct=_+1<=S,Lt=g.type,ts=g.dismissible!==!1,At=g.className||"",rn=g.descriptionClassName||"",ns=ye.useMemo(()=>E.findIndex(Le=>Le.toastId===g.id)||0,[E,g.id]),hr=ye.useMemo(()=>{var Le;return(Le=g.closeButton)!=null?Le:M},[g.closeButton,M]),Hs=ye.useMemo(()=>g.duration||Q||Jw,[g.duration,Q]),ms=ye.useRef(0),Tn=ye.useRef(0),z=ye.useRef(0),Y=ye.useRef(null),[W,de]=ae.split("-"),me=ye.useMemo(()=>E.reduce((Le,dt,Nt)=>Nt>=ns?Le:Le+dt.height,0),[E,ns]),xe=yL(),je=g.invert||y,_e=Lt==="loading";Tn.current=ye.useMemo(()=>ns*le+me,[ns,me]),ye.useEffect(()=>{ot.current=Hs},[Hs]),ye.useEffect(()=>{P(!0)},[]),ye.useEffect(()=>{const Le=jt.current;if(Le){const dt=Le.getBoundingClientRect().height;return Fe(dt),j(Nt=>[{toastId:g.id,height:dt,position:g.position},...Nt]),()=>j(Nt=>Nt.filter($t=>$t.toastId!==g.id))}},[j,g.id]),ye.useLayoutEffect(()=>{if(!B)return;const Le=jt.current,dt=Le.style.height;Le.style.height="auto";const Nt=Le.getBoundingClientRect().height;Le.style.height=dt,Fe(Nt),j($t=>$t.find(vt=>vt.toastId===g.id)?$t.map(vt=>vt.toastId===g.id?{...vt,height:Nt}:vt):[{toastId:g.id,height:Nt,position:g.position},...$t])},[B,g.title,g.description,j,g.id,g.jsx,g.action,g.cancel]);const Ae=ye.useCallback(()=>{re(!0),tt(Tn.current),j(Le=>Le.filter(dt=>dt.toastId!==g.id)),setTimeout(()=>{T(g)},TL)},[g,T,j,Tn]);ye.useEffect(()=>{if(g.promise&&Lt==="loading"||g.duration===1/0||g.type==="loading")return;let Le;return R||x||xe?(()=>{if(z.current{g.onAutoClose==null||g.onAutoClose.call(g,g),Ae()},ot.current)),()=>clearTimeout(Le)},[R,x,g,Lt,xe,Ae]),ye.useEffect(()=>{g.delete&&(Ae(),g.onDismiss==null||g.onDismiss.call(g,g))},[Ae,g.delete]);function Ke(){var Le;if(q?.loading){var dt;return ye.createElement("div",{className:er($?.loader,g==null||(dt=g.classNames)==null?void 0:dt.loader,"sonner-loader"),"data-visible":Lt==="loading"},q.loading)}return ye.createElement(fL,{className:er($?.loader,g==null||(Le=g.classNames)==null?void 0:Le.loader),visible:Lt==="loading"})}const _t=g.icon||q?.[Lt]||uL(Lt);var an,Dt;return ye.createElement("li",{tabIndex:0,ref:jt,className:er(Z,At,$?.toast,g==null||(t=g.classNames)==null?void 0:t.toast,$?.default,$?.[Lt],g==null||(n=g.classNames)==null?void 0:n[Lt]),"data-sonner-toast":"","data-rich-colors":(an=g.richColors)!=null?an:A,"data-styled":!(g.jsx||g.unstyled||w),"data-mounted":B,"data-promise":!!g.promise,"data-swiped":Me,"data-removed":I,"data-visible":Ct,"data-y-position":W,"data-x-position":de,"data-index":_,"data-front":sn,"data-swiping":he,"data-dismissible":ts,"data-type":Lt,"data-invert":je,"data-swipe-out":Se,"data-swipe-direction":O,"data-expanded":!!(R||be&&B),"data-testid":g.testId,style:{"--index":_,"--toasts-before":_,"--z-index":N.length-_,"--offset":`${I?ht:Tn.current}px`,"--initial-height":be?"auto":`${es}px`,...L,...g.style},onDragEnd:()=>{we(!1),K(null),Y.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ts||(Yt.current=new Date,tt(Tn.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(we(!0),Y.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,dt,Nt;if(Se||!ts)return;Y.current=null;const $t=Number(((Le=jt.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Hn=Number(((dt=jt.current)==null?void 0:dt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vt=new Date().getTime()-((Nt=Yt.current)==null?void 0:Nt.getTime()),fn=ee==="x"?$t:Hn,mr=Math.abs(fn)/vt;if(Math.abs(fn)>=ML||mr>.11){tt(Tn.current),g.onDismiss==null||g.onDismiss.call(g,g),D(ee==="x"?$t>0?"right":"left":Hn>0?"down":"up"),Ae(),ve(!0);return}else{var Cn,on;(Cn=jt.current)==null||Cn.style.setProperty("--swipe-amount-x","0px"),(on=jt.current)==null||on.style.setProperty("--swipe-amount-y","0px")}Ye(!1),we(!1),K(null)},onPointerMove:Le=>{var dt,Nt,$t;if(!Y.current||!ts||((dt=window.getSelection())==null?void 0:dt.toString().length)>0)return;const vt=Le.clientY-Y.current.y,fn=Le.clientX-Y.current.x;var mr;const Cn=(mr=e.swipeDirections)!=null?mr:OL(ae);!ee&&(Math.abs(fn)>1||Math.abs(vt)>1)&&K(Math.abs(fn)>Math.abs(vt)?"x":"y");let on={x:0,y:0};const qr=qn=>1/(1.5+Math.abs(qn)/20);if(ee==="y"){if(Cn.includes("top")||Cn.includes("bottom"))if(Cn.includes("top")&&vt<0||Cn.includes("bottom")&&vt>0)on.y=vt;else{const qn=vt*qr(vt);on.y=Math.abs(qn)0)on.x=fn;else{const qn=fn*qr(fn);on.x=Math.abs(qn)0||Math.abs(on.y)>0)&&Ye(!0),(Nt=jt.current)==null||Nt.style.setProperty("--swipe-amount-x",`${on.x}px`),($t=jt.current)==null||$t.style.setProperty("--swipe-amount-y",`${on.y}px`)}},hr&&!g.jsx&&Lt!=="loading"?ye.createElement("button",{"aria-label":V,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ts?()=>{}:()=>{Ae(),g.onDismiss==null||g.onDismiss.call(g,g)},className:er($?.closeButton,g==null||(r=g.classNames)==null?void 0:r.closeButton)},(Dt=q?.close)!=null?Dt:vL):null,(Lt||g.icon||g.promise)&&g.icon!==null&&(q?.[Lt]!==null||g.icon)?ye.createElement("div",{"data-icon":"",className:er($?.icon,g==null||(i=g.classNames)==null?void 0:i.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||Ke():null,g.type!=="loading"?_t:null):null,ye.createElement("div",{"data-content":"",className:er($?.content,g==null||(l=g.classNames)==null?void 0:l.content)},ye.createElement("div",{"data-title":"",className:er($?.title,g==null||(u=g.classNames)==null?void 0:u.title)},g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title),g.description?ye.createElement("div",{"data-description":"",className:er(X,rn,$?.description,g==null||(f=g.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),ye.isValidElement(g.cancel)?g.cancel:g.cancel&&Hu(g.cancel)?ye.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||H,onClick:Le=>{Hu(g.cancel)&&ts&&(g.cancel.onClick==null||g.cancel.onClick.call(g.cancel,Le),Ae())},className:er($?.cancelButton,g==null||(h=g.classNames)==null?void 0:h.cancelButton)},g.cancel.label):null,ye.isValidElement(g.action)?g.action:g.action&&Hu(g.action)?ye.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||U,onClick:Le=>{Hu(g.action)&&(g.action.onClick==null||g.action.onClick.call(g.action,Le),!Le.defaultPrevented&&Ae())},className:er($?.actionButton,g==null||(m=g.classNames)==null?void 0:m.actionButton)},g.action.label):null)};function e1(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DL(e,t){const n={};return[e,t].forEach((r,i)=>{const l=i===1,u=l?"--mobile-offset":"--offset",f=l?NL:EL;function h(m){["top","right","bottom","left"].forEach(y=>{n[`${u}-${y}`]=typeof m=="number"?`${m}px`:m})}typeof r=="number"||typeof r=="string"?h(r):typeof r=="object"?["top","right","bottom","left"].forEach(m=>{r[m]===void 0?n[`${u}-${m}`]=f:n[`${u}-${m}`]=typeof r[m]=="number"?`${r[m]}px`:r[m]}):h(f)}),n}const zL=ye.forwardRef(function(t,n){const{id:r,invert:i,position:l="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:h,className:m,offset:y,mobileOffset:g,theme:w="light",richColors:x,duration:j,style:S,visibleToasts:E=_L,toastOptions:_,dir:N=e1(),gap:R=RL,icons:T,containerAriaLabel:A="Notifications"}=t,[M,L]=ye.useState([]),H=ye.useMemo(()=>r?M.filter(B=>B.toasterId===r):M.filter(B=>!B.toasterId),[M,r]),U=ye.useMemo(()=>Array.from(new Set([l].concat(H.filter(B=>B.position).map(B=>B.position)))),[H,l]),[Z,X]=ye.useState([]),[Q,ae]=ye.useState(!1),[le,be]=ye.useState(!1),[$,q]=ye.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ye.useRef(null),ee=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),K=ye.useRef(null),O=ye.useRef(!1),D=ye.useCallback(B=>{L(P=>{var I;return(I=P.find(re=>re.id===B.id))!=null&&I.delete||Wn.dismiss(B.id),P.filter(({id:re})=>re!==B.id)})},[]);return ye.useEffect(()=>Wn.subscribe(B=>{if(B.dismiss){requestAnimationFrame(()=>{L(P=>P.map(I=>I.id===B.id?{...I,delete:!0}:I))});return}setTimeout(()=>{ZM.flushSync(()=>{L(P=>{const I=P.findIndex(re=>re.id===B.id);return I!==-1?[...P.slice(0,I),{...P[I],...B},...P.slice(I+1)]:[B,...P]})})})}),[M]),ye.useEffect(()=>{if(w!=="system"){q(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?q("dark"):q("light")),typeof window>"u")return;const B=window.matchMedia("(prefers-color-scheme: dark)");try{B.addEventListener("change",({matches:P})=>{q(P?"dark":"light")})}catch{B.addListener(({matches:I})=>{try{q(I?"dark":"light")}catch(re){console.error(re)}})}},[w]),ye.useEffect(()=>{M.length<=1&&ae(!1)},[M]),ye.useEffect(()=>{const B=P=>{var I;if(u.every(we=>P[we]||P.code===we)){var he;ae(!0),(he=V.current)==null||he.focus()}P.code==="Escape"&&(document.activeElement===V.current||(I=V.current)!=null&&I.contains(document.activeElement))&&ae(!1)};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[u]),ye.useEffect(()=>{if(V.current)return()=>{K.current&&(K.current.focus({preventScroll:!0}),K.current=null,O.current=!1)}},[V.current]),ye.createElement("section",{ref:n,"aria-label":`${A} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},U.map((B,P)=>{var I;const[re,he]=B.split("-");return H.length?ye.createElement("ol",{key:B,dir:N==="auto"?e1():N,tabIndex:-1,ref:V,className:m,"data-sonner-toaster":!0,"data-sonner-theme":$,"data-y-position":re,"data-x-position":he,style:{"--front-toast-height":`${((I=Z[0])==null?void 0:I.height)||0}px`,"--width":`${kL}px`,"--gap":`${R}px`,...S,...DL(y,g)},onBlur:we=>{O.current&&!we.currentTarget.contains(we.relatedTarget)&&(O.current=!1,K.current&&(K.current.focus({preventScroll:!0}),K.current=null))},onFocus:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||O.current||(O.current=!0,K.current=we.relatedTarget)},onMouseEnter:()=>ae(!0),onMouseMove:()=>ae(!0),onMouseLeave:()=>{le||ae(!1)},onDragEnd:()=>ae(!1),onPointerDown:we=>{we.target instanceof HTMLElement&&we.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},H.filter(we=>!we.position&&P===0||we.position===B).map((we,Se)=>{var ve,Me;return ye.createElement(AL,{key:we.id,icons:T,index:Se,toast:we,defaultRichColors:x,duration:(ve=_?.duration)!=null?ve:j,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:i,visibleToasts:E,closeButton:(Me=_?.closeButton)!=null?Me:h,interacting:le,position:B,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:D,toasts:H.filter(Ye=>Ye.position==we.position),heights:Z.filter(Ye=>Ye.position==we.position),setHeights:X,expandByDefault:f,gap:R,expanded:Q,swipeDirections:t.swipeDirections})})):null}))}),Ed="bdrive-theme",Wp="bdrive-theme",lE="(prefers-color-scheme: dark)";let cE="system";function _v(){try{const e=localStorage.getItem(Ed);return e==="light"||e==="dark"||e==="system"?e:"system"}catch{return cE}}function LL(e){if(e!=="system")return e;try{return window.matchMedia(lE).matches?"dark":"light"}catch{return"dark"}}function $L(){return document.documentElement.dataset.theme==="light"?"light":"dark"}function od(){const e=LL(_v()),t=document.documentElement;t.dataset.theme=e,t.style.colorScheme=e,window.dispatchEvent(new Event(Wp))}function FL(e){cE=e;try{e==="system"?localStorage.removeItem(Ed):localStorage.setItem(Ed,e)}catch{}od()}let t1=!1;function IL(){if(!t1){t1=!0,od();try{window.matchMedia(lE).addEventListener("change",()=>{_v()==="system"&&od()})}catch{}window.addEventListener("storage",e=>{(e.key===Ed||e.key===null)&&od()})}}function PL(e){return window.addEventListener(Wp,e),()=>window.removeEventListener(Wp,e)}function n1(){return`${_v()}:${$L()}`}function Ev(){const[e,t]=b.useSyncExternalStore(PL,n1,n1).split(":");return{pref:e,theme:t,setPref:FL}}const UL=({...e})=>{const{theme:t}=Ev();return o.jsx(zL,{theme:t,className:"toaster group",icons:{success:o.jsx(B3,{className:"size-4"}),info:o.jsx(I5,{className:"size-4"}),warning:o.jsx(tE,{className:"size-4"}),error:o.jsx(g6,{className:"size-4"}),loading:o.jsx(Y5,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius-ctl)"},...e})};function Ne(e,t=!1){t?Ww.error(e,{duration:1/0,closeButton:!0}):Ww(e)}function VL(){return o.jsx(UL,{position:"bottom-center"})}const s1=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,r1=__,HL=(e,t)=>n=>{var r;if(t?.variants==null)return r1(e,n?.class,n?.className);const{variants:i,defaultVariants:l}=t,u=Object.keys(i).map(m=>{const y=n?.[m],g=l?.[m];if(y===null)return null;const w=s1(y)||s1(g);return i[m][w]}),f=n&&Object.entries(n).reduce((m,y)=>{let[g,w]=y;return w===void 0||(m[g]=w),m},{}),h=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((m,y)=>{let{class:g,className:w,...x}=y;return Object.entries(x).every(j=>{let[S,E]=j;return Array.isArray(E)?E.includes({...l,...f}[S]):{...l,...f}[S]===E})?[...m,g,w]:m},[]);return r1(e,u,h,n?.class,n?.className)},qL=HL("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[background-color,border-color,color] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",primary:"pbtn",danger:"danger-btn",subtle:"ai-btn",toolbar:"btn",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function Ie({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const l=r?YM:"button";return o.jsx(l,{"data-slot":"button","data-variant":t,"data-size":n,className:at(qL({variant:t,size:n,className:e})),...i})}function uc({...e}){return o.jsx(Kg,{"data-slot":"dialog",...e})}function BL({...e}){return o.jsx(Yg,{"data-slot":"dialog-portal",...e})}function GL({className:e,...t}){return o.jsx(Qg,{"data-slot":"dialog-overlay",className:at("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function dc({className:e,children:t,showCloseButton:n=!0,...r}){return o.jsxs(BL,{"data-slot":"dialog-portal",children:[o.jsx(GL,{}),o.jsxs(Xg,{"data-slot":"dialog-content",className:at("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...r,children:[t,n&&o.jsxs(Mj,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(nE,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function zo({className:e,...t}){return o.jsx(Ej,{"data-slot":"dialog-title",className:at("text-lg leading-none font-semibold",e),...t})}function KL({className:e,...t}){return o.jsx(kj,{"data-slot":"dialog-description",className:at("text-sm text-muted-foreground",e),...t})}let uE=null,ld=[];function fc(e){uE=e,ld.forEach(t=>t())}function Wl(e,t,n="",r="OK",i={}){return new Promise(l=>fc({kind:"prompt",title:e,label:t,value:n,okLabel:r,...i,resolve:l}))}function ir(e,t,n="Confirm",r=!1){return new Promise(i=>fc({kind:"confirm",title:e,message:t,confirmLabel:n,danger:r,resolve:i}))}function ZL(){const e=b.useSyncExternalStore(n=>(ld.push(n),()=>{ld=ld.filter(r=>r!==n)}),()=>uE);if(!e)return null;const t=()=>{fc(null),e.kind==="prompt"?e.resolve(null):e.resolve(!1)};return o.jsx(uc,{open:!0,onOpenChange:n=>!n&&t(),children:o.jsx(dc,{className:"modal",showCloseButton:!1,children:e.kind==="prompt"?o.jsx(YL,{m:e}):o.jsx(QL,{m:e})})})}function YL({m:e}){const t=b.useRef(null),n=m=>{fc(null),e.resolve(m)},[r,i]=b.useState(""),[l,u]=b.useState(e.value),f=e.match===void 0||l.trim()===e.match,h=()=>{const m=l;if(f){if(!m.trim()){i("Give it a name."),t.current.focus();return}n(m)}};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:e.label}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",value:l,ref:t,id:"modal-input",autoFocus:!0,onFocus:m=>m.currentTarget.select(),"aria-invalid":!!r,"aria-describedby":r?"modal-input-err":void 0,onChange:m=>{u(m.currentTarget.value),r&&i("")},onKeyDown:m=>m.key==="Enter"&&h()}),r&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:r}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>n(null),children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:h,disabled:!f,children:e.okLabel})]})]})}function QL({m:e}){const t=n=>{fc(null),e.resolve(n)};return o.jsxs(o.Fragment,{children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.title})}),o.jsx("div",{className:"modal-msg",children:e.message}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>t(!1),autoFocus:e.danger,children:"Cancel"}),o.jsx(Ie,{variant:e.danger?"danger":"primary",onClick:()=>t(!0),autoFocus:!e.danger,children:e.confirmLabel})]})]})}let Nd=null,cd=[];const Nv=e=>{Nd=e,cd.forEach(t=>t())};function VB(e,t){Nv({...t,path:e,from:t})}function HB(e){Nd?.from===e&&Nv(null)}function XL(){const e=b.useSyncExternalStore(f=>(cd.push(f),()=>{cd=cd.filter(h=>h!==f)}),()=>Nd),[t,n]=b.useState(null);if(!e)return null;const r=t===e,i=e.path.split("/").pop()||e.path,l=async f=>{n(e);try{await f()}finally{n(h=>h===e?null:h),Nd===e&&Nv(null)}},u=()=>{l(e.keep)};return o.jsx(uc,{open:!0,onOpenChange:f=>!f&&!r&&u(),children:o.jsxs(dc,{className:"modal shrink-dialog",showCloseButton:!1,id:"shrink-dialog",children:[o.jsxs("div",{className:"sd-head",children:[o.jsx("span",{className:"sd-icon","aria-hidden":"true",children:o.jsx(ge,{name:"shield"})}),o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:e.now===0?"This save would erase the note":"This save would cut most of the note"})})]}),o.jsxs(KL,{className:"modal-msg",children:[i," would go from ",e.was.toLocaleString()," B to ",e.now.toLocaleString()," B. This usually means the editor lost its connection before the content loaded. Nothing has been written yet."]}),o.jsxs("div",{className:"sd-compare",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Saved version"}),o.jsx("b",{className:"sd-ok",children:mi(e.was)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Your editor"}),o.jsx("b",{className:"sd-bad",children:e.now===0?"0 B · empty":mi(e.now)})]})]}),o.jsxs("div",{className:"modal-actions sd-actions",children:[o.jsx(Ie,{id:"shrink-keep",variant:"primary",autoFocus:!0,disabled:r,onClick:u,children:"Keep saved version"}),o.jsx(Ie,{id:"shrink-confirm",variant:"danger",disabled:r,onClick:()=>{l(e.confirm)},children:"Save anyway"})]})]})})}const dE={queryKey:["projects"],queryFn:()=>We("/api/projects")};function WL(e){return rt({...dE,enabled:e,select:t=>t.projects||[]})}function JL(){const e=mn();return()=>e.fetchQuery(dE)}function fE(e){return rt({queryKey:["orgs"],queryFn:()=>We("/api/orgs"),enabled:e,select:t=>t.orgs||[]})}function kv(e){return rt({queryKey:["permissions",e],queryFn:()=>We(`/api/p/${e}/permissions`),enabled:!!e})}function hE(e){return rt({queryKey:["folders",e],queryFn:()=>We(`/api/p/${e}/folders`),enabled:!!e})}function mE(e,t=!0){return rt({queryKey:["shares",e],queryFn:()=>We(`/api/p/${e}/shares`),enabled:!!e&&t,select:n=>n.shares||[]})}function pE(e){return rt({queryKey:["admin","pending"],queryFn:()=>We("/api/admin/pending"),enabled:e,select:t=>t.pending||[]})}function gE(){const e=mn();return()=>Promise.all([e.invalidateQueries({queryKey:["projects"]}),e.invalidateQueries({queryKey:["orgs"]})]).then(()=>{})}function vE(e){return e.split("/").map(encodeURIComponent).join("/")}function e$(e){try{return decodeURIComponent(e)}catch{return e}}function mf(e){return e.split("/").map(e$).join("/")}const t$={dashboard:"insights",history:"activity",install:"install",settings:"settings"},Jp={insights:"dashboard",activity:"history",install:"install",settings:"settings"};new Set(Object.keys(Jp));const a1={dashboard:"dashboard",history:"history"};function n$(e){return Object.hasOwn(a1,e)?a1[e]:void 0}function s$(e){return Object.hasOwn(Jp,e)?Jp[e]:void 0}const Rv=["q","user","actor","device","range","since","until"];function Mv(e){return!!e&&Rv.some(t=>!!e[t])}function r$(e){const t=new URLSearchParams;for(const r of Rv)e?.[r]&&t.set(r,e[r]);const n=t.toString();return n?"?"+n:""}const a$={dashboard:"Insights",history:"Activity",install:"Install",settings:"Settings"};function i1(e){const t=e.slice(e.lastIndexOf("/")+1);return t.replace(/\.md$/i,"")||t}function yE(e,t){let n="";return e.view?(n=a$[e.view],e.viewTarget&&(n=`${i1(e.viewTarget)} · ${n}`)):e.path&&(n=i1(e.path)+(e.editing?" · Editing":e.version?" · Version":"")),n?`${n} — ${t}`:t}function Tv(e,t){const n=e.indexOf("?"),r=n===-1?null:new URLSearchParams(e.slice(n)),i=r?.get("v")||"",l=r?.get("connect")||"",u=i$(n===-1?e:e.slice(0,n),t);i&&(u.version=i),l&&(u.connect=l),r?.has("full")&&(u.full=!0);const f=r?.get("comment")||"";/^[0-9a-f]{12}$/.test(f)&&(u.comment=f);const h={};for(const m of Rv){const y=r?.get(m);y&&(h[m]=y)}if(Mv(h)&&(u.filters=h),u.view==="history"&&!u.viewTarget){const m=(r?.get("path")||r?.get("prefix")||"").replace(/^\/+|\/+$/g,"");m&&(u.viewTarget=mf(m),u.queryTarget=!0)}return u}function o1(e,t){const n=t.replace(/\/+$/,"");return n!==t&&(e.trailingSlash=!0),e.path=n?mf(n):"",e}function l1(e){return e.path.split("/")[0]!=="edit"||(e.editing=!0,e.path=e.path.slice(5).replace(/\/+$/,"")),e}function i$(e,t){const n=e.replace(/^\/+/,"");if(t!=="hub")return l1(o1({path:""},n));if(n==="orgs"||n.startsWith("orgs/"))return{org:n.slice(5).replace(/\/+$/,""),path:""};if(n==="billing"||n.startsWith("billing/"))return{billing:!0,path:""};if(n==="connections"||n.startsWith("connections/"))return{connections:!0,path:""};const r=n.indexOf("/");if(r===-1)return{project:n,path:""};const i=o1({project:n.slice(0,r),path:""},n.slice(r+1)),l=i.path.indexOf("/"),u=l===-1?i.path:i.path.slice(0,l);if(u==="edit")return l1(i);const f=n$(u),h=s$(u);return(h||f)&&(i.view=h||f,f&&(i.legacyView=!0),i.viewTarget=l===-1?"":i.path.slice(l+1).replace(/\/+$/,""),i.path=""),i}function $n(e,t,n,r,i){const l=vE(e),u=l&&i?"edit/"+l:l,f=(n?"?v="+n:"")+(r?(n?"&":"?")+"full=1":"");return t?"/"+t+(u?"/"+u:"")+f:"/"+u+f}function o$(e){const t=e.indexOf("?");if(t===-1)return e;const n=new URLSearchParams(e.slice(t+1));if(!n.has("full"))return e;n.delete("full");const r=n.toString();return e.slice(0,t)+(r?"?"+r:"")}function un(e,t,n,r){let i=(t?"/"+t:"")+"/"+t$[e];return n&&(i+="/"+vE(n.replace(/\/+$/,""))),i+(e==="history"?r$(r):"")}function l$(e,t){const n=mf(t).toLowerCase(),r=e.filter(i=>i.name.toLowerCase()===n);return r.length===1?r[0].id:void 0}let Ov="POP";const eg=new Set;function xE(){for(const e of eg)e()}window.addEventListener("popstate",()=>{Ov="POP",xE()});function gt(e,t){const n=location.pathname+location.search;!t?.replace&&n===e||(history[t?.replace?"replaceState":"pushState"](null,"",e),Ov=t?.replace?"REPLACE":"PUSH",xE())}function Av(){return b.useSyncExternalStore(e=>(eg.add(e),()=>{eg.delete(e)}),()=>location.pathname+location.search)}function c$(){return Ov}function Pn(e){return e.startsWith("/")&&!e.startsWith("//")?{href:e,onClick:n=>{n.defaultPrevented||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.button!==0||(n.preventDefault(),gt(e),document.body.classList.remove("sb-open"))}}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function si({to:e}){return b.useEffect(()=>{gt(e,{replace:!0})},[e]),null}function bE(){return{accessor:(e,t)=>typeof e=="function"?{...t,accessorFn:e}:{...t,accessorKey:e},display:e=>e,group:e=>e}}function ba(e,t){return typeof e=="function"?e(t):e}function hs(e,t){return n=>{t.setState(r=>({...r,[e]:ba(n,r[e])}))}}function pf(e){return e instanceof Function}function u$(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function d$(e,t){const n=[],r=i=>{i.forEach(l=>{n.push(l);const u=t(l);u!=null&&u.length&&r(u)})};return r(e),n}function Ve(e,t,n){let r=[],i;return l=>{let u;n.key&&n.debug&&(u=Date.now());const f=e(l);if(!(f.length!==r.length||f.some((y,g)=>r[g]!==y)))return i;r=f;let m;if(n.key&&n.debug&&(m=Date.now()),i=t(...f),n==null||n.onChange==null||n.onChange(i),n.key&&n.debug&&n!=null&&n.debug()){const y=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-m)*100)/100,w=g/16,x=(j,S)=>{for(j=String(j);j.length{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Rn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return qu(t,[...f,...m,...h],e)},He(e.options,Rn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),qu(t,n,e,"center")),He(e.options,Rn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"left")},He(e.options,Rn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"right")},He(e.options,Rn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Rn))}};function qu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Is(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Is(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Is(e);const Dv=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Dv.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Dv.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const zr={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Dv};function Is(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:hs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?zr.includesString:typeof r=="number"?zr.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?zr.equals:Array.isArray(r)?zr.arrIncludes:zr.weakEquals},e.getFilterFn=()=>{var n,r;return pf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:zr[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=ba(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=ba(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,rp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:hs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return rp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return rp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:rp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:hs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Pl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Pl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Pl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},ap=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:ap(),...e}),getDefaultOptions:e=>({onColumnPinningChange:hs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?ap():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:ap())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Bu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ip=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Bu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ip(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:hs("columnSizing",e),onColumnSizingInfoChange:hs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bu.minSize,(r=l??e.columnDef.size)!=null?r:Bu.size),(i=e.columnDef.maxSize)!=null?i:Bu.maxSize)},e.getStart=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),op(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=op(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;op(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ip():(n=e.initialState.columnSizingInfo)!=null?n:ip())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Gu=null;function A$(){if(typeof Gu=="boolean")return Gu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gu=e,Gu}function op(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:hs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Pl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:hs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>zr.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return pf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:zr[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:hs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},tg=0,ng=10,lp=()=>({pageIndex:tg,pageSize:ng}),F$={getInitialState:e=>({...e,pagination:{...lp(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:hs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>ba(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?lp():(i=e.initialState.pagination)!=null?i:lp())},e.setPageIndex=r=>{e.setPagination(i=>{let l=ba(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:tg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?ng:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:ng)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,ba(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=ba(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},cp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:cp(),...e}),getDefaultOptions:e=>({onRowPinningChange:hs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?cp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:cp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:hs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{sg(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return sg(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},sg=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>sg(e,f.id,n,r,i))};function up(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=zv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function zv(e,t){var n;return(n=t[e.id])!=null?n:!1}function rg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(zv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=rg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const ag=/([0-9]+)/gm,U$=(e,t,n)=>RE(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(_a(e.getValue(n)),_a(t.getValue(n))),H$=(e,t,n)=>Lv(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>Lv(_a(e.getValue(n)),_a(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rLv(e.getValue(n),t.getValue(n));function Lv(e,t){return e===t?0:e>t?1:-1}function _a(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(ag).filter(Boolean),r=t.split(ag).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Al={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:hs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Al.datetime;if(typeof l=="string"&&(r=!0,l.split(ag).length>1))return Al.alphanumeric}return r?Al.text:Al.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Al[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=ba(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ig(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var hc=e=>e.type==="checkbox",wa=e=>e instanceof Date,bn=e=>e==null;const $v=e=>typeof e=="object";var Vt=e=>!bn(e)&&!Array.isArray(e)&&$v(e)&&!wa(e),J$=e=>Vt(e)&&e.target?hc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Vt(t)&&t.hasOwnProperty("isPrototypeOf")},gf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(gf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Vt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Gt(e[i]));return r}const mo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",Fv=["__proto__","constructor","prototype"],t8=/^\w*$/;var mc=e=>t8.test(e),Mt=e=>e===void 0;const n8=/[.[\]'"]/;var vf=e=>e.split(n8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Vt(e))return n;const r=mc(t)?[t]:vf(t);if(r.some(l=>Fv.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Ns=e=>typeof e=="function",wt=(e,t,n)=>{let r=-1;const i=mc(t)?[t]:vf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const a8=gf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),og=e=>bn(e)||!$v(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(og(e)||og(t))return Object.is(e,t);if(wa(e)&&wa(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(wa(f)&&wa(h)||(Vt(f)||Array.isArray(f))&&(Vt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Ku=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),dp=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Ul=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Ul(f,t))break}else if(Vt(f)&&Ul(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return wt(i,DE,t[n]),wt(e,n,i),e},xn=e=>Vt(e)&&!Object.keys(e).length,Iv=e=>e.type==="file",kd=e=>{if(!gf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pv=e=>e.type==="radio",Rd=e=>e instanceof RegExp,Uv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||tr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var po=e=>Vt(e)&&!Rd(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Pv(u),L=hc(u),H=M||L,U=(E||Iv(u))&&Mt(u.value)&&Mt(N)||kd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Uv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||tr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Q,message:ae}=wn(h)?{value:!!h,message:h}:po(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Q,ae;const le=po(w),be=po(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Q=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Q,message:ae}=po(x);if(Rd(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Ns(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Vt(j)){let Q={};for(const ae in j){if(!xn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!xn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},ud=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;rFv.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Vt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Kt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if($v(e[n])&&e[n]!==null&&!wa(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Vt(i)&&l){const u=IE(i,l);Vt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Pv(e)||hc(e),fp=e=>kd(e)&&e.isConnected,d8=e=>{for(const t in e)if(Ns(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Vt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function lg(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function cg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},cg(i,t[r],l),HE(t[r])&&lg(t,r)):Mt(i)||(t[r]=!0)}return t}function ri(e,t,n,r){n||(n=cg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Mt(t)||og(n[i])?n[i]=cg(l,Array.isArray(l)?[]:{},u):ri(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&lg(n,i)):nr(l,t[i])?lg(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Iv(t)?t.files:Pv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):hc(t)?zE(e.refs).value:qE(Mt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&wt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Dl=e=>Mt(e)?e:Rd(e)?e.source:Vt(e)?Rd(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(Ns(e.validate))return e.validate.constructor.name===b1;if(Vt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||mc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},g8=(e,t,n)=>!e||!t||e===t||ud(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(ke(e,t)).length&&Kt(e,t);const x8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},hp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Gt(BE),isLoading:Ns(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Vt(t.defaultValues)||Vt(t.values)?Gt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Gt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Ku(t.mode),w=Ku(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=xn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:mo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?wt(n.validatingFields,W,Y):Kt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ri(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const je=W(ke(r,z),de.argA,de.argB);me&&wt(r,z,je)}if(xe&&Array.isArray(ke(n.errors,z))){const je=W(ke(n.errors,z),de.argA,de.argB);me&&wt(n.errors,z,je),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const je=W(ke(n.touchedFields,z),de.argA,de.argB);me&&wt(n.touchedFields,z,je)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else wt(l,z,Y)},H=(z,Y)=>{wt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=mc(z)?[z]:vf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),je=ke(l,z,Mt(W)?ke(i,z):W);Mt(je)||de&&de.defaultChecked||Y?wt(l,z,Y?je:x1(me._f)):D(z,je),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&dp(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,je=!1;const _e={name:z};if(!t.disabled||de===!0){if(!W||de){const Ae=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(je=n.isDirty,n.isDirty=_e.isDirty=!Ae||ee(),xe=je!==_e.isDirty),je=!!ke(n.dirtyFields,z),Ae!==n.isDirty?n.dirtyFields=ri(i,l,void 0,r):Ae?Kt(n.dirtyFields,z):wt(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&je!==!Ae}if(W){const Ae=ke(n.touchedFields,z);Ae||(wt(n.touchedFields,z,W),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ae!==W)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?wt(n.errors,z,W):Kt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!xn(de)||xe){const je={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...je},E.state.next(je)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Vt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):wt(n.errors,W,de):Kt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Vt(W))for(const de in W){const me=W[de];me&&ht(`${hp}.${de}`,{message:wn(me.message)?me.message:"",type:me.type||Ls.validate})}else wn(W)||!W?ht(hp,{message:W||"",type:Ls.validate}):Ye(hp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const je=z[xe];if(je){const{_f:_e,...Ae}=je;if(_e){const Ke=f.array.has(_e.name),Ct=je._f&&h8(je._f),rn=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;Ct&&rn&&A([_e.name],!0);const Dt=await v1(je,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,Ke);if(Ct&&rn&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Y)||(!Y&&(ke(Dt,_e.name)?Ke?f1(n.errors,Dt,_e.name):wt(n.errors,_e.name,Dt[_e.name]):Kt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ae)&&await q({context:me,onlyCheckValid:Y,fields:Ae,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!fp(W)):!fp(Y._f.ref))&&ot(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&wt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>i8(z,f,{...u.mount?l:Mt(Y)?i:wn(z)?{[z]:Y}:Y},W,Y),O=z=>$E(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let je=Y;if(xe){const _e=xe._f;_e&&(!_e.disabled&&wt(l,z,qE(Y,_e)),je=kd(_e.ref)&&bn(Y)?"":Y,PE(_e.ref)?[..._e.ref.options].forEach(Ae=>Ae.selected=je.includes(Ae.value)):_e.refs?hc(_e.ref)?_e.refs.forEach(Ae=>{(!Ae.defaultChecked||!Ae.disabled)&&(Array.isArray(je)?Ae.checked=!!je.find(Ke=>Ke===Ae.value):Ae.checked=je===Ae.value||!!je)}):_e.refs.forEach(Ae=>Ae.checked=Ae.value===je):Iv(_e.ref)?_e.ref.value="":(_e.ref.value=je,!_e.ref.type&&!me&&E.state.next({name:z,values:de?l:Gt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,je,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&Se(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const je=Y[xe],_e=z+"."+xe,Ae=ke(r,_e);(f.array.has(z)||Vt(je)||Ae&&!Ae._f)&&!wa(je)?B(_e,je,W,de,me):D(_e,je,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),je=f.array.has(z),_e=de?Y:Gt(Y),Ae=ke(l,z),Ke=nr(Ae,_e);if(Ke||wt(l,z,_e),je)E.array.next({name:z,values:de?l:Gt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const Ct=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||Ct?D(z,_e,W,de,me):B(z,_e,W,de,me)}if(!Ke&&!me){const Ct=dp(z,f),rn=de?l:Gt(l);E.state.next({...Ct&&n,name:u.mount||Ct?z:void 0,values:rn})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Ns(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=FE(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=je=>{de=Number.isNaN(je)||wa(je)&&isNaN(je.getTime())||nr(je,ke(l,W,je))};if(me){let je,_e;const Ae=Y.type?x1(me._f):J$(z),Ke=z.type===mo.BLUR||z.type===mo.FOCUS_OUT,Ct=!m8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,rn=Ct||v8(Ke,ke(n.touchedFields,W),n.isSubmitted,w,g),Dt=dp(W,f,Ke);if(wt(l,W,Ae),Ke){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const Et=h[W];Et&&Et(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Ae,Ke),dt=!xn(Le)||Dt;if(!Ke&&E.state.next({name:W,type:z.type,...y?{values:Gt(l)}:{}}),rn)return(!Ct||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?Ke&&T():Ke||T()),dt&&E.state.next({name:W,...Dt?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!Ke&&Dt&&E.state.next({...n}),t.resolver){const{errors:Et}=await le([W]);if(A([W]),xe(Ae),!de){!xn(Le)&&E.state.next(Le);return}const $t=w1(n.errors,r,W),Hn=w1(Et,r,$t.name||W);je=Hn.error,W=Hn.name,_e=xn(Et)}else A([W],!0),je=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Ae),de&&(je?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&Se(me._f.deps),ae(W,_e,je,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},Se=async(z,Y={})=>{let W,de;const me=ud(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=xn(xe),de=z?!me.some(je=>ke(xe,je)):W}else z?(de=(await Promise.all(me.map(async xe=>{const je=ke(r,xe);return await q({fields:je&&je._f?{[xe]:je}:je,eventType:mo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:mo.TRIGGER});if(Y.delayError&&t.delayError&&wn(z)){const xe=ke(n.errors,z);xe?(Kt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Ul(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=IE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:wn(z)?ke(W,z):z.map(de=>ke(W,de))},Me=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ye=z=>{const Y=z?ud(z):void 0;Y?.forEach(W=>Kt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:je,type:_e,...Ae}=me;wt(n.errors,z,{...Ae,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},tt=(z,Y)=>{if(Ns(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},es=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,hr,z.reRenderRoot)){const je={...l};z.callback({values:je,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},es({...z,formState:{...x,...z.formState}})),ot=(z,Y={})=>{for(const W of z?ud(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Kt(r,W),Kt(l,W)),!Y.keepError&&Kt(n.errors,W),!Y.keepDirty&&Kt(n.dirtyFields,W),!Y.keepTouched&&Kt(n.touchedFields,W),!Y.keepIsValidating&&Kt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Kt(i,W);E.state.next({values:Gt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},Yt=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},Nt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return wt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?Yt({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Dl(Y.min),max:Dl(Y.max),minLength:Dl(Y.minLength),maxLength:Dl(Y.maxLength),pattern:Dl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),Nt(z,Y),f.registerName.delete(z),W=ke(r,z);const je=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(je),Ae=W._f.refs||[];if(_e?Ae.find(Ke=>Ke===je):je===W._f.ref)return;wt(r,z,{_f:{...W._f,..._e?{refs:[...Ae.filter(fp),je,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:je.type,name:z}}:{ref:je}}}),X(z,!1,void 0,je)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},dn=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Ul(r,we,f.mount),jt=z=>{tr(z)&&(E.state.next({disabled:z}),Ul(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},Lt=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=Gt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:je}=await le();A(),n.errors=xe,me=Gt(je)}else await q({fields:r,eventType:mo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Kt(me,xe);if(Kt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),dn(),setTimeout(dn);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},ts=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,Gt(ke(i,z))):(I(z,Y.defaultValue),wt(i,z,Gt(Y.defaultValue))),Y.keepTouched||Kt(n.touchedFields,z),Y.keepDirty||(Kt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,Gt(ke(i,z))):ee()),Y.keepError||(Kt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},At=(z,Y={})=>{const W=z?Gt(z):i,de=Gt(W),me=xn(z),xe=de,je=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ri(i,l,void 0,je))]);for(const Ae of Array.from(_e)){const Ke=ke(n.dirtyFields,Ae),Ct=ke(l,Ae),rn=ke(xe,Ae);Ke&&!Mt(Ct)?wt(xe,Ae,Ct):!Ke&&!Mt(rn)&&I(Ae,rn)}}else{if(gf&&Mt(z))for(const _e of f.mount){const Ae=ke(r,_e);if(Ae&&Ae._f){const Ke=Array.isArray(Ae._f.refs)?Ae._f.refs[0]:Ae._f.ref;if(kd(Ke)){const Ct=Ke.closest("form");if(Ct){Ct.reset();break}}}}if(Y.keepFieldsRef)for(const _e of f.mount)I(_e,ke(xe,_e));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?Gt(i):{},Y.keepFieldsRef)for(const _e of f.mount)wt(l,_e,ke(xe,_e))}else l=Gt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?ri(i,l,void 0,je):n.dirtyFields:Y.keepDefaultValues&&z?ri(i,z,void 0,je):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},sn=(z,Y)=>At(Ns(z)?z(l):z,{...t.resetOptions,...Y}),ns=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Ns(me.select)&&me.select()})}},hr=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},Tn={control:{register:Nt,unregister:ot,getFieldState:Me,handleSubmit:Lt,setError:ht,_subscribe:es,_runSchema:le,_updateIsValidating:A,_focusError:dn,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:Yt,_setErrors:U,_getFieldArray:O,_reset:At,_resetDefaultValues:()=>Ns(t.defaultValues)&&t.defaultValues().then(z=>{sn(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:jt,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Ku(t.mode),w=Ku(t.reValidateMode)}},subscribe:Fe,trigger:Se,register:Nt,handleSubmit:Lt,watch:tt,setValue:I,setValues:re,getValues:ve,reset:sn,resetField:ts,resetDefaultValues:(z,Y={})=>{if(i=Gt(z),!Y.keepDirty){const W=ri(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!xn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ye,unregister:ot,setError:ht,setFocus:ns,getFieldState:Me};return{...Tn,formControl:Tn}}function Vv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Gt(BE),isLoading:Ns(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Ns(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Ns(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},ug=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&ug(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));wt(u,"root",l),wt(n,r,u)}else wt(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Hv=globalThis.__zod_globalConfig;function gi(e){return Hv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function dg(e,t){return typeof t=="bigint"?t.toString():t}function qv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bv(e){return e==null}function Gv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function St(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ma(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=qv(()=>{if(Hv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Jl(e){if(Md(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Md(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function k8(e,t){if(!Jl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ma(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return ji(this,"shape",l),l}});return Ta(e,i)}function R8(e,t){if(!Jl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ji(this,"shape",r),r}});return Ta(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ta(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Ma(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return ji(this,"shape",h),h},checks:[]});return Ta(t,u)}function O8(e,t,n){const r=Ma(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return ji(this,"shape",l),l}});return Ta(t,r)}function wo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Zu(e){return typeof e=="string"?e:e?.message}function vi(e,t,n){const r=e.message?e.message:Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Kv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ec(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zv=pe("$ZodError",XE),xf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new _o;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},L8=bf(xf),wf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},$8=wf(xf),Sf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new _o;return l.issues.length?{success:!1,error:new(e??Zv)(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},F8=Sf(xf),jf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},I8=jf(xf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,i)},U8=e=>(t,n,r)=>bf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},H8=e=>async(t,n,r)=>wf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},B8=e=>(t,n,r)=>Sf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},K8=e=>async(t,n,r)=>jf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Kv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cf=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),Cf.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),Cf.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=yf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${yf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${yf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
+            color: hsl(${Math.max(0,Math.min(120-120*w,120))}deg 100% 31%);`,n?.key)}return i}}function He(e,t,n,r){return{debug:()=>{var i;return(i=e?.debugAll)!=null?i:e[t]},key:!1,onChange:r}}function f$(e,t,n,r){const i=()=>{var u;return(u=l.getValue())!=null?u:e.options.renderFallbackValue},l={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:i,getContext:Ve(()=>[e,n,t,l],(u,f,h,m)=>({table:u,column:f,row:h,cell:m,getValue:m.getValue,renderValue:m.renderValue}),He(e.options,"debugCells"))};return e._features.forEach(u=>{u.createCell==null||u.createCell(l,n,t,e)},{}),l}function h$(e,t,n,r){var i,l;const f={...e._getDefaultColumnDef(),...t},h=f.accessorKey;let m=(i=(l=f.id)!=null?l:h?typeof String.prototype.replaceAll=="function"?h.replaceAll(".","_"):h.replace(/\./g,"_"):void 0)!=null?i:typeof f.header=="string"?f.header:void 0,y;if(f.accessorFn?y=f.accessorFn:h&&(h.includes(".")?y=w=>{let x=w;for(const S of h.split(".")){var j;x=(j=x)==null?void 0:j[S]}return x}:y=w=>w[f.accessorKey]),!m)throw new Error;let g={id:`${String(m)}`,accessorFn:y,parent:r,depth:n,columnDef:f,columns:[],getFlatColumns:Ve(()=>[!0],()=>{var w;return[g,...(w=g.columns)==null?void 0:w.flatMap(x=>x.getFlatColumns())]},He(e.options,"debugColumns")),getLeafColumns:Ve(()=>[e._getOrderColumnsFn()],w=>{var x;if((x=g.columns)!=null&&x.length){let j=g.columns.flatMap(S=>S.getLeafColumns());return w(j)}return[g]},He(e.options,"debugColumns"))};for(const w of e._features)w.createColumn==null||w.createColumn(g,e);return g}const Rn="debugHeaders";function c1(e,t,n){var r;let l={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const u=[],f=h=>{h.subHeaders&&h.subHeaders.length&&h.subHeaders.map(f),u.push(h)};return f(l),u},getContext:()=>({table:e,header:l,column:t})};return e._features.forEach(u=>{u.createHeader==null||u.createHeader(l,e)}),l}const m$={createTable:e=>{e.getHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>{var l,u;const f=(l=r?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?l:[],h=(u=i?.map(g=>n.find(w=>w.id===g)).filter(Boolean))!=null?u:[],m=n.filter(g=>!(r!=null&&r.includes(g.id))&&!(i!=null&&i.includes(g.id)));return qu(t,[...f,...m,...h],e)},He(e.options,Rn)),e.getCenterHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,i)=>(n=n.filter(l=>!(r!=null&&r.includes(l.id))&&!(i!=null&&i.includes(l.id))),qu(t,n,e,"center")),He(e.options,Rn)),e.getLeftHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"left")},He(e.options,Rn)),e.getRightHeaderGroups=Ve(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var i;const l=(i=r?.map(u=>n.find(f=>f.id===u)).filter(Boolean))!=null?i:[];return qu(t,l,e,"right")},He(e.options,Rn)),e.getFooterGroups=Ve(()=>[e.getHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getLeftFooterGroups=Ve(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getCenterFooterGroups=Ve(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getRightFooterGroups=Ve(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),He(e.options,Rn)),e.getFlatHeaders=Ve(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getLeftFlatHeaders=Ve(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterFlatHeaders=Ve(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getRightFlatHeaders=Ve(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),He(e.options,Rn)),e.getCenterLeafHeaders=Ve(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeftLeafHeaders=Ve(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getRightLeafHeaders=Ve(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),He(e.options,Rn)),e.getLeafHeaders=Ve(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var i,l,u,f,h,m;return[...(i=(l=t[0])==null?void 0:l.headers)!=null?i:[],...(u=(f=n[0])==null?void 0:f.headers)!=null?u:[],...(h=(m=r[0])==null?void 0:m.headers)!=null?h:[]].map(y=>y.getLeafHeaders()).flat()},He(e.options,Rn))}};function qu(e,t,n,r){var i,l;let u=0;const f=function(w,x){x===void 0&&(x=1),u=Math.max(u,x),w.filter(j=>j.getIsVisible()).forEach(j=>{var S;(S=j.columns)!=null&&S.length&&f(j.columns,x+1)},0)};f(e);let h=[];const m=(w,x)=>{const j={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},S=[];w.forEach(E=>{const _=[...S].reverse()[0],N=E.column.depth===j.depth;let R,T=!1;if(N&&E.column.parent?R=E.column.parent:(R=E.column,T=!0),_&&_?.column===R)_.subHeaders.push(E);else{const A=c1(n,R,{id:[r,x,R.id,E?.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${S.filter(M=>M.column===R).length}`:void 0,depth:x,index:S.length});A.subHeaders.push(E),S.push(A)}j.headers.push(E),E.headerGroup=j}),h.push(j),x>0&&m(S,x-1)},y=t.map((w,x)=>c1(n,w,{depth:u,index:x}));m(y,u-1),h.reverse();const g=w=>w.filter(j=>j.column.getIsVisible()).map(j=>{let S=0,E=0,_=[0];j.subHeaders&&j.subHeaders.length?(_=[],g(j.subHeaders).forEach(R=>{let{colSpan:T,rowSpan:A}=R;S+=T,_.push(A)})):S=1;const N=Math.min(..._);return E=E+N,j.colSpan=S,j.rowSpan=E,{colSpan:S,rowSpan:E}});return g((i=(l=h[0])==null?void 0:l.headers)!=null?i:[]),h}const p$=(e,t,n,r,i,l,u)=>{let f={id:t,index:r,original:n,depth:i,parentId:u,_valuesCache:{},_uniqueValuesCache:{},getValue:h=>{if(f._valuesCache.hasOwnProperty(h))return f._valuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return f._valuesCache[h]=m.accessorFn(f.original,r),f._valuesCache[h]},getUniqueValues:h=>{if(f._uniqueValuesCache.hasOwnProperty(h))return f._uniqueValuesCache[h];const m=e.getColumn(h);if(m!=null&&m.accessorFn)return m.columnDef.getUniqueValues?(f._uniqueValuesCache[h]=m.columnDef.getUniqueValues(f.original,r),f._uniqueValuesCache[h]):(f._uniqueValuesCache[h]=[f.getValue(h)],f._uniqueValuesCache[h])},renderValue:h=>{var m;return(m=f.getValue(h))!=null?m:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>d$(f.subRows,h=>h.subRows),getParentRow:()=>f.parentId?e.getRow(f.parentId,!0):void 0,getParentRows:()=>{let h=[],m=f;for(;;){const y=m.getParentRow();if(!y)break;h.push(y),m=y}return h.reverse()},getAllCells:Ve(()=>[e.getAllLeafColumns()],h=>h.map(m=>f$(e,f,m,m.id)),He(e.options,"debugRows")),_getAllCellsByColumnId:Ve(()=>[f.getAllCells()],h=>h.reduce((m,y)=>(m[y.column.id]=y,m),{}),He(e.options,"debugRows"))};for(let h=0;h{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},wE=(e,t,n)=>{var r,i;const l=n==null||(r=n.toString())==null?void 0:r.toLowerCase();return!!(!((i=e.getValue(t))==null||(i=i.toString())==null||(i=i.toLowerCase())==null)&&i.includes(l))};wE.autoRemove=e=>Is(e);const SE=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};SE.autoRemove=e=>Is(e);const jE=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};jE.autoRemove=e=>Is(e);const CE=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};CE.autoRemove=e=>Is(e);const _E=(e,t,n)=>!n.some(r=>{var i;return!((i=e.getValue(t))!=null&&i.includes(r))});_E.autoRemove=e=>Is(e)||!(e!=null&&e.length);const EE=(e,t,n)=>n.some(r=>{var i;return(i=e.getValue(t))==null?void 0:i.includes(r)});EE.autoRemove=e=>Is(e)||!(e!=null&&e.length);const NE=(e,t,n)=>e.getValue(t)===n;NE.autoRemove=e=>Is(e);const kE=(e,t,n)=>e.getValue(t)==n;kE.autoRemove=e=>Is(e);const Dv=(e,t,n)=>{let[r,i]=n;const l=e.getValue(t);return l>=r&&l<=i};Dv.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,i=typeof n!="number"?parseFloat(n):n,l=t===null||Number.isNaN(r)?-1/0:r,u=n===null||Number.isNaN(i)?1/0:i;if(l>u){const f=l;l=u,u=f}return[l,u]};Dv.autoRemove=e=>Is(e)||Is(e[0])&&Is(e[1]);const zr={includesString:wE,includesStringSensitive:SE,equalsString:jE,arrIncludes:CE,arrIncludesAll:_E,arrIncludesSome:EE,equals:NE,weakEquals:kE,inNumberRange:Dv};function Is(e){return e==null||e===""}const v$={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:hs("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?zr.includesString:typeof r=="number"?zr.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?zr.equals:Array.isArray(r)?zr.arrIncludes:zr.weakEquals},e.getFilterFn=()=>{var n,r;return pf(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:zr[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,i;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const i=e.getFilterFn(),l=r?.find(y=>y.id===e.id),u=ba(n,l?l.value:void 0);if(u1(i,u,e)){var f;return(f=r?.filter(y=>y.id!==e.id))!=null?f:[]}const h={id:e.id,value:u};if(l){var m;return(m=r?.map(y=>y.id===e.id?h:y))!=null?m:[]}return r!=null&&r.length?[...r,h]:[h]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=i=>{var l;return(l=ba(t,i))==null?void 0:l.filter(u=>{const f=n.find(h=>h.id===u.id);if(f){const h=f.getFilterFn();if(u1(h,u.value,f))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function u1(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const y$=(e,t,n)=>n.reduce((r,i)=>{const l=i.getValue(e);return r+(typeof l=="number"?l:0)},0),x$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r>l||r===void 0&&l>=l)&&(r=l)}),r},b$=(e,t,n)=>{let r;return n.forEach(i=>{const l=i.getValue(e);l!=null&&(r=l)&&(r=l)}),r},w$=(e,t,n)=>{let r,i;return n.forEach(l=>{const u=l.getValue(e);u!=null&&(r===void 0?u>=u&&(r=i=u):(r>u&&(r=u),i{let n=0,r=0;if(t.forEach(i=>{let l=i.getValue(e);l!=null&&(l=+l)>=l&&(++n,r+=l)}),n)return r/n},j$=(e,t)=>{if(!t.length)return;const n=t.map(l=>l.getValue(e));if(!u$(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),i=n.sort((l,u)=>l-u);return n.length%2!==0?i[r]:(i[r-1]+i[r])/2},C$=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),_$=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,E$=(e,t)=>t.length,rp={sum:y$,min:x$,max:b$,extent:w$,mean:S$,median:j$,unique:C$,uniqueCount:_$,count:E$},N$={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:hs("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return rp.sum;if(Object.prototype.toString.call(r)==="[object Date]")return rp.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:rp[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var i;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((i=n.subRows)!=null&&i.length)}}};function k$(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(l=>!t.includes(l.id));return n==="remove"?r:[...t.map(l=>e.find(u=>u.id===l)).filter(Boolean),...r]}const R$={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:hs("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Ve(n=>[Pl(t,n)],n=>n.findIndex(r=>r.id===e.id),He(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Pl(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const i=Pl(t,n);return((r=i[i.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Ve(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>i=>{let l=[];if(!(t!=null&&t.length))l=i;else{const u=[...t],f=[...i];for(;f.length&&u.length;){const h=u.shift(),m=f.findIndex(y=>y.id===h);m>-1&&l.push(f.splice(m,1)[0])}l=[...l,...f]}return k$(l,n,r)},He(e.options,"debugTable"))}},ap=()=>({left:[],right:[]}),M$={getInitialState:e=>({columnPinning:ap(),...e}),getDefaultOptions:e=>({onColumnPinningChange:hs("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(i=>i.id).filter(Boolean);t.setColumnPinning(i=>{var l,u;if(n==="right"){var f,h;return{left:((f=i?.left)!=null?f:[]).filter(g=>!(r!=null&&r.includes(g))),right:[...((h=i?.right)!=null?h:[]).filter(g=>!(r!=null&&r.includes(g))),...r]}}if(n==="left"){var m,y;return{left:[...((m=i?.left)!=null?m:[]).filter(g=>!(r!=null&&r.includes(g))),...r],right:((y=i?.right)!=null?y:[]).filter(g=>!(r!=null&&r.includes(g)))}}return{left:((l=i?.left)!=null?l:[]).filter(g=>!(r!=null&&r.includes(g))),right:((u=i?.right)!=null?u:[]).filter(g=>!(r!=null&&r.includes(g)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var i,l,u;return((i=r.columnDef.enablePinning)!=null?i:!0)&&((l=(u=t.options.enableColumnPinning)!=null?u:t.options.enablePinning)!=null?l:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(f=>f.id),{left:r,right:i}=t.getState().columnPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"left":u?"right":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();return i?(n=(r=t.getState().columnPinning)==null||(r=r[i])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,i)=>{const l=[...r??[],...i??[]];return n.filter(u=>!l.includes(u.column.id))},He(t.options,"debugRows")),e.getLeftVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"left"})),He(t.options,"debugRows")),e.getRightVisibleCells=Ve(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(l=>n.find(u=>u.column.id===l)).filter(Boolean).map(l=>({...l,position:"right"})),He(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?ap():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:ap())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var i,l;return!!((i=r.left)!=null&&i.length||(l=r.right)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getRightLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(i=>i.id===r)).filter(Boolean),He(e.options,"debugColumns")),e.getCenterLeafColumns=Ve(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const i=[...n??[],...r??[]];return t.filter(l=>!i.includes(l.id))},He(e.options,"debugColumns"))}};function T$(e){return e||(typeof document<"u"?document:null)}const Bu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ip=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),O$={getDefaultColumnDef:()=>Bu,getInitialState:e=>({columnSizing:{},columnSizingInfo:ip(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:hs("columnSizing",e),onColumnSizingInfoChange:hs("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,i;const l=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bu.minSize,(r=l??e.columnDef.size)!=null?r:Bu.size),(i=e.columnDef.maxSize)!=null?i:Bu.maxSize)},e.getStart=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.getAfter=Ve(n=>[n,Pl(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((i,l)=>i+l.getSize(),0),He(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...i}=n;return i})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=i=>{if(i.subHeaders.length)i.subHeaders.forEach(r);else{var l;n+=(l=i.column.getSize())!=null?l:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),i=r?.getCanResize();return l=>{if(!r||!i||(l.persist==null||l.persist(),op(l)&&l.touches&&l.touches.length>1))return;const u=e.getSize(),f=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[r.id,r.getSize()]],h=op(l)?Math.round(l.touches[0].clientX):l.clientX,m={},y=(_,N)=>{typeof N=="number"&&(t.setColumnSizingInfo(R=>{var T,A;const M=t.options.columnResizeDirection==="rtl"?-1:1,L=(N-((T=R?.startOffset)!=null?T:0))*M,H=Math.max(L/((A=R?.startSize)!=null?A:0),-.999999);return R.columnSizingStart.forEach(U=>{let[Z,X]=U;m[Z]=Math.round(Math.max(X+X*H,0)*100)/100}),{...R,deltaOffset:L,deltaPercentage:H}}),(t.options.columnResizeMode==="onChange"||_==="end")&&t.setColumnSizing(R=>({...R,...m})))},g=_=>y("move",_),w=_=>{y("end",_),t.setColumnSizingInfo(N=>({...N,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=T$(n),j={moveHandler:_=>g(_.clientX),upHandler:_=>{x?.removeEventListener("mousemove",j.moveHandler),x?.removeEventListener("mouseup",j.upHandler),w(_.clientX)}},S={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),g(_.touches[0].clientX),!1),upHandler:_=>{var N;x?.removeEventListener("touchmove",S.moveHandler),x?.removeEventListener("touchend",S.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),w((N=_.touches[0])==null?void 0:N.clientX)}},E=A$()?{passive:!1}:!1;op(l)?(x?.addEventListener("touchmove",S.moveHandler,E),x?.addEventListener("touchend",S.upHandler,E)):(x?.addEventListener("mousemove",j.moveHandler,E),x?.addEventListener("mouseup",j.upHandler,E)),t.setColumnSizingInfo(_=>({..._,startOffset:h,startSize:u,deltaOffset:0,deltaPercentage:0,columnSizingStart:f,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?ip():(n=e.initialState.columnSizingInfo)!=null?n:ip())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,i)=>r+i.getSize(),0))!=null?t:0}}};let Gu=null;function A$(){if(typeof Gu=="boolean")return Gu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gu=e,Gu}function op(e){return e.type==="touchstart"}const D$={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:hs("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const i=e.columns;return(n=i.length?i.some(l=>l.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Ve(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),He(t.options,"debugRows")),e.getVisibleCells=Ve(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,i)=>[...n,...r,...i],He(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Ve(()=>[r(),r().filter(i=>i.getIsVisible()).map(i=>i.id).join("_")],i=>i.filter(l=>l.getIsVisible==null?void 0:l.getIsVisible()),He(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((i,l)=>({...i,[l.id]:n||!(l.getCanHide!=null&&l.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Pl(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const z$={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},L$={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:hs("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,i,l;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((i=t.options.enableFilters)!=null?i:!0)&&((l=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?l:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>zr.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return pf(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:zr[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},$$={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:hs("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var i,l;e.setExpanded(r?{}:(i=(l=e.initialState)==null?void 0:l.expanded)!=null?i:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(i=>!i.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(l=>{const u=l.split(".");r=Math.max(r,u.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var i;const l=r===!0?!0:!!(r!=null&&r[e.id]);let u={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(f=>{u[f]=!0}):u=r,n=(i=n)!=null?i:!l,!l&&n)return{...u,[e.id]:!0};if(l&&!n){const{[e.id]:f,...h}=u;return h}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,i;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((i=e.subRows)!=null&&i.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},tg=0,ng=10,lp=()=>({pageIndex:tg,pageSize:ng}),F$={getInitialState:e=>({...e,pagination:{...lp(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:hs("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,i;if(!t){e._queue(()=>{t=!0});return}if((r=(i=e.options.autoResetAll)!=null?i:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const i=l=>ba(r,l);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(i)},e.resetPagination=r=>{var i;e.setPagination(r?lp():(i=e.initialState.pagination)!=null?i:lp())},e.setPageIndex=r=>{e.setPagination(i=>{let l=ba(r,i.pageIndex);const u=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return l=Math.max(0,Math.min(l,u)),{...i,pageIndex:l}})},e.resetPageIndex=r=>{var i,l;e.setPageIndex(r?tg:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageIndex)!=null?i:tg)},e.resetPageSize=r=>{var i,l;e.setPageSize(r?ng:(i=(l=e.initialState)==null||(l=l.pagination)==null?void 0:l.pageSize)!=null?i:ng)},e.setPageSize=r=>{e.setPagination(i=>{const l=Math.max(1,ba(r,i.pageSize)),u=i.pageSize*i.pageIndex,f=Math.floor(u/l);return{...i,pageIndex:f,pageSize:l}})},e.setPageCount=r=>e.setPagination(i=>{var l;let u=ba(r,(l=e.options.pageCount)!=null?l:-1);return typeof u=="number"&&(u=Math.max(-1,u)),{...i,pageCount:u}}),e.getPageOptions=Ve(()=>[e.getPageCount()],r=>{let i=[];return r&&r>0&&(i=[...new Array(r)].fill(null).map((l,u)=>u)),i},He(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,i=e.getPageCount();return i===-1?!0:i===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},cp=()=>({top:[],bottom:[]}),I$={getInitialState:e=>({rowPinning:cp(),...e}),getDefaultOptions:e=>({onRowPinningChange:hs("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,i)=>{const l=r?e.getLeafRows().map(h=>{let{id:m}=h;return m}):[],u=i?e.getParentRows().map(h=>{let{id:m}=h;return m}):[],f=new Set([...u,e.id,...l]);t.setRowPinning(h=>{var m,y;if(n==="bottom"){var g,w;return{top:((g=h?.top)!=null?g:[]).filter(S=>!(f!=null&&f.has(S))),bottom:[...((w=h?.bottom)!=null?w:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)]}}if(n==="top"){var x,j;return{top:[...((x=h?.top)!=null?x:[]).filter(S=>!(f!=null&&f.has(S))),...Array.from(f)],bottom:((j=h?.bottom)!=null?j:[]).filter(S=>!(f!=null&&f.has(S)))}}return{top:((m=h?.top)!=null?m:[]).filter(S=>!(f!=null&&f.has(S))),bottom:((y=h?.bottom)!=null?y:[]).filter(S=>!(f!=null&&f.has(S)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:i}=t.options;return typeof r=="function"?r(e):(n=r??i)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:i}=t.getState().rowPinning,l=n.some(f=>r?.includes(f)),u=n.some(f=>i?.includes(f));return l?"top":u?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const i=e.getIsPinned();if(!i)return-1;const l=(n=i==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(u=>{let{id:f}=u;return f});return(r=l?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?cp():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:cp())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var i,l;return!!((i=r.top)!=null&&i.length||(l=r.bottom)!=null&&l.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var i;return((i=e.options.keepPinnedRows)==null||i?(n??[]).map(u=>{const f=e.getRow(u,!0);return f.getIsAllParentsExpanded()?f:null}):(n??[]).map(u=>t.find(f=>f.id===u))).filter(Boolean).map(u=>({...u,position:r}))},e.getTopRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),He(e.options,"debugRows")),e.getBottomRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),He(e.options,"debugRows")),e.getCenterRows=Ve(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const i=new Set([...n??[],...r??[]]);return t.filter(l=>!i.has(l.id))},He(e.options,"debugRows"))}},P$={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:hs("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},i=e.getPreGroupedRowModel().flatRows;return t?i.forEach(l=>{l.getCanSelect()&&(r[l.id]=!0)}):i.forEach(l=>{delete r[l.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),i={...n};return e.getRowModel().rows.forEach(l=>{sg(i,l.id,r,!0,e)}),i}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getFilteredSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getGroupedSelectedRowModel=Ve(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?up(e,n):{rows:[],flatRows:[],rowsById:{}},He(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(i=>i.getCanSelect()&&!n[i.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(i=>i.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(i=>!n[i.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const i=e.getIsSelected();t.setRowSelection(l=>{var u;if(n=typeof n<"u"?n:!i,e.getCanSelect()&&i===n)return l;const f={...l};return sg(f,e.id,n,(u=r?.selectChildren)!=null?u:!0,t),f})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zv(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rg(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var i;n&&e.toggleSelected((i=r.target)==null?void 0:i.checked)}}}},sg=(e,t,n,r,i)=>{var l;const u=i.getRow(t,!0);n?(u.getCanMultiSelect()||Object.keys(e).forEach(f=>delete e[f]),u.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(l=u.subRows)!=null&&l.length&&u.getCanSelectSubRows()&&u.subRows.forEach(f=>sg(e,f.id,n,r,i))};function up(e,t){const n=e.getState().rowSelection,r=[],i={},l=function(u,f){return u.map(h=>{var m;const y=zv(h,n);if(y&&(r.push(h),i[h.id]=h),(m=h.subRows)!=null&&m.length&&(h={...h,subRows:l(h.subRows)}),y)return h}).filter(Boolean)};return{rows:l(t.rows),flatRows:r,rowsById:i}}function zv(e,t){var n;return(n=t[e.id])!=null?n:!1}function rg(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let i=!0,l=!1;return e.subRows.forEach(u=>{if(!(l&&!i)&&(u.getCanSelect()&&(zv(u,t)?l=!0:i=!1),u.subRows&&u.subRows.length)){const f=rg(u,t);f==="all"?l=!0:(f==="some"&&(l=!0),i=!1)}}),i?"all":l?"some":!1}const ag=/([0-9]+)/gm,U$=(e,t,n)=>RE(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),V$=(e,t,n)=>RE(_a(e.getValue(n)),_a(t.getValue(n))),H$=(e,t,n)=>Lv(_a(e.getValue(n)).toLowerCase(),_a(t.getValue(n)).toLowerCase()),q$=(e,t,n)=>Lv(_a(e.getValue(n)),_a(t.getValue(n))),B$=(e,t,n)=>{const r=e.getValue(n),i=t.getValue(n);return r>i?1:rLv(e.getValue(n),t.getValue(n));function Lv(e,t){return e===t?0:e>t?1:-1}function _a(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function RE(e,t){const n=e.split(ag).filter(Boolean),r=t.split(ag).filter(Boolean);for(;n.length&&r.length;){const i=n.shift(),l=r.shift(),u=parseInt(i,10),f=parseInt(l,10),h=[u,f].sort();if(isNaN(h[0])){if(i>l)return 1;if(l>i)return-1;continue}if(isNaN(h[1]))return isNaN(u)?-1:1;if(u>f)return 1;if(f>u)return-1}return n.length-r.length}const Al={alphanumeric:U$,alphanumericCaseSensitive:V$,text:H$,textCaseSensitive:q$,datetime:B$,basic:G$},K$={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:hs("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const i of n){const l=i?.getValue(e.id);if(Object.prototype.toString.call(l)==="[object Date]")return Al.datetime;if(typeof l=="string"&&(r=!0,l.split(ag).length>1))return Al.alphanumeric}return r?Al.text:Al.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return pf(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Al[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const i=e.getNextSortingOrder(),l=typeof n<"u"&&n!==null;t.setSorting(u=>{const f=u?.find(x=>x.id===e.id),h=u?.findIndex(x=>x.id===e.id);let m=[],y,g=l?n:i==="desc";if(u!=null&&u.length&&e.getCanMultiSort()&&r?f?y="toggle":y="add":u!=null&&u.length&&h!==u.length-1?y="replace":f?y="toggle":y="replace",y==="toggle"&&(l||i||(y="remove")),y==="add"){var w;m=[...u,{id:e.id,desc:g}],m.splice(0,m.length-((w=t.options.maxMultiSortColCount)!=null?w:Number.MAX_SAFE_INTEGER))}else y==="toggle"?m=u.map(x=>x.id===e.id?{...x,desc:g}:x):y==="remove"?m=u.filter(x=>x.id!==e.id):m=[{id:e.id,desc:g}];return m})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,i;const l=e.getFirstSortDir(),u=e.getIsSorted();return u?u!==l&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(i=t.options.enableMultiRemove)!=null)||i)?!1:u==="desc"?"asc":"desc":l},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(i=>i.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(i=>i.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Z$=[m$,D$,R$,M$,g$,v$,z$,L$,K$,N$,$$,F$,I$,P$,O$];function Y$(e){var t,n;const r=[...Z$,...(t=e._features)!=null?t:[]];let i={_features:r};const l=i._features.reduce((w,x)=>Object.assign(w,x.getDefaultOptions==null?void 0:x.getDefaultOptions(i)),{}),u=w=>i.options.mergeOptions?i.options.mergeOptions(l,w):{...l,...w};let h={...{},...(n=e.initialState)!=null?n:{}};i._features.forEach(w=>{var x;h=(x=w.getInitialState==null?void 0:w.getInitialState(h))!=null?x:h});const m=[];let y=!1;const g={_features:r,options:{...l,...e},initialState:h,_queue:w=>{m.push(w),y||(y=!0,Promise.resolve().then(()=>{for(;m.length;)m.shift()();y=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{i.setState(i.initialState)},setOptions:w=>{const x=ba(w,i.options);i.options=u(x)},getState:()=>i.options.state,setState:w=>{i.options.onStateChange==null||i.options.onStateChange(w)},_getRowId:(w,x,j)=>{var S;return(S=i.options.getRowId==null?void 0:i.options.getRowId(w,x,j))!=null?S:`${j?[j.id,x].join("."):x}`},getCoreRowModel:()=>(i._getCoreRowModel||(i._getCoreRowModel=i.options.getCoreRowModel(i)),i._getCoreRowModel()),getRowModel:()=>i.getPaginationRowModel(),getRow:(w,x)=>{let j=(x?i.getPrePaginationRowModel():i.getRowModel()).rowsById[w];if(!j&&(j=i.getCoreRowModel().rowsById[w],!j))throw new Error;return j},_getDefaultColumnDef:Ve(()=>[i.options.defaultColumn],w=>{var x;return w=(x=w)!=null?x:{},{header:j=>{const S=j.header.column.columnDef;return S.accessorKey?S.accessorKey:S.accessorFn?S.id:null},cell:j=>{var S,E;return(S=(E=j.renderValue())==null||E.toString==null?void 0:E.toString())!=null?S:null},...i._features.reduce((j,S)=>Object.assign(j,S.getDefaultColumnDef==null?void 0:S.getDefaultColumnDef()),{}),...w}},He(e,"debugColumns")),_getColumnDefs:()=>i.options.columns,getAllColumns:Ve(()=>[i._getColumnDefs()],w=>{const x=function(j,S,E){return E===void 0&&(E=0),j.map(_=>{const N=h$(i,_,E,S),R=_;return N.columns=R.columns?x(R.columns,N,E+1):[],N})};return x(w)},He(e,"debugColumns")),getAllFlatColumns:Ve(()=>[i.getAllColumns()],w=>w.flatMap(x=>x.getFlatColumns()),He(e,"debugColumns")),_getAllFlatColumnsById:Ve(()=>[i.getAllFlatColumns()],w=>w.reduce((x,j)=>(x[j.id]=j,x),{}),He(e,"debugColumns")),getAllLeafColumns:Ve(()=>[i.getAllColumns(),i._getOrderColumnsFn()],(w,x)=>{let j=w.flatMap(S=>S.getLeafColumns());return x(j)},He(e,"debugColumns")),getColumn:w=>i._getAllFlatColumnsById()[w]};Object.assign(i,g);for(let w=0;wVe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(i,l,u){l===void 0&&(l=0);const f=[];for(let m=0;me._autoResetPageIndex()))}function TE(){return e=>Ve(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,i=[],l=r.filter(h=>{var m;return(m=e.getColumn(h.id))==null?void 0:m.getCanSort()}),u={};l.forEach(h=>{const m=e.getColumn(h.id);m&&(u[h.id]={sortUndefined:m.columnDef.sortUndefined,invertSorting:m.columnDef.invertSorting,sortingFn:m.getSortingFn()})});const f=h=>{const m=h.map(y=>({...y}));return m.sort((y,g)=>{for(let x=0;x{var g;i.push(y),(g=y.subRows)!=null&&g.length&&(y.subRows=f(y.subRows))}),m};return{rows:f(n.rows),flatRows:i,rowsById:n.rowsById}},He(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function ig(e,t){return e?Q$(e)?b.createElement(e,t):e:null}function Q$(e){return X$(e)||typeof e=="function"||W$(e)}function X$(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function W$(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OE(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=b.useState(()=>({current:Y$(t)})),[r,i]=b.useState(()=>n.current.initialState);return n.current.setOptions(l=>({...l,...e,state:{...r,...e.state},onStateChange:u=>{i(u),e.onStateChange==null||e.onStateChange(u)}})),n.current}var hc=e=>e.type==="checkbox",wa=e=>e instanceof Date,bn=e=>e==null;const $v=e=>typeof e=="object";var Vt=e=>!bn(e)&&!Array.isArray(e)&&$v(e)&&!wa(e),J$=e=>Vt(e)&&e.target?hc(e.target)?e.target.checked:e.target.value:e,e8=(e,t)=>t.split(".").some((n,r,i)=>!isNaN(Number(n))&&e.has(i.slice(0,r).join("."))),AE=e=>{const t=e.constructor&&e.constructor.prototype;return Vt(t)&&t.hasOwnProperty("isPrototypeOf")},gf=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(gf&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(Vt(e)&&AE(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Gt(e[i]));return r}const mo={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},$s={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ls={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},DE="root",Fv=["__proto__","constructor","prototype"],t8=/^\w*$/;var mc=e=>t8.test(e),Mt=e=>e===void 0;const n8=/[.[\]'"]/;var vf=e=>e.split(n8).filter(Boolean),ke=(e,t,n)=>{if(!t||!Vt(e))return n;const r=mc(t)?[t]:vf(t);if(r.some(l=>Fv.includes(l)))return n;const i=r.reduce((l,u)=>bn(l)?void 0:l[u],e);return Mt(i)||i===e?Mt(e[t])?n:e[t]:i},tr=e=>typeof e=="boolean",Ns=e=>typeof e=="function",wt=(e,t,n)=>{let r=-1;const i=mc(t)?[t]:vf(t),l=i.length,u=l-1;for(;++r{const i={};for(const l in e)Object.defineProperty(i,l,{get:()=>{const u=l;return t._proxyFormState[u]!==$s.all&&(t._proxyFormState[u]=!r||$s.all),e[u]}});return i};const a8=gf?ye.useLayoutEffect:ye.useEffect;var wn=e=>typeof e=="string",i8=(e,t,n,r,i)=>wn(e)?(r&&t.watch.add(e),ke(n,e,i)):Array.isArray(e)?e.map(l=>(r&&t.watch.add(l),ke(n,l))):(r&&(t.watchAll=!0),n),og=e=>bn(e)||!$v(e);const d1=(e,t)=>t.length===0&&!Array.isArray(e)&&!AE(e);function nr(e,t,n=new WeakMap){if(e===t)return!0;if(og(e)||og(t))return Object.is(e,t);if(wa(e)&&wa(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(d1(e,r)||d1(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;const l=n.get(e);if(l&&l.has(t))return!0;if(l)l.add(t);else{const u=new WeakSet;u.add(t),n.set(e,u)}for(const u of r){const f=e[u];if(!(u in t))return!1;if(u!=="ref"){const h=t[u];if(wa(f)&&wa(h)||(Vt(f)||Array.isArray(f))&&(Vt(h)||Array.isArray(h))?!nr(f,h,n):!Object.is(f,h))return!1}}return!0}var Ku=e=>({isOnSubmit:!e||e===$s.onSubmit,isOnBlur:e===$s.onBlur,isOnChange:e===$s.onChange,isOnAll:e===$s.all,isOnTouch:e===$s.onTouched}),dp=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(const r of t.watch)if(e.startsWith(r)&&e.charAt(r.length)===".")return!0;return!1};const Ul=(e,t,n,r)=>{for(const i of n||Object.keys(e)){const l=ke(e,i);if(l){const{_f:u,...f}=l;if(u){if(u.refs&&u.refs[0]&&t(u.refs[0],i)&&!r)return!0;if(u.ref&&t(u.ref,u.name)&&!r)return!0;if(Ul(f,t))break}else if(Vt(f)&&Ul(f,t))break}}};var f1=(e,t,n)=>{const r=ke(e,n),i=Array.isArray(r)?r:[];return wt(i,DE,t[n]),wt(e,n,i),e},xn=e=>Vt(e)&&!Object.keys(e).length,Iv=e=>e.type==="file",kd=e=>{if(!gf)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pv=e=>e.type==="radio",Rd=e=>e instanceof RegExp,Uv=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{};const h1={value:!1,isValid:!1},m1={value:!0,isValid:!0};var zE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Mt(e[0].attributes.value)?Mt(e[0].value)||e[0].value===""?m1:{value:e[0].value,isValid:!0}:m1:h1}return h1};const p1={isValid:!1,value:null};var LE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,p1):p1;function g1(e,t,n="validate"){if(wn(e)||Array.isArray(e)&&e.every(wn)||tr(e)&&!e)return{type:n,message:wn(e)?e:"",ref:t}}var po=e=>Vt(e)&&!Rd(e)?e:{value:e,message:""},v1=async(e,t,n,r,i,l)=>{const{ref:u,refs:f,required:h,maxLength:m,minLength:y,min:g,max:w,pattern:x,validate:j,name:S,valueAsNumber:E,mount:_}=e._f,N=ke(n,S);if(!_||t.has(S))return{};const R=f?f[0]:u,T=Q=>{if(i&&R.reportValidity){const ae=tr(Q)?"":Q||"";f?f.forEach(le=>le.setCustomValidity(ae)):R.setCustomValidity(ae),R.reportValidity()}},A={},M=Pv(u),L=hc(u),H=M||L,U=(E||Iv(u))&&Mt(u.value)&&Mt(N)||kd(u)&&u.value===""||N===""||Array.isArray(N)&&!N.length,Z=Uv.bind(null,S,r,A),X=(Q,ae,le,be=Ls.maxLength,$=Ls.minLength)=>{const q=Q?ae:le;A[S]={type:Q?be:$,message:q,ref:u,...Z(Q?be:$,q)}};if(l?!Array.isArray(N)||!N.length:h&&(!H&&(U||bn(N))||tr(N)&&!N||L&&!zE(f).isValid||M&&!LE(f).isValid)){const{value:Q,message:ae}=wn(h)?{value:!!h,message:h}:po(h);if(Q&&(A[S]={type:Ls.required,message:ae,ref:R,...Z(Ls.required,ae)},!r))return T(ae),A}if(!U&&(!bn(g)||!bn(w))){let Q,ae;const le=po(w),be=po(g);if(!bn(N)&&!isNaN(N)){const $=u.valueAsNumber||N&&+N;bn(le.value)||(Q=$>le.value),bn(be.value)||(ae=$new Date(new Date().toDateString()+" "+K),V=u.type=="time",ee=u.type=="week";wn(le.value)&&N&&(Q=V?q(N)>q(le.value):ee?N>le.value:$>new Date(le.value)),wn(be.value)&&N&&(ae=V?q(N)+Q.value,be=!bn(ae.value)&&N.length<+ae.value;if((le||be)&&(X(le,Q.message,ae.message),!r))return T(A[S].message),A}if(x&&!U&&wn(N)){const{value:Q,message:ae}=po(x);if(Rd(Q)&&!N.match(Q)&&(A[S]={type:Ls.pattern,message:ae,ref:u,...Z(Ls.pattern,ae)},!r))return T(ae),A}if(j){if(Ns(j)){const Q=await j(N,n),ae=g1(Q,R);if(ae&&(A[S]={...ae,...Z(Ls.validate,ae.message)},!r))return T(ae.message),A}else if(Vt(j)){let Q={};for(const ae in j){if(!xn(Q)&&!r)break;const le=g1(await j[ae](N,n),R,ae);le&&(Q={...le,...Z(ae,le.message)},T(le.message),r&&(A[S]=Q))}if(!xn(Q)&&(A[S]={ref:R,...Q},!r))return A}}return T(!0),A},ud=e=>Array.isArray(e)?e:[e],$E=e=>Array.isArray(e)?e.filter(Boolean):[];function o8(e,t){const n=t.slice(0,-1).length;let r=0;for(;rFv.includes(String(u))))return e;const r=n.length===1?e:o8(e,n),i=n.length-1,l=n[i];return r&&delete r[l],i!==0&&(Vt(r)&&xn(r)||Array.isArray(r)&&l8(r))&&Kt(e,n.slice(0,-1)),e}const FE=e=>{const t={};for(const n of Object.keys(e))if($v(e[n])&&e[n]!==null&&!wa(e[n])){const r=FE(e[n]);for(const i of Object.keys(r))t[`${n}.${i}`]=r[i]}else t[n]=e[n];return t},c8=ye.createContext(null);c8.displayName="HookFormContext";var y1=()=>{let e=[];return{get observers(){return e},next:i=>{for(const l of e)l.next&&l.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(l=>l!==i)}}),unsubscribe:()=>{e=[]}}};function IE(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const i=e[r],l=t[r];if(i&&Vt(i)&&l){const u=IE(i,l);Vt(u)&&(n[r]=u)}else e[r]&&(n[r]=l)}return n}var PE=e=>e.type==="select-multiple",u8=e=>Pv(e)||hc(e),fp=e=>kd(e)&&e.isConnected,d8=e=>{for(const t in e)if(Ns(e[t]))return!0;return!1};function UE(e){return Array.isArray(e)||Vt(e)&&!d8(e)}function VE(e){return!!(e&&"_f"in e)}function HE(e){return Array.isArray(e)?!e.some(t=>!Mt(t)):!Object.keys(e).length}function lg(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function cg(e,t={},n){for(const r in e){const i=e[r],l=n&&n[r];UE(i)&&(!Array.isArray(i)||!VE(l))?(t[r]=Array.isArray(i)?[]:{},cg(i,t[r],l),HE(t[r])&&lg(t,r)):Mt(i)||(t[r]=!0)}return t}function ri(e,t,n,r){n||(n=cg(t,{},r));for(const i in e){const l=e[i],u=r&&r[i];UE(l)&&(!Array.isArray(l)||!VE(u))?(Mt(t)||og(n[i])?n[i]=cg(l,Array.isArray(l)?[]:{},u):ri(l,bn(t)?{}:t[i],n[i],u),HE(n[i])&&lg(n,i)):nr(l,t[i])?lg(n,i):n[i]=!0}return n}var qE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Mt(e)?e:t?e===""?NaN:e&&+e:n&&wn(e)?new Date(e):r?r(e):e;function x1(e){const t=e.ref;return Iv(t)?t.files:Pv(t)?LE(e.refs).value:PE(t)?[...t.selectedOptions].map(({value:n})=>n):hc(t)?zE(e.refs).value:qE(Mt(t.value)?e.ref.value:t.value,e)}var f8=(e,t,n,r)=>{const i={};for(const l of e){const u=ke(t,l);u&&wt(i,l,u._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},Dl=e=>Mt(e)?e:Rd(e)?e.source:Vt(e)?Rd(e.value)?e.value.source:e.value:e;const b1="AsyncFunction";var h8=e=>{if(!e||!e.validate)return!1;if(Ns(e.validate))return e.validate.constructor.name===b1;if(Vt(e.validate)){for(const t in e.validate)if(e.validate[t].constructor.name===b1)return!0}return!1},m8=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=ke(e,n);if(r||mc(n))return{error:r,name:n};const i=n.split(".");for(;i.length;){const l=i.join("."),u=ke(t,l),f=ke(e,l);if(u&&!Array.isArray(u)&&n!==l)return{name:n};if(f&&f.type)return{name:l,error:f};if(f&&f.root&&f.root.type)return{name:`${l}.root`,error:f.root};i.pop()}return{name:n}}var p8=(e,t,n,r)=>{n(e);const{name:i,...l}=e,u=Object.keys(l);return!u.length||r&&u.length>=Object.keys(t).length||u.find(f=>t[f]===(!r||$s.all))},g8=(e,t,n)=>!e||!t||e===t||ud(e).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),v8=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:(n?r.isOnChange:i.isOnChange)?e:!0,y8=(e,t)=>!$E(ke(e,t)).length&&Kt(e,t);const x8={mode:$s.onSubmit,reValidateMode:$s.onChange,shouldFocusError:!0},hp="form",BE={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b8(e={}){let t={...x8,...e},n={...Gt(BE),isLoading:Ns(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=Vt(t.defaultValues)||Vt(t.values)?Gt(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Gt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const h={},m={};let y=0,g=Ku(t.mode),w=Ku(t.reValidateMode);const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},j={...x};let S={...j};const E={array:y1(),state:y1()};let _=0;const N=t.criteriaMode===$s.all,R=(z,Y)=>W=>{clearTimeout(m[z]),m[z]=setTimeout(Y,W)},T=async z=>{if(!u.keepIsValid&&!t.disabled&&(j.isValid||S.isValid||z)){const Y=++_;let W;t.resolver?(W=xn((await le()).errors),Y===_&&A()):W=await q({fields:r,onlyCheckValid:!0,eventType:mo.VALID}),Y===_&&W!==n.isValid&&E.state.next({isValid:W})}},A=(z,Y)=>{!t.disabled&&(j.isValidating||j.validatingFields||S.isValidating||S.validatingFields)&&((z||Array.from(f.mount)).forEach(W=>{W&&(Y?wt(n.validatingFields,W,Y):Kt(n.validatingFields,W))}),E.state.next({validatingFields:n.validatingFields,isValidating:!xn(n.validatingFields)}))},M=()=>{n.dirtyFields=ri(i,l,void 0,r)},L=(z,Y=[],W,de,me=!0,xe=!0)=>{if(de&&W&&!t.disabled){if(u.action=!0,xe&&Array.isArray(ke(r,z))){const je=W(ke(r,z),de.argA,de.argB);me&&wt(r,z,je)}if(xe&&Array.isArray(ke(n.errors,z))){const je=W(ke(n.errors,z),de.argA,de.argB);me&&wt(n.errors,z,je),y8(n.errors,z)}if((j.touchedFields||S.touchedFields)&&xe&&Array.isArray(ke(n.touchedFields,z))){const je=W(ke(n.touchedFields,z),de.argA,de.argB);me&&wt(n.touchedFields,z,je)}(j.dirtyFields||S.dirtyFields)&&M(),E.state.next({name:z,isDirty:ee(z,Y),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else wt(l,z,Y)},H=(z,Y)=>{wt(n.errors,z,Y),n.errors={...n.errors},E.state.next({errors:n.errors})},U=z=>{n.errors=z,E.state.next({errors:n.errors,isValid:!1})},Z=z=>{const Y=mc(z)?[z]:vf(z);let W=l,de=i;for(let me=0;me{const me=ke(r,z);if(me){if(Z(z))return;const xe=Mt(ke(l,z)),je=ke(l,z,Mt(W)?ke(i,z):W);Mt(je)||de&&de.defaultChecked||Y?wt(l,z,Y?je:x1(me._f)):D(z,je),u.mount&&!u.action&&(T(),xe&&n.isDirty&&(j.isDirty||S.isDirty)&&(ee()||(n.isDirty=!1,E.state.next({...n}))),e.shouldUnregister&&xe&&!Mt(ke(l,z))&&dp(z,f)&&(u.watch=!0))}},Q=(z,Y,W,de,me)=>{let xe=!1,je=!1;const _e={name:z};if(!t.disabled||de===!0){if(!W||de){const Ae=nr(ke(i,z),Y);(j.isDirty||S.isDirty)&&(je=n.isDirty,n.isDirty=_e.isDirty=!Ae||ee(),xe=je!==_e.isDirty),je=!!ke(n.dirtyFields,z),Ae!==n.isDirty?n.dirtyFields=ri(i,l,void 0,r):Ae?Kt(n.dirtyFields,z):wt(n.dirtyFields,z,!0),_e.dirtyFields=n.dirtyFields,xe=xe||(j.dirtyFields||S.dirtyFields)&&je!==!Ae}if(W){const Ae=ke(n.touchedFields,z);Ae||(wt(n.touchedFields,z,W),_e.touchedFields=n.touchedFields,xe=xe||(j.touchedFields||S.touchedFields)&&Ae!==W)}xe&&me&&E.state.next(_e)}return xe?_e:{}},ae=(z,Y,W,de)=>{const me=ke(n.errors,z),xe=(j.isValid||S.isValid)&&tr(Y)&&n.isValid!==Y;if(t.delayError&&W?(h[z]=R(z,()=>H(z,W)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z],W?wt(n.errors,z,W):Kt(n.errors,z),n.errors={...n.errors}),(W?!nr(me,W):me)||!xn(de)||xe){const je={...de,...xe&&tr(Y)?{isValid:Y}:{},errors:n.errors,name:z};n={...n,...je},E.state.next(je)}},le=async z=>(A(z,!0),await t.resolver(l,t.context,f8(z||f.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),be=async z=>{const{errors:Y}=await le(z);if(A(z),z){for(const W of z){const de=ke(Y,W);de?f.array.has(W)&&Vt(de)&&!Object.keys(de).some(me=>!Number.isNaN(Number(me)))?f1(n.errors,{[W]:de},W):wt(n.errors,W,de):Kt(n.errors,W)}n.errors={...n.errors}}else n.errors=Y;return Y},$=async({name:z,eventType:Y})=>{if(e.validate){const W=await e.validate({formValues:l,formState:n,name:z,eventType:Y});if(Vt(W))for(const de in W){const me=W[de];me&&ht(`${hp}.${de}`,{message:wn(me.message)?me.message:"",type:me.type||Ls.validate})}else wn(W)||!W?ht(hp,{message:W||"",type:Ls.validate}):Ye(hp);return W}return!0},q=async({fields:z,onlyCheckValid:Y,name:W,eventType:de,context:me={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(me.runRootValidation=!0,!await $({name:W,eventType:de})&&(me.valid=!1,Y)))return me.valid;for(const xe in z){const je=z[xe];if(je){const{_f:_e,...Ae}=je;if(_e){const Ke=f.array.has(_e.name),_t=je._f&&h8(je._f),an=j.validatingFields||j.isValidating||S.validatingFields||S.isValidating;_t&&an&&A([_e.name],!0);const Dt=await v1(je,f.disabled,l,N,t.shouldUseNativeValidation&&!Y,Ke);if(_t&&an&&A([_e.name]),Dt[_e.name]&&(me.valid=!1,Y)||(!Y&&(ke(Dt,_e.name)?Ke?f1(n.errors,Dt,_e.name):wt(n.errors,_e.name,Dt[_e.name]):Kt(n.errors,_e.name)),e.shouldUseNativeValidation&&Dt[_e.name]))break}!xn(Ae)&&await q({context:me,onlyCheckValid:Y,fields:Ae,name:xe,eventType:de})}}return me.valid},V=()=>{for(const z of f.unMount){const Y=ke(r,z);Y&&(Y._f.refs?Y._f.refs.every(W=>!fp(W)):!fp(Y._f.ref))&&ot(z)}f.unMount=new Set},ee=(z,Y)=>(z&&Y&&wt(l,z,Y),!nr(u.mount?l:i,i)),K=(z,Y,W)=>i8(z,f,{...u.mount?l:Mt(Y)?i:wn(z)?{[z]:Y}:Y},W,Y),O=z=>$E(ke(u.mount?l:i,z,t.shouldUnregister?ke(i,z,[]):[])),D=(z,Y,W={},de=!1,me=!1)=>{const xe=ke(r,z);let je=Y;if(xe){const _e=xe._f;_e&&(!_e.disabled&&wt(l,z,qE(Y,_e)),je=kd(_e.ref)&&bn(Y)?"":Y,PE(_e.ref)?[..._e.ref.options].forEach(Ae=>Ae.selected=je.includes(Ae.value)):_e.refs?hc(_e.ref)?_e.refs.forEach(Ae=>{(!Ae.defaultChecked||!Ae.disabled)&&(Array.isArray(je)?Ae.checked=!!je.find(Ke=>Ke===Ae.value):Ae.checked=je===Ae.value||!!je)}):_e.refs.forEach(Ae=>Ae.checked=Ae.value===je):Iv(_e.ref)?_e.ref.value="":(_e.ref.value=je,!_e.ref.type&&!me&&E.state.next({name:z,values:de?l:Gt(l)})))}(W.shouldDirty||W.shouldTouch)&&Q(z,je,W.shouldTouch,W.shouldDirty,!me),W.shouldValidate&&Se(z,{delayError:W.delayError})},B=(z,Y,W,de=!1,me=!1)=>{for(const xe in Y){if(!Y.hasOwnProperty(xe))return;const je=Y[xe],_e=z+"."+xe,Ae=ke(r,_e);(f.array.has(z)||Vt(je)||Ae&&!Ae._f)&&!wa(je)?B(_e,je,W,de,me):D(_e,je,W,de,me)}},P=(z,Y,W,de,me=!1)=>{const xe=ke(r,z),je=f.array.has(z),_e=de?Y:Gt(Y),Ae=ke(l,z),Ke=nr(Ae,_e);if(Ke||wt(l,z,_e),je)E.array.next({name:z,values:de?l:Gt(l)}),(j.isDirty||j.dirtyFields||S.isDirty||S.dirtyFields)&&W.shouldDirty&&(M(),me||E.state.next({name:z,dirtyFields:n.dirtyFields,isDirty:ee(z,_e)}));else{const _t=Array.isArray(_e)&&!_e.length||xn(_e);!xe||xe._f||bn(_e)||_t?D(z,_e,W,de,me):B(z,_e,W,de,me)}if(!Ke&&!me){const _t=dp(z,f),an=de?l:Gt(l);E.state.next({..._t&&n,name:u.mount||_t?z:void 0,values:an})}},I=(z,Y,W={})=>P(z,Y,W,!1),re=(z,Y={})=>{const W=Ns(z)?z(l):z;if(!nr(l,W)){l={...l,...W};const de=FE(W);for(const me of f.mount)me in de&&P(me,de[me],Y,!0,!0);E.state.next({...n,name:void 0,type:void 0,...y?{values:l}:{}}),Y.shouldValidate&&T()}},he=async z=>{u.mount=!0;const Y=z.target;let W=Y.name,de=!0;const me=ke(r,W),xe=je=>{de=Number.isNaN(je)||wa(je)&&isNaN(je.getTime())||nr(je,ke(l,W,je))};if(me){let je,_e;const Ae=Y.type?x1(me._f):J$(z),Ke=z.type===mo.BLUR||z.type===mo.FOCUS_OUT,_t=!m8(me._f)&&!e.validate&&!t.resolver&&!ke(n.errors,W)&&!me._f.deps,an=_t||v8(Ke,ke(n.touchedFields,W),n.isSubmitted,w,g),Dt=dp(W,f,Ke);if(wt(l,W,Ae),Ke){if(!Y||!Y.readOnly){me._f.onBlur&&me._f.onBlur(z);const Nt=h[W];Nt&&Nt(0)}}else me._f.onChange&&me._f.onChange(z);const Le=Q(W,Ae,Ke),dt=!xn(Le)||Dt;if(!Ke&&E.state.next({name:W,type:z.type,...y?{values:Gt(l)}:{}}),an)return(!_t||!n.isValid)&&(j.isValid||S.isValid)&&(t.mode==="onBlur"?Ke&&T():Ke||T()),dt&&E.state.next({name:W,...Dt?{}:Le});if(!t.resolver&&e.validate&&await $({name:W,eventType:z.type}),!Ke&&Dt&&E.state.next({...n}),t.resolver){const{errors:Nt}=await le([W]);if(A([W]),xe(Ae),!de){!xn(Le)&&E.state.next(Le);return}const $t=w1(n.errors,r,W),Hn=w1(Nt,r,$t.name||W);je=Hn.error,W=Hn.name,_e=xn(Nt)}else A([W],!0),je=(await v1(me,f.disabled,l,N,t.shouldUseNativeValidation))[W],A([W]),xe(Ae),de&&(je?_e=!1:(j.isValid||S.isValid)&&(_e=await q({fields:r,onlyCheckValid:!0,name:W,eventType:z.type})));de&&(me._f.deps&&(!Array.isArray(me._f.deps)||me._f.deps.length>0)&&Se(me._f.deps),ae(W,_e,je,Le))}},we=(z,Y)=>{if(ke(n.errors,Y)&&z.focus)return z.focus(),1},Se=async(z,Y={})=>{let W,de;const me=ud(z);if(t.resolver){const xe=await be(Mt(z)?z:me);W=xn(xe),de=z?!me.some(je=>ke(xe,je)):W}else z?(de=(await Promise.all(me.map(async xe=>{const je=ke(r,xe);return await q({fields:je&&je._f?{[xe]:je}:je,eventType:mo.TRIGGER})}))).every(Boolean),!(!de&&!n.isValid)&&T()):de=W=await q({fields:r,name:z,eventType:mo.TRIGGER});if(Y.delayError&&t.delayError&&wn(z)){const xe=ke(n.errors,z);xe?(Kt(n.errors,z),h[z]=R(z,()=>H(z,xe)),h[z](t.delayError)):(clearTimeout(m[z]),delete h[z])}return E.state.next({...!wn(z)||(j.isValid||S.isValid)&&W!==n.isValid?{}:{name:z},...t.resolver||!z?{isValid:W}:{},errors:n.errors}),Y.shouldFocus&&!de&&Ul(r,we,z?me:f.mount),de},ve=(z,Y)=>{let W={...u.mount?l:i};return Y&&(W=IE(Y.dirtyFields?n.dirtyFields:n.touchedFields,W)),Mt(z)?W:wn(z)?ke(W,z):z.map(de=>ke(W,de))},Me=(z,Y)=>({invalid:!!ke((Y||n).errors,z),isDirty:!!ke((Y||n).dirtyFields,z),error:ke((Y||n).errors,z),isValidating:!!ke(n.validatingFields,z),isTouched:!!ke((Y||n).touchedFields,z)}),Ye=z=>{const Y=z?ud(z):void 0;Y?.forEach(W=>Kt(n.errors,W)),Y?Y.forEach(W=>{E.state.next({name:W,errors:n.errors})}):E.state.next({errors:{}})},ht=(z,Y,W)=>{const de=(ke(r,z,{_f:{}})._f||{}).ref,me=ke(n.errors,z)||{},{ref:xe,message:je,type:_e,...Ae}=me;wt(n.errors,z,{...Ae,...Y,ref:de}),E.state.next({name:z,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&de&&de.focus&&de.focus()},tt=(z,Y)=>{if(Ns(z)){y++;const{unsubscribe:W}=E.state.subscribe({next:me=>"values"in me&&z(me.values||K(void 0,Y),me)});let de=!1;return{unsubscribe:()=>{de||(de=!0,y--,W())}}}return K(z,Y,!0)},es=z=>{var Y;const W=!!(!((Y=z.formState)===null||Y===void 0)&&Y.values);W&&y++;const{unsubscribe:de}=E.state.subscribe({next:xe=>{if(g8(z.name,xe.name,z.exact)&&p8(xe,z.formState||j,hr,z.reRenderRoot)){const je={...l};z.callback({values:je,...n,...xe,defaultValues:i})}}});if(!W)return de;let me=!1;return()=>{me||(me=!0,y--,de())}},Fe=z=>(u.mount=!0,S={...S,...z.formState},es({...z,formState:{...x,...z.formState}})),ot=(z,Y={})=>{for(const W of z?ud(z):f.mount)f.mount.delete(W),f.array.delete(W),Y.keepValue||(Kt(r,W),Kt(l,W)),!Y.keepError&&Kt(n.errors,W),!Y.keepDirty&&Kt(n.dirtyFields,W),!Y.keepTouched&&Kt(n.touchedFields,W),!Y.keepIsValidating&&Kt(n.validatingFields,W),!t.shouldUnregister&&!Y.keepDefaultValue&&Kt(i,W);E.state.next({values:Gt(l)}),E.state.next({...n,...Y.keepDirty?{isDirty:ee()}:{}}),!Y.keepIsValid&&T()},Yt=({disabled:z,name:Y})=>{if(tr(z)&&u.mount||z||f.disabled.has(Y)){const me=f.disabled.has(Y)!==!!z;z?f.disabled.add(Y):f.disabled.delete(Y),me&&u.mount&&!u.action&&T()}},jt=(z,Y={})=>{let W=ke(r,z);const de=tr(Y.disabled)||tr(t.disabled),me=!f.registerName.has(z)&&W&&W._f&&!W._f.mount;return wt(r,z,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:z}},name:z,mount:!0,...Y}}),f.mount.add(z),W&&!me?Yt({disabled:tr(Y.disabled)?Y.disabled:t.disabled,name:z}):X(z,!0,Y.value),{...de?{disabled:Y.disabled||t.disabled}:{},...t.progressive?{required:!!Y.required,min:Dl(Y.min),max:Dl(Y.max),minLength:Dl(Y.minLength),maxLength:Dl(Y.maxLength),pattern:Dl(Y.pattern)}:{},name:z,onChange:he,onBlur:he,ref:xe=>{if(xe){f.registerName.add(z),jt(z,Y),f.registerName.delete(z),W=ke(r,z);const je=Mt(xe.value)&&xe.querySelectorAll&&xe.querySelectorAll("input,select,textarea")[0]||xe,_e=u8(je),Ae=W._f.refs||[];if(_e?Ae.find(Ke=>Ke===je):je===W._f.ref)return;wt(r,z,{_f:{...W._f,..._e?{refs:[...Ae.filter(fp),je,...Array.isArray(ke(i,z))?[{}]:[]],ref:{type:je.type,name:z}}:{ref:je}}}),X(z,!1,void 0,je)}else W=ke(r,z,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||Y.shouldUnregister)&&!(e8(f.array,z)&&u.action)&&f.unMount.add(z)}}},sn=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Ul(r,we,f.mount),Ct=z=>{tr(z)&&(E.state.next({disabled:z}),Ul(r,(Y,W)=>{const de=ke(r,W);de&&(Y.disabled=de._f.disabled||z,Array.isArray(de._f.refs)&&de._f.refs.forEach(me=>{me.disabled=de._f.disabled||z}))},0,!1))},Lt=(z,Y)=>async W=>{let de;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let me=Gt(l);if(E.state.next({isSubmitting:!0}),t.resolver){const{errors:xe,values:je}=await le();A(),n.errors=xe,me=Gt(je)}else await q({fields:r,eventType:mo.SUBMIT});if(f.disabled.size)for(const xe of f.disabled)Kt(me,xe);if(Kt(n.errors,DE),xn(n.errors)){E.state.next({errors:{}});try{await z(me,W)}catch(xe){de=xe}}else Y&&await Y({...n.errors},W),sn(),setTimeout(sn);if(E.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:xn(n.errors)&&!de,submitCount:n.submitCount+1,errors:n.errors}),de)throw de},ts=(z,Y={})=>{ke(r,z)&&(Mt(Y.defaultValue)?I(z,Gt(ke(i,z))):(I(z,Y.defaultValue),wt(i,z,Gt(Y.defaultValue))),Y.keepTouched||Kt(n.touchedFields,z),Y.keepDirty||(Kt(n.dirtyFields,z),n.isDirty=Y.defaultValue?ee(z,Gt(ke(i,z))):ee()),Y.keepError||(Kt(n.errors,z),j.isValid&&T()),E.state.next({...n}))},At=(z,Y={})=>{const W=z?Gt(z):i,de=Gt(W),me=xn(z),xe=de,je=r;if(Y.keepDefaultValues||(i=W),!Y.keepValues){if(Y.keepDirtyValues){const _e=new Set([...f.mount,...Object.keys(ri(i,l,void 0,je))]);for(const Ae of Array.from(_e)){const Ke=ke(n.dirtyFields,Ae),_t=ke(l,Ae),an=ke(xe,Ae);Ke&&!Mt(_t)?wt(xe,Ae,_t):!Ke&&!Mt(an)&&I(Ae,an)}}else{if(gf&&Mt(z))for(const _e of f.mount){const Ae=ke(r,_e);if(Ae&&Ae._f){const Ke=Array.isArray(Ae._f.refs)?Ae._f.refs[0]:Ae._f.ref;if(kd(Ke)){const _t=Ke.closest("form");if(_t){_t.reset();break}}}}if(Y.keepFieldsRef)for(const _e of f.mount)I(_e,ke(xe,_e));else r={}}if(t.shouldUnregister){if(l=Y.keepDefaultValues?Gt(i):{},Y.keepFieldsRef)for(const _e of f.mount)wt(l,_e,ke(xe,_e))}else l=Gt(xe);E.array.next({values:{...xe}}),E.state.next({name:void 0,type:void 0,values:{...xe}})}f={mount:Y.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!j.isValid||!!Y.keepIsValid||!!Y.keepDirtyValues||!t.shouldUnregister&&!xn(xe),u.watch=!!t.shouldUnregister,u.keepIsValid=!!Y.keepIsValid,u.action=!1,Y.keepErrors||(n.errors={}),E.state.next({submitCount:Y.keepSubmitCount?n.submitCount:0,isDirty:me?!1:Y.keepDirty?n.isDirty:Y.keepValues?ee():!!(Y.keepDefaultValues&&!nr(z,i)),isSubmitted:Y.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:me?{}:Y.keepDirtyValues?Y.keepDefaultValues&&l?ri(i,l,void 0,je):n.dirtyFields:Y.keepDefaultValues&&z?ri(i,z,void 0,je):Y.keepDirty?n.dirtyFields:{},touchedFields:Y.keepTouched?n.touchedFields:{},errors:Y.keepErrors?n.errors:{},isSubmitSuccessful:Y.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},rn=(z,Y)=>At(Ns(z)?z(l):z,{...t.resetOptions,...Y}),ns=(z,Y={})=>{const W=ke(r,z),de=W&&W._f;if(de){const me=de.refs?de.refs[0]:de.ref;me.focus&&setTimeout(()=>{me.focus(),Y.shouldSelect&&Ns(me.select)&&me.select()})}},hr=z=>{const{name:Y,type:W,values:de,...me}=z;n={...n,...me}},Tn={control:{register:jt,unregister:ot,getFieldState:Me,handleSubmit:Lt,setError:ht,_subscribe:es,_runSchema:le,_updateIsValidating:A,_focusError:sn,_getWatch:K,_getDirty:ee,_setValid:T,_setFieldArray:L,_setDisabledField:Yt,_setErrors:U,_getFieldArray:O,_reset:At,_resetDefaultValues:()=>Ns(t.defaultValues)&&t.defaultValues().then(z=>{rn(z,t.resetOptions),E.state.next({isLoading:!1})}),_removeUnmounted:V,_disableForm:Ct,_subjects:E,_proxyFormState:j,get _fields(){return r},get _formValues(){return l},get _state(){return u},set _state(z){u=z},get _defaultValues(){return i},get _names(){return f},set _names(z){f=z},get _formState(){return n},get _options(){return t},set _options(z){t={...t,...z},g=Ku(t.mode),w=Ku(t.reValidateMode)}},subscribe:Fe,trigger:Se,register:jt,handleSubmit:Lt,watch:tt,setValue:I,setValues:re,getValues:ve,reset:rn,resetField:ts,resetDefaultValues:(z,Y={})=>{if(i=Gt(z),!Y.keepDirty){const W=ri(i,l,void 0,r);n.dirtyFields=W,n.isDirty=!xn(W)}Y.keepIsValid||T(),E.state.next({...n,defaultValues:i})},clearErrors:Ye,unregister:ot,setError:ht,setFocus:ns,getFieldState:Me};return{...Tn,formControl:Tn}}function Vv(e={}){const t=ye.useRef(void 0),n=ye.useRef(void 0),r=ye.useRef(e.formControl),[i,l]=ye.useState(()=>({...Gt(BE),isLoading:Ns(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:Ns(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl)if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!Ns(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:f,...h}=b8(e);t.current={...h,formState:i}}const u=t.current.control;return u._options=e,a8(()=>{const f=u._subscribe({formState:u._proxyFormState,callback:()=>l({...u._formState,defaultValues:u._defaultValues}),reRenderRoot:!0});return l(h=>({...h,isReady:!0})),u._formState.isReady=!0,f},[u]),ye.useEffect(()=>u._disableForm(e.disabled),[u,e.disabled]),ye.useEffect(()=>{e.mode&&(u._options.mode=e.mode),e.reValidateMode&&(u._options.reValidateMode=e.reValidateMode)},[u,e.mode,e.reValidateMode]),ye.useEffect(()=>{e.errors&&(u._setErrors(e.errors),u._focusError())},[u,e.errors]),ye.useEffect(()=>{e.shouldUnregister&&u._subjects.state.next({values:u._getWatch()})},[u,e.shouldUnregister]),ye.useEffect(()=>{if(u._proxyFormState.isDirty){const f=u._getDirty();f!==i.isDirty&&u._subjects.state.next({isDirty:f})}},[u,i.isDirty]),ye.useEffect(()=>{var f;e.values&&!nr(e.values,n.current)?(u._reset(e.values,{keepFieldsRef:!0,...u._options.resetOptions}),!((f=u._options.resetOptions)===null||f===void 0)&&f.keepIsValid||u._setValid(),n.current=e.values,l(h=>({...h}))):u._resetDefaultValues()},[u,e.values]),ye.useEffect(()=>{u._state.mount||(u._setValid(),u._state.mount=!0),u._state.watch&&(u._state.watch=!1,u._subjects.state.next({...u._formState})),u._removeUnmounted()}),t.current.formState=ye.useMemo(()=>r8(i,u),[u,i]),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ke(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},ug=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r&&r.refs&&r.refs.forEach(i=>S1(i,n,e))}},j1=(e,t)=>{t.shouldUseNativeValidation&&ug(e,t);const n={};for(const r in e){const i=ke(t.fields,r),l=Object.assign(e[r]||{},{ref:i&&i.ref});if(w8(t.names||Object.keys(e),r)){const u=Object.assign({},ke(n,r));wt(u,"root",l),wt(n,r,u)}else wt(n,r,l)}return n},w8=(e,t)=>{const n=C1(t).replace(/[.*+?^${}()|\\]/g,"\\$&");return e.some(r=>C1(r).match(`^${n}\\.\\d+`))};function C1(e){return e.replace(/[\[\]]/g,"")}var _1;function pe(e,t,n){function r(f,h){if(f._zod||Object.defineProperty(f,"_zod",{value:{def:h,constr:u,traits:new Set},enumerable:!1}),f._zod.traits.has(e))return;f._zod.traits.add(e),t(f,h);const m=u.prototype,y=Object.keys(m);for(let g=0;gn?.Parent&&f instanceof n.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class _o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GE extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(_1=globalThis).__zod_globalConfig??(_1.__zod_globalConfig={});const Hv=globalThis.__zod_globalConfig;function gi(e){return Hv}function KE(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function dg(e,t){return typeof t=="bigint"?t.toString():t}function qv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Bv(e){return e==null}function Gv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const E1=Symbol("evaluating");function St(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E1)return r===void 0&&(r=E1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ma(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function N1(e){return JSON.stringify(e)}function S8(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ZE="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j8=qv(()=>{if(Hv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Jl(e){if(Md(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Md(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YE(e){return Jl(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const C8=new Set(["string","number","symbol"]);function yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function qe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function E8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&(u[f]=n.shape[f])}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function N8(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const l=Ma(e._zod.def,{get shape(){const u={...e._zod.def.shape};for(const f in t){if(!(f in n.shape))throw new Error(`Unrecognized key: "${f}"`);t[f]&&delete u[f]}return ji(this,"shape",u),u},checks:[]});return Ta(e,l)}function k8(e,t){if(!Jl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const l=e._zod.def.shape;for(const u in t)if(Object.getOwnPropertyDescriptor(l,u)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ma(e._zod.def,{get shape(){const l={...e._zod.def.shape,...t};return ji(this,"shape",l),l}});return Ta(e,i)}function R8(e,t){if(!Jl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ji(this,"shape",r),r}});return Ta(e,n)}function M8(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ma(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ta(e,n)}function T8(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const u=Ma(t._zod.def,{get shape(){const f=t._zod.def.shape,h={...f};if(n)for(const m in n){if(!(m in f))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(h[m]=e?new e({type:"optional",innerType:f[m]}):f[m])}else for(const m in f)h[m]=e?new e({type:"optional",innerType:f[m]}):f[m];return ji(this,"shape",h),h},checks:[]});return Ta(t,u)}function O8(e,t,n){const r=Ma(t._zod.def,{get shape(){const i=t._zod.def.shape,l={...i};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(l[u]=new e({type:"nonoptional",innerType:i[u]}))}else for(const u in i)l[u]=new e({type:"nonoptional",innerType:i[u]});return ji(this,"shape",l),l}});return Ta(t,r)}function wo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Zu(e){return typeof e=="string"?e:e?.message}function vi(e,t,n){const r=e.message?e.message:Zu(e.inst?._zod.def?.error?.(e))??Zu(t?.error?.(e))??Zu(n.customError?.(e))??Zu(n.localeError?.(e))??"Invalid input",{inst:i,continue:l,input:u,...f}=e;return f.path??(f.path=[]),f.message=r,t?.reportInput&&(f.input=u),f}function Kv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ec(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const XE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zv=pe("$ZodError",XE),xf=pe("$ZodError",XE,{Parent:Error});function D8(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function z8(e,t=n=>n.message){const n={_errors:[]},r=(i,l=[])=>{for(const u of i.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(f=>r({issues:f},[...l,...u.path]));else if(u.code==="invalid_key")r({issues:u.issues},[...l,...u.path]);else if(u.code==="invalid_element")r({issues:u.issues},[...l,...u.path]);else{const f=[...l,...u.path];if(f.length===0)n._errors.push(t(u));else{let h=n,m=0;for(;m(t,n,r,i)=>{const l=r?{...r,async:!1}:{async:!1},u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise)throw new _o;if(u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},L8=bf(xf),wf=e=>async(t,n,r,i)=>{const l=r?{...r,async:!0}:{async:!0};let u=t._zod.run({value:n,issues:[]},l);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new(i?.Err??e)(u.issues.map(h=>vi(h,l,gi())));throw ZE(f,i?.callee),f}return u.value},$8=wf(xf),Sf=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new _o;return l.issues.length?{success:!1,error:new(e??Zv)(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},F8=Sf(xf),jf=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);return l instanceof Promise&&(l=await l),l.issues.length?{success:!1,error:new e(l.issues.map(u=>vi(u,i,gi())))}:{success:!0,data:l.value}},I8=jf(xf),P8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,i)},U8=e=>(t,n,r)=>bf(e)(t,n,r),V8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return wf(e)(t,n,i)},H8=e=>async(t,n,r)=>wf(e)(t,n,r),q8=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Sf(e)(t,n,i)},B8=e=>(t,n,r)=>Sf(e)(t,n,r),G8=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jf(e)(t,n,i)},K8=e=>async(t,n,r)=>jf(e)(t,n,r),Z8=/^[cC][0-9a-z]{6,}$/,Y8=/^[0-9a-z]+$/,Q8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,X8=/^[0-9a-vA-V]{20}$/,W8=/^[A-Za-z0-9]{27}$/,J8=/^[a-zA-Z0-9_-]{21}$/,eF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function rF(){return new RegExp(sF,"u")}const aF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cF=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,WE=/^[A-Za-z0-9_-]*$/,uF=/^https?$/,dF=/^\+[1-9]\d{6,14}$/,JE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fF=new RegExp(`^${JE}$`);function e2(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hF(e){return new RegExp(`^${e2(e)}$`)}function mF(e){const t=e2({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${JE}T(?:${r})$`)}const pF=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gF=/^(?:true|false)$/i,vF=/^[^A-Z]*$/,yF=/^[^a-z]*$/,fr=pe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xF=pe("$ZodCheckMaxLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const i=r.value;if(i.length<=t.maximum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),bF=pe("$ZodCheckMinLength",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const u=Kv(i);r.issues.push({origin:u,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wF=pe("$ZodCheckLengthEquals",(e,t)=>{var n;fr.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Bv(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,l=i.length;if(l===t.length)return;const u=Kv(i),f=l>t.length;r.issues.push({origin:u,...f?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cf=pe("$ZodCheckStringFormat",(e,t)=>{var n,r;fr.init(e,t),e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,t.pattern&&(l.patterns??(l.patterns=new Set),l.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),SF=pe("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jF=pe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vF),Cf.init(e,t)}),CF=pe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yF),Cf.init(e,t)}),_F=pe("$ZodCheckIncludes",(e,t)=>{fr.init(e,t);const n=yf(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const l=i._zod.bag;l.patterns??(l.patterns=new Set),l.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),EF=pe("$ZodCheckStartsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`^${yf(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),NF=pe("$ZodCheckEndsWith",(e,t)=>{fr.init(e,t);const n=new RegExp(`.*${yf(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kF=pe("$ZodCheckOverwrite",(e,t)=>{fr.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class RF{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
 `).filter(u=>u),i=Math.min(...r.map(u=>u.length-u.trimStart().length)),l=r.map(u=>u.slice(i)).map(u=>" ".repeat(this.indent*2)+u);for(const u of l)this.content.push(u)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(l=>`  ${l}`)];return new t(...n,i.join(`
 `))}}const MF={major:4,minor:4,patch:3},tn=pe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=MF;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const l of i._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(u,f,h)=>{let m=wo(u),y;for(const g of f){if(g._zod.def.when){if(A8(u)||!g._zod.def.when(u))continue}else if(m)continue;const w=u.issues.length,x=g._zod.check(u);if(x instanceof Promise&&h?.async===!1)throw new _o;if(y||x instanceof Promise)y=(y??Promise.resolve()).then(async()=>{await x,u.issues.length!==w&&(m||(m=wo(u,w)))});else{if(u.issues.length===w)continue;m||(m=wo(u,w))}}return y?y.then(()=>u):u},l=(u,f,h)=>{if(wo(u))return u.aborted=!0,u;const m=i(f,r,h);if(m instanceof Promise){if(h.async===!1)throw new _o;return m.then(y=>e._zod.parse(y,h))}return e._zod.parse(m,h)};e._zod.run=(u,f)=>{if(f.skipChecks)return e._zod.parse(u,f);if(f.direction==="backward"){const m=e._zod.parse({value:u.value,issues:[]},{...f,skipChecks:!0});return m instanceof Promise?m.then(y=>l(y,u,f)):l(m,u,f)}const h=e._zod.parse(u,f);if(h instanceof Promise){if(f.async===!1)throw new _o;return h.then(m=>i(m,r,f))}return i(h,r,f)}}St(e,"~standard",()=>({validate:i=>{try{const l=F8(e,i);return l.success?{value:l.data}:{issues:l.error?.issues}}catch{return I8(e,i).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}))}),Yv=pe("$ZodString",(e,t)=>{tn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pF(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ot=pe("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Yv.init(e,t)}),TF=pe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tF),Ot.init(e,t)}),OF=pe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=k1(r))}else t.pattern??(t.pattern=k1());Ot.init(e,t)}),AF=pe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nF),Ot.init(e,t)}),DF=pe("$ZodURL",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===uF.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),zF=pe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rF()),Ot.init(e,t)}),LF=pe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=J8),Ot.init(e,t)}),$F=pe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Z8),Ot.init(e,t)}),FF=pe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Y8),Ot.init(e,t)}),IF=pe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Q8),Ot.init(e,t)}),PF=pe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=X8),Ot.init(e,t)}),UF=pe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W8),Ot.init(e,t)}),VF=pe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mF(t)),Ot.init(e,t)}),HF=pe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fF),Ot.init(e,t)}),qF=pe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hF(t)),Ot.init(e,t)}),BF=pe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eF),Ot.init(e,t)}),GF=pe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aF),Ot.init(e,t),e._zod.bag.format="ipv4"}),KF=pe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=iF),Ot.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ZF=pe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oF),Ot.init(e,t)}),YF=pe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lF),Ot.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,l]=r;if(!l)throw new Error;const u=Number(l);if(`${u}`!==l)throw new Error;if(u<0||u>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function t2(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const QF=pe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cF),Ot.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{t2(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function XF(e){if(!WE.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return t2(n)}const WF=pe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=WE),Ot.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{XF(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JF=pe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dF),Ot.init(e,t)});function eI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const tI=pe("$ZodJWT",(e,t)=>{Ot.init(e,t),e._zod.check=n=>{eI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),nI=pe("$ZodBoolean",(e,t)=>{tn.init(e,t),e._zod.pattern=gF,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),sI=pe("$ZodUnknown",(e,t)=>{tn.init(e,t),e._zod.parse=n=>n}),rI=pe("$ZodNever",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function R1(e,t,n){e.issues.length&&t.issues.push(...QE(n,e.issues)),t.value[n]=e.value}const aI=pe("$ZodArray",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const l=[];for(let u=0;uR1(m,n,u))):R1(h,n,u)}return l.length?Promise.all(l).then(()=>n):n}});function Td(e,t,n,r,i,l){const u=n in r;if(e.issues.length){if(i&&l&&!u)return;t.issues.push(...QE(n,e.issues))}if(!u&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?u&&(t.value[n]=void 0):t.value[n]=e.value}function n2(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_8(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s2(e,t,n,r,i,l){const u=[],f=i.keySet,h=i.catchall._zod,m=h.def.type,y=h.optin==="optional",g=h.optout==="optional";for(const w in t){if(w==="__proto__"||f.has(w))continue;if(m==="never"){u.push(w);continue}const x=h.run({value:t[w],issues:[]},r);x instanceof Promise?e.push(x.then(j=>Td(j,n,w,t,y,g))):Td(x,n,w,t,y,g)}return u.length&&n.issues.push({code:"unrecognized_keys",keys:u,input:t,inst:l}),e.length?Promise.all(e).then(()=>n):n}const iI=pe("$ZodObject",(e,t)=>{if(tn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const f=t.shape;Object.defineProperty(t,"shape",{get:()=>{const h={...f};return Object.defineProperty(t,"shape",{value:h}),h}})}const r=qv(()=>n2(t));St(e._zod,"propValues",()=>{const f=t.shape,h={};for(const m in f){const y=f[m]._zod;if(y.values){h[m]??(h[m]=new Set);for(const g of y.values)h[m].add(g)}}return h});const i=Md,l=t.catchall;let u;e._zod.parse=(f,h)=>{u??(u=r.value);const m=f.value;if(!i(m))return f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f;f.value={};const y=[],g=u.shape;for(const w of u.keys){const x=g[w],j=x._zod.optin==="optional",S=x._zod.optout==="optional",E=x._zod.run({value:m[w],issues:[]},h);E instanceof Promise?y.push(E.then(_=>Td(_,f,w,m,j,S))):Td(E,f,w,m,j,S)}return l?s2(y,m,f,h,r.value,e):y.length?Promise.all(y).then(()=>f):f}}),oI=pe("$ZodObjectJIT",(e,t)=>{iI.init(e,t);const n=e._zod.parse,r=qv(()=>n2(t)),i=w=>{const x=new RF(["shape","payload","ctx"]),j=r.value,S=R=>{const T=N1(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let _=0;for(const R of j.keys)E[R]=`key_${_++}`;x.write("const newResult = {};");for(const R of j.keys){const T=E[R],A=N1(R),M=w[R],L=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";x.write(`const ${T} = ${S(R)};`),L&&H?x.write(`
         if (${T}.issues.length) {
@@ -113,7 +113,7 @@ Error generating stack: `+d.message+`
 
       `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(R,T)=>N(w,R,T)};let l;const u=Md,f=!Hv.jitless,m=f&&j8.value,y=t.catchall;let g;e._zod.parse=(w,x)=>{g??(g=r.value);const j=w.value;return u(j)?f&&m&&x?.async===!1&&x.jitless!==!0?(l||(l=i(t.shape)),w=l(w,x),y?s2([],j,w,x,g,e):w):n(w,x):(w.issues.push({expected:"object",code:"invalid_type",input:j,inst:e}),w)}});function M1(e,t,n,r){for(const l of e)if(l.issues.length===0)return t.value=l.value,t;const i=e.filter(l=>!wo(l));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(l=>l.issues.map(u=>vi(u,r,gi())))}),t)}const lI=pe("$ZodUnion",(e,t)=>{tn.init(e,t),St(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),St(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),St(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),St(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Gv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let l=!1;const u=[];for(const f of t.options){const h=f._zod.run({value:r.value,issues:[]},i);if(h instanceof Promise)u.push(h),l=!0;else{if(h.issues.length===0)return h;u.push(h)}}return l?Promise.all(u).then(f=>M1(f,r,e,i)):M1(u,r,e,i)}}),cI=pe("$ZodIntersection",(e,t)=>{tn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,l=t.left._zod.run({value:i,issues:[]},r),u=t.right._zod.run({value:i,issues:[]},r);return l instanceof Promise||u instanceof Promise?Promise.all([l,u]).then(([h,m])=>T1(n,h,m)):T1(n,l,u)}});function fg(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Jl(e)&&Jl(t)){const n=Object.keys(t),r=Object.keys(e).filter(l=>n.indexOf(l)!==-1),i={...e,...t};for(const l of r){const u=fg(e[l],t[l]);if(!u.valid)return{valid:!1,mergeErrorPath:[l,...u.mergeErrorPath]};i[l]=u.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;rf.l&&f.r).map(([f])=>f);if(l.length&&i&&e.issues.push({...i,keys:l}),wo(e))return e;const u=fg(t.value,n.value);if(!u.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`);return e.value=u.data,e}const uI=pe("$ZodEnum",(e,t)=>{tn.init(e,t);const n=KE(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>C8.has(typeof i)).map(i=>typeof i=="string"?yf(i):i.toString()).join("|")})$`),e._zod.parse=(i,l)=>{const u=i.value;return r.has(u)||i.issues.push({code:"invalid_value",values:n,input:u,inst:e}),i}}),dI=pe("$ZodTransform",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(u=>(n.value=u,n.fallback=!0,n));if(i instanceof Promise)throw new _o;return n.value=i,n.fallback=!0,n}});function O1(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const r2=pe("$ZodOptional",(e,t)=>{tn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,l=t.innerType._zod.run(n,r);return l instanceof Promise?l.then(u=>O1(u,i)):O1(l,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),fI=pe("$ZodExactOptional",(e,t)=>{r2.init(e,t),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hI=pe("$ZodNullable",(e,t)=>{tn.init(e,t),St(e._zod,"optin",()=>t.innerType._zod.optin),St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Gv(n.source)}|null)$`):void 0}),St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),mI=pe("$ZodDefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>A1(l,t)):A1(i,t)}});function A1(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const pI=pe("$ZodPrefault",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gI=pe("$ZodNonOptional",(e,t)=>{tn.init(e,t),St(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>D1(l,e)):D1(i,e)}});function D1(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vI=pe("$ZodCatch",(e,t)=>{tn.init(e,t),e._zod.optin="optional",St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>(n.value=l.value,l.issues.length&&(n.value=t.catchValue({...n,error:{issues:l.issues.map(u=>vi(u,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>vi(l,r,gi()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),yI=pe("$ZodPipe",(e,t)=>{tn.init(e,t),St(e._zod,"values",()=>t.in._zod.values),St(e._zod,"optin",()=>t.in._zod.optin),St(e._zod,"optout",()=>t.out._zod.optout),St(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const l=t.out._zod.run(n,r);return l instanceof Promise?l.then(u=>Yu(u,t.in,r)):Yu(l,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(l=>Yu(l,t.out,r)):Yu(i,t.out,r)}});function Yu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const xI=pe("$ZodReadonly",(e,t)=>{tn.init(e,t),St(e._zod,"propValues",()=>t.innerType._zod.propValues),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"optin",()=>t.innerType?._zod?.optin),St(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(z1):z1(i)}});function z1(e){return e.value=Object.freeze(e.value),e}const bI=pe("$ZodCustom",(e,t)=>{fr.init(e,t),tn.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(l=>L1(l,n,r,e));L1(i,n,r,e)}});function L1(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(ec(i))}}var $1;class wI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function SI(){return new wI}($1=globalThis).__zod_globalRegistry??($1.__zod_globalRegistry=SI());const Fl=globalThis.__zod_globalRegistry;function jI(e,t){return new e({type:"string",...qe(t)})}function CI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function F1(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function _I(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function EI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function NI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function kI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function RI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function MI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function TI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function OI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function AI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function DI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function zI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function LI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function $I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function FI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function PI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function UI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function VI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function HI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function qI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function BI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function GI(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function KI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function ZI(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function YI(e,t){return new e({type:"boolean",...qe(t)})}function QI(e){return new e({type:"unknown"})}function XI(e,t){return new e({type:"never",...qe(t)})}function a2(e,t){return new xF({check:"max_length",...qe(t),maximum:e})}function Od(e,t){return new bF({check:"min_length",...qe(t),minimum:e})}function i2(e,t){return new wF({check:"length_equals",...qe(t),length:e})}function WI(e,t){return new SF({check:"string_format",format:"regex",...qe(t),pattern:e})}function JI(e){return new jF({check:"string_format",format:"lowercase",...qe(e)})}function eP(e){return new CF({check:"string_format",format:"uppercase",...qe(e)})}function tP(e,t){return new _F({check:"string_format",format:"includes",...qe(t),includes:e})}function nP(e,t){return new EF({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function sP(e,t){return new NF({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Lo(e){return new kF({check:"overwrite",tx:e})}function rP(e){return Lo(t=>t.normalize(e))}function aP(){return Lo(e=>e.trim())}function iP(){return Lo(e=>e.toLowerCase())}function oP(){return Lo(e=>e.toUpperCase())}function lP(){return Lo(e=>S8(e))}function cP(e,t,n){return new e({type:"array",element:t,...qe(n)})}function uP(e,t,n){return new e({type:"custom",check:"custom",fn:t,...qe(n)})}function dP(e,t){const n=fP(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(ec(i,r.value,n._zod.def));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=n),l.continue??(l.continue=!n._zod.def.abort),r.issues.push(ec(l))}},e(r.value,r)),t);return n}function fP(e,t){const n=new fr({check:"custom",...qe(t)});return n._zod.check=e,n}function o2(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Fl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,l=t.seen.get(e);if(l)return l.count++,n.schemaPath.includes(e)&&(l.cycle=n.path),l.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,u);const f=e._zod.toJSONSchema?.();if(f)u.schema=f;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,u.schema,y);else{const w=u.schema,x=t.processors[i.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);x(e,t,w,y)}const g=e._zod.parent;g&&(u.ref||(u.ref=g),jn(g,t,y),t.seen.get(g).isParent=!0)}const h=t.metadataRegistry.get(e);return h&&Object.assign(u.schema,h),t.io==="input"&&Ln(e)&&(delete u.schema.examples,delete u.schema.default),t.io==="input"&&"_prefault"in u.schema&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,t.seen.get(e).schema}function l2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of e.seen.entries()){const f=e.metadataRegistry.get(u[0])?.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const i=u=>{const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(u[0])?.id,w=e.external.uri??(j=>j);if(g)return{ref:w(g)};const x=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=x,{defId:x,ref:`${w("__shared")}#/${f}/${x}`}}if(u[1]===n)return{ref:"#"};const m=`#/${f}/`,y=u[1].schema.id??`__schema${e.counter++}`;return{defId:y,ref:m+y}},l=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:m}=i(u);f.def={...f.schema},m&&(f.defId=m);const y=f.schema;for(const g in y)delete y[g];y.$ref=h};if(e.cycles==="throw")for(const u of e.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/
 
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ln(r.element,n);if(r.type==="set")return Ln(r.valueType,n);if(r.type==="lazy")return Ln(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ln(r.innerType,n);if(r.type==="intersection")return Ln(r.left,n)||Ln(r.right,n);if(r.type==="record"||r.type==="map")return Ln(r.keyType,n)||Ln(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(r.in,n)||Ln(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Ln(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Ln(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Ln(i,n))return!0;return!!(r.rest&&Ln(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Ad=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function hg(){return hg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(hg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Uv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Qv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Zv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Zv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,dg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,dg,2)}},isEmpty:{get(){return e.issues.length===0}}})},Os=pe("ZodError",HP,{Parent:Error}),qP=bf(Os),BP=wf(Os),GP=Sf(Os),KP=jf(Os),ZP=P8(Os),YP=U8(Os),QP=V8(Os),XP=H8(Os),WP=q8(Os),JP=B8(Os),e9=G8(Os),t9=K8(Os),P1=new WeakMap;function _f(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const nn=pe("ZodType",(e,t)=>(tn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),_f(e,"ZodType",{check(...n){const r=this.def;return this.clone(Ma(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ta(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Lo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Fl.add(r,{description:n}),r},meta(...n){if(n.length===0)return Fl.get(this);const r=this.clone();return Fl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Fl.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Yv.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_f(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Od(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Od(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Yv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Qu,n)),e.uuidv4=n=>e.check(EI(Qu,n)),e.uuidv6=n=>e.check(NI(Qu,n)),e.uuidv7=n=>e.check(kI(Qu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function dd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Qu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,_f(e,"ZodArray",{min(n,r){return this.check(Od(n,r))},nonempty(n){return this.check(Od(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),St(e,"shape",()=>t.shape),_f(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Xv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const mg=pe("ZodEnum",(e,t)=>{uI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new mg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(ec(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(ec(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:at("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:at("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:at("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:at("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:at("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:at("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ig(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ig(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ig(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Pn($n(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Mn(g.row.original.url).then(w=>Ne(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await en("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const nU=Xv({name:dd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Vv({resolver:Qv(nU),values:{name:e.name}}),{data:m}=rt({queryKey:["invites",e.id],queryFn:()=>We(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=rt({queryKey:["orgShares",e.id],queryFn:()=>We(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await en("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await Mn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Mn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await en("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=rt({queryKey:["apps",e.id],queryFn:()=>We(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Mn(u),await Wl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Wl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Mn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>en("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>en("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await en("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await en("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(w){Ne(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Xv({require_verification:V1(),require_approval:V1()});function oU(){const e=mn(),{data:t,error:n}=rt({queryKey:["admin","policy"],queryFn:()=>We("/api/admin/policy")}),{data:r}=pE(!0),i=Vv({resolver:Qv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:at("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rs({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:at("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ms({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:at("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:at("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:at("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=mn(),n=rt({queryKey:["mcp","grants"],queryFn:()=>We("/api/mcp/grants")}),r=FM({mutationFn:u=>en("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(ks,{children:o.jsxs(Rs,{children:[o.jsx(Ms,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(ks,{className:"mcp-grant",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Jv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function ey({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:at("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Es({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:at("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function pg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const Dd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ty(e){try{return localStorage.getItem(e)}catch{return null}}function pc(e,t){try{localStorage.setItem(e,t)}catch{}}const gg=new Set;function ny(){for(const e of gg)e()}function sy(e){return gg.add(e),()=>{gg.delete(e)}}const zd=new Map;function hU(e){let t=zd.get(e);if(t===void 0){const n=Number(ty(Dd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),zd.set(e,t),n>0||pc(Dd(e),String(t))}return t}function mU(e){pc(Dd(e),String(Date.now())),zd.delete(e)}function pU(e){const t=Date.now();zd.set(e,t),pc(Dd(e),String(t)),ny()}function ry(e){return b.useSyncExternalStore(sy,()=>e?hU(e):0)}const vg=new Map,gU=[];function ay(e){let t=vg.get(e);if(!t){try{const n=JSON.parse(ty(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}vg.set(e,t)}return t}function W1(e,t){const n=ay(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];vg.set(e,r),pc(b2(e),JSON.stringify(r)),ny()}function vU(e){return b.useSyncExternalStore(sy,()=>e?ay(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(sy,()=>ty(w2)==="recent"?"recent":"name")}function xU(e){pc(w2,e),ny()}function fd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Xu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ir="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=mp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=mp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=mp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function iy(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function oy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=iy(t);return!e||n===null||!C2(Ps(e),n)?"":`stale · last changed ${oy(n)}`}function E2(e,t=!0){const n=rt({queryKey:["tree",e],queryFn:()=>We(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return rt({queryKey:["heat",e],queryFn:()=>We(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return rt({queryKey:["history",e,"prefix",t,20],queryFn:()=>We(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",Ld=100;function T2(e,t=!0){const n=ry(e),r=e?M2(e):"";return rt({queryKey:["history",r,"since",n],queryFn:()=>We(r+"history?n="+Ld+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=rt({queryKey:["heatDevices",n],queryFn:()=>We(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=rt({queryKey:["comments",e,"open-all"],queryFn:()=>We(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function vo(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},hd=0,A2=null;const yg=new Set;function Ef(e){ur=e;for(const t of yg)t()}function ly(){return b.useSyncExternalStore(e=>(yg.add(e),()=>yg.delete(e)),()=>ur)}function D2(e){e!==ur.query&&Ef({query:e,sel:0})}function xg(){D2("")}function DU(e,t){hd=e,A2=t,ur.sel>=e&&Ef({...ur,sel:Math.max(0,e-1)})}function zU(e){hd!==0&&Ef({...ur,sel:(ur.sel+e+hd)%hd})}function J1(e){e!==ur.sel&&Ef({...ur,sel:e})}function LU(){A2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function gc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],$d=e=>e>=Ld?Ld-1+"+":String(e);function pp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?gc(l.name):void 0,children:o.jsx(ci,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${$d(u)} changes since your last visit`,children:$d(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=Ev(),w=r?.org??null,x=w?Pn(w.manage_url):null,j=r?.billing?Pn(r.billing.url):null,S=Pn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Wv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Jv,{asChild:!0,children:l}),o.jsxs(ey,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Es,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),fs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(_.name),children:o.jsx(ci,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Es,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(pg,{}),n&&t&&o.jsxs(Es,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Es,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(pg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Es,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+vo(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(cf,{delayDuration:300,children:[o.jsx(uf,{asChild:!0,children:f}),o.jsx(df,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=ly();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),Co(),fs())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?Co(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?xg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:xg,children:"esc"}):o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{Co(),fs()},children:Xl?"⌘K":"Ctrl K"})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Xl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(Cv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?$d(n)+" new":void 0,badge:r==="activity"&&n?$d(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.current.name),children:o.jsx(ci,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Lr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:at("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=rt({queryKey:["billing"],queryFn:()=>We(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsxs(Ms,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function md({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:at("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function gp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:at("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:at("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function In(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const bg=280,ZU=Xv({name:dd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:dd().max(bg,`Keep the description under ${bg} characters.`),icon:dd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=In(e.perm,"admin"),l=Vv({resolver:Qv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await en("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){Ne(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!In(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:u})}),o.jsxs(Wv,{children:[o.jsx(Jv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(ey,{align:"start",className:"ps-icon-grid",children:[o.jsx(Es,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ci,{})}),Object.keys(Qp).map(m=>o.jsx(Es,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ci,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-name",children:"Name"}),o.jsx(md,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(gp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",bg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Lr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(ks,{id:"ps-devices",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Pn(cn("install",e.id)),children:"Connect a device"})})})]}),In(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(ks,{children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"About"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(ks,{className:"ps-danger",children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"Danger zone"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Wl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await en("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(ks,{id:"ps-data",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await en("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:In(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const wg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(wg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=mn(),{data:r,error:i}=kv(e.id),l=In(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Wl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>en("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(ks,{className:"ps-people",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await Mn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>en("PUT",m,{default:j}),"Default access updated.")},children:wg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>en("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:wg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>en("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function Nf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const f=u[1];if(t===u[0]){l(u);continue}if(e.external){const m=e.external.registry.get(u[0])?.id;if(t!==u[0]&&m){l(u);continue}}if(e.metadataRegistry.get(u[0])?.id){l(u);continue}if(f.cycle){l(u);continue}if(f.count>1&&e.reused==="ref"){l(u);continue}}}function c2(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=f=>{const h=e.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,y={...m},g=h.ref;if(h.ref=null,g){r(g);const x=e.seen.get(g),j=x.schema;if(j.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(j)):Object.assign(m,j),Object.assign(m,y),f._zod.parent===g)for(const E in m)E==="$ref"||E==="allOf"||E in y||delete m[E];if(j.$ref&&x.def)for(const E in m)E==="$ref"||E==="allOf"||E in x.def&&JSON.stringify(m[E])===JSON.stringify(x.def[E])&&delete m[E]}const w=f._zod.parent;if(w&&w!==g){r(w);const x=e.seen.get(w);if(x?.schema.$ref&&(m.$ref=x.schema.$ref,x.def))for(const j in m)j==="$ref"||j==="allOf"||j in x.def&&JSON.stringify(m[j])===JSON.stringify(x.def[j])&&delete m[j]}e.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...e.seen.entries()].reverse())r(f[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const f=e.external.registry.get(t)?.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(f)}Object.assign(i,n.def??n.schema);const l=e.metadataRegistry.get(t)?.id;l!==void 0&&i.id===l&&delete i.id;const u=e.external?.defs??{};for(const f of e.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,u[h.defId]=h.def)}e.external||Object.keys(u).length>0&&(e.target==="draft-2020-12"?i.$defs=u:i.definitions=u);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ln(r.element,n);if(r.type==="set")return Ln(r.valueType,n);if(r.type==="lazy")return Ln(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Ln(r.innerType,n);if(r.type==="intersection")return Ln(r.left,n)||Ln(r.right,n);if(r.type==="record"||r.type==="map")return Ln(r.keyType,n)||Ln(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(r.in,n)||Ln(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Ln(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Ln(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Ln(i,n))return!0;return!!(r.rest&&Ln(r.rest,n))}return!1}const hP=(e,t={})=>n=>{const r=o2({...n,processors:t});return jn(e,r),l2(r,e),c2(r,e)},Ad=(e,t,n={})=>r=>{const{libraryOptions:i,target:l}=r??{},u=o2({...i??{},target:l,io:t,processors:n});return jn(e,u),l2(u,e),c2(u,e)},mP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pP=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:l,maximum:u,format:f,patterns:h,contentEncoding:m}=e._zod.bag;if(typeof l=="number"&&(i.minLength=l),typeof u=="number"&&(i.maxLength=u),f&&(i.format=mP[f]??f,i.format===""&&delete i.format,f==="time"&&delete i.format),m&&(i.contentEncoding=m),h&&h.size>0){const y=[...h];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},gP=(e,t,n,r)=>{n.type="boolean"},vP=(e,t,n,r)=>{n.not={}},yP=(e,t,n,r)=>{},xP=(e,t,n,r)=>{const i=e._zod.def,l=KE(i.entries);l.every(u=>typeof u=="number")&&(n.type="number"),l.every(u=>typeof u=="string")&&(n.type="string"),n.enum=l},bP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wP=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SP=(e,t,n,r)=>{const i=n,l=e._zod.def,{minimum:u,maximum:f}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof f=="number"&&(i.maxItems=f),i.type="array",i.items=jn(l.element,t,{...r,path:[...r.path,"items"]})},jP=(e,t,n,r)=>{const i=n,l=e._zod.def;i.type="object",i.properties={};const u=l.shape;for(const m in u)i.properties[m]=jn(u[m],t,{...r,path:[...r.path,"properties",m]});const f=new Set(Object.keys(u)),h=new Set([...f].filter(m=>{const y=l.shape[m]._zod;return t.io==="input"?y.optin===void 0:y.optout===void 0}));h.size>0&&(i.required=Array.from(h)),l.catchall?._zod.def.type==="never"?i.additionalProperties=!1:l.catchall?l.catchall&&(i.additionalProperties=jn(l.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},CP=(e,t,n,r)=>{const i=e._zod.def,l=i.inclusive===!1,u=i.options.map((f,h)=>jn(f,t,{...r,path:[...r.path,l?"oneOf":"anyOf",h]}));l?n.oneOf=u:n.anyOf=u},_P=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.left,t,{...r,path:[...r.path,"allOf",0]}),u=jn(i.right,t,{...r,path:[...r.path,"allOf",1]}),f=m=>"allOf"in m&&Object.keys(m).length===1,h=[...f(l)?l.allOf:[l],...f(u)?u.allOf:[u]];n.allOf=h},EP=(e,t,n,r)=>{const i=e._zod.def,l=jn(i.innerType,t,r),u=t.seen.get(e);t.target==="openapi-3.0"?(u.ref=i.innerType,n.nullable=!0):n.anyOf=[l,{type:"null"}]},NP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType},kP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},MP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType;let u;try{u=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=u},TP=(e,t,n,r)=>{const i=e._zod.def,l=i.in._zod.traits.has("$ZodTransform"),u=t.io==="input"?l?i.out:i.in:i.out;jn(u,t,r);const f=t.seen.get(e);f.ref=u},OP=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType,n.readOnly=!0},u2=(e,t,n,r)=>{const i=e._zod.def;jn(i.innerType,t,r);const l=t.seen.get(e);l.ref=i.innerType};function hg(){return hg=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var h=i.errors[0][0];n[f]={message:h.message,type:h.code}}else n[f]={message:u,type:l};if(i.code==="invalid_union"&&i.errors.forEach(function(g){return g.forEach(function(w){return e.push(hg({},w,{path:[].concat(i.path,w.path)}))})}),t){var m=n[f].types,y=m&&m[i.code];n[f]=Uv(f,t,n,l,y?[].concat(y,i.message):i.message)}e.shift()};e.length;)r();return n}function Qv(e,t,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return Array.isArray(f?.issues)})(u))return{values:{},errors:j1(AP(u.errors,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(e))return function(r,i,l){try{return Promise.resolve(I1(function(){return Promise.resolve((n.mode==="sync"?L8:$8)(e,r,t)).then(function(u){return l.shouldUseNativeValidation&&ug({},l),{errors:{},values:n.raw?Object.assign({},r):u}})},function(u){if((function(f){return f instanceof Zv})(u))return{values:{},errors:j1(DP(u.issues,!l.shouldUseNativeValidation&&l.criteriaMode==="all"),l)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const zP=pe("ZodISODateTime",(e,t)=>{VF.init(e,t),zt.init(e,t)});function LP(e){return BI(zP,e)}const $P=pe("ZodISODate",(e,t)=>{HF.init(e,t),zt.init(e,t)});function FP(e){return GI($P,e)}const IP=pe("ZodISOTime",(e,t)=>{qF.init(e,t),zt.init(e,t)});function PP(e){return KI(IP,e)}const UP=pe("ZodISODuration",(e,t)=>{BF.init(e,t),zt.init(e,t)});function VP(e){return ZI(UP,e)}const HP=(e,t)=>{Zv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>z8(e,n)},flatten:{value:n=>D8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,dg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,dg,2)}},isEmpty:{get(){return e.issues.length===0}}})},Os=pe("ZodError",HP,{Parent:Error}),qP=bf(Os),BP=wf(Os),GP=Sf(Os),KP=jf(Os),ZP=P8(Os),YP=U8(Os),QP=V8(Os),XP=H8(Os),WP=q8(Os),JP=B8(Os),e9=G8(Os),t9=K8(Os),P1=new WeakMap;function _f(e,t,n){const r=Object.getPrototypeOf(e);let i=P1.get(r);if(i||(i=new Set,P1.set(r,i)),!i.has(t)){i.add(t);for(const l in n){const u=n[l];Object.defineProperty(r,l,{configurable:!0,enumerable:!1,get(){const f=u.bind(this);return Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f}),f},set(f){Object.defineProperty(this,l,{configurable:!0,writable:!0,enumerable:!0,value:f})}})}}}const nn=pe("ZodType",(e,t)=>(tn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=hP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qP(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GP(e,n,r),e.parseAsync=async(n,r)=>BP(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>KP(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZP(e,n,r),e.decode=(n,r)=>YP(e,n,r),e.encodeAsync=async(n,r)=>QP(e,n,r),e.decodeAsync=async(n,r)=>XP(e,n,r),e.safeEncode=(n,r)=>WP(e,n,r),e.safeDecode=(n,r)=>JP(e,n,r),e.safeEncodeAsync=async(n,r)=>e9(e,n,r),e.safeDecodeAsync=async(n,r)=>t9(e,n,r),_f(e,"ZodType",{check(...n){const r=this.def;return this.clone(Ma(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Ta(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Z9(n,r))},superRefine(n,r){return this.check(Y9(n,r))},overwrite(n){return this.check(Lo(n))},optional(){return q1(this)},exactOptional(){return z9(this)},nullable(){return B1(this)},nullish(){return q1(B1(this))},nonoptional(n){return U9(this,n)},array(){return _9(this)},or(n){return k9([this,n])},and(n){return M9(this,n)},transform(n){return G1(this,A9(n))},default(n){return F9(this,n)},prefault(n){return P9(this,n)},catch(n){return H9(this,n)},pipe(n){return G1(this,n)},readonly(){return G9(this)},describe(n){const r=this.clone();return Fl.add(r,{description:n}),r},meta(...n){if(n.length===0)return Fl.get(this);const r=this.clone();return Fl.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Fl.get(e)?.description},configurable:!0}),e)),d2=pe("_ZodString",(e,t)=>{Yv.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>pP(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_f(e,"_ZodString",{regex(...r){return this.check(WI(...r))},includes(...r){return this.check(tP(...r))},startsWith(...r){return this.check(nP(...r))},endsWith(...r){return this.check(sP(...r))},min(...r){return this.check(Od(...r))},max(...r){return this.check(a2(...r))},length(...r){return this.check(i2(...r))},nonempty(...r){return this.check(Od(1,...r))},lowercase(r){return this.check(JI(r))},uppercase(r){return this.check(eP(r))},trim(){return this.check(aP())},normalize(...r){return this.check(rP(...r))},toLowerCase(){return this.check(iP())},toUpperCase(){return this.check(oP())},slugify(){return this.check(lP())}})}),n9=pe("ZodString",(e,t)=>{Yv.init(e,t),d2.init(e,t),e.email=n=>e.check(CI(s9,n)),e.url=n=>e.check(RI(r9,n)),e.jwt=n=>e.check(qI(x9,n)),e.emoji=n=>e.check(MI(a9,n)),e.guid=n=>e.check(F1(U1,n)),e.uuid=n=>e.check(_I(Qu,n)),e.uuidv4=n=>e.check(EI(Qu,n)),e.uuidv6=n=>e.check(NI(Qu,n)),e.uuidv7=n=>e.check(kI(Qu,n)),e.nanoid=n=>e.check(TI(i9,n)),e.guid=n=>e.check(F1(U1,n)),e.cuid=n=>e.check(OI(o9,n)),e.cuid2=n=>e.check(AI(l9,n)),e.ulid=n=>e.check(DI(c9,n)),e.base64=n=>e.check(UI(g9,n)),e.base64url=n=>e.check(VI(v9,n)),e.xid=n=>e.check(zI(u9,n)),e.ksuid=n=>e.check(LI(d9,n)),e.ipv4=n=>e.check($I(f9,n)),e.ipv6=n=>e.check(FI(h9,n)),e.cidrv4=n=>e.check(II(m9,n)),e.cidrv6=n=>e.check(PI(p9,n)),e.e164=n=>e.check(HI(y9,n)),e.datetime=n=>e.check(LP(n)),e.date=n=>e.check(FP(n)),e.time=n=>e.check(PP(n)),e.duration=n=>e.check(VP(n))});function dd(e){return jI(n9,e)}const zt=pe("ZodStringFormat",(e,t)=>{Ot.init(e,t),d2.init(e,t)}),s9=pe("ZodEmail",(e,t)=>{AF.init(e,t),zt.init(e,t)}),U1=pe("ZodGUID",(e,t)=>{TF.init(e,t),zt.init(e,t)}),Qu=pe("ZodUUID",(e,t)=>{OF.init(e,t),zt.init(e,t)}),r9=pe("ZodURL",(e,t)=>{DF.init(e,t),zt.init(e,t)}),a9=pe("ZodEmoji",(e,t)=>{zF.init(e,t),zt.init(e,t)}),i9=pe("ZodNanoID",(e,t)=>{LF.init(e,t),zt.init(e,t)}),o9=pe("ZodCUID",(e,t)=>{$F.init(e,t),zt.init(e,t)}),l9=pe("ZodCUID2",(e,t)=>{FF.init(e,t),zt.init(e,t)}),c9=pe("ZodULID",(e,t)=>{IF.init(e,t),zt.init(e,t)}),u9=pe("ZodXID",(e,t)=>{PF.init(e,t),zt.init(e,t)}),d9=pe("ZodKSUID",(e,t)=>{UF.init(e,t),zt.init(e,t)}),f9=pe("ZodIPv4",(e,t)=>{GF.init(e,t),zt.init(e,t)}),h9=pe("ZodIPv6",(e,t)=>{KF.init(e,t),zt.init(e,t)}),m9=pe("ZodCIDRv4",(e,t)=>{ZF.init(e,t),zt.init(e,t)}),p9=pe("ZodCIDRv6",(e,t)=>{YF.init(e,t),zt.init(e,t)}),g9=pe("ZodBase64",(e,t)=>{QF.init(e,t),zt.init(e,t)}),v9=pe("ZodBase64URL",(e,t)=>{WF.init(e,t),zt.init(e,t)}),y9=pe("ZodE164",(e,t)=>{JF.init(e,t),zt.init(e,t)}),x9=pe("ZodJWT",(e,t)=>{tI.init(e,t),zt.init(e,t)}),b9=pe("ZodBoolean",(e,t)=>{nI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gP(e,n,r)});function V1(e){return YI(b9,e)}const w9=pe("ZodUnknown",(e,t)=>{sI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yP()});function H1(){return QI(w9)}const S9=pe("ZodNever",(e,t)=>{rI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vP(e,n,r)});function j9(e){return XI(S9,e)}const C9=pe("ZodArray",(e,t)=>{aI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SP(e,n,r,i),e.element=t.element,_f(e,"ZodArray",{min(n,r){return this.check(Od(n,r))},nonempty(n){return this.check(Od(1,n))},max(n,r){return this.check(a2(n,r))},length(n,r){return this.check(i2(n,r))},unwrap(){return this.element}})});function _9(e,t){return cP(C9,e,t)}const E9=pe("ZodObject",(e,t)=>{oI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jP(e,n,r,i),St(e,"shape",()=>t.shape),_f(e,"ZodObject",{keyof(){return T9(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:H1()})},loose(){return this.clone({...this._zod.def,catchall:H1()})},strict(){return this.clone({...this._zod.def,catchall:j9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return k8(this,n)},safeExtend(n){return R8(this,n)},merge(n){return M8(this,n)},pick(n){return E8(this,n)},omit(n){return N8(this,n)},partial(...n){return T8(f2,this,n[0])},required(...n){return O8(h2,this,n[0])}})});function Xv(e,t){const n={type:"object",shape:e??{},...qe(t)};return new E9(n)}const N9=pe("ZodUnion",(e,t)=>{lI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CP(e,n,r,i),e.options=t.options});function k9(e,t){return new N9({type:"union",options:e,...qe(t)})}const R9=pe("ZodIntersection",(e,t)=>{cI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_P(e,n,r,i)});function M9(e,t){return new R9({type:"intersection",left:e,right:t})}const mg=pe("ZodEnum",(e,t)=>{uI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(r,i,l)=>xP(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const l={};for(const u of r)if(n.has(u))l[u]=t.entries[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})},e.exclude=(r,i)=>{const l={...t.entries};for(const u of r)if(n.has(u))delete l[u];else throw new Error(`Key ${u} not found in enum`);return new mg({...t,checks:[],...qe(i),entries:l})}});function T9(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new mg({type:"enum",entries:n,...qe(t)})}const O9=pe("ZodTransform",(e,t)=>{dI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wP(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new GE(e.constructor.name);n.addIssue=l=>{if(typeof l=="string")n.issues.push(ec(l,n.value,t));else{const u=l;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=n.value),u.inst??(u.inst=e),n.issues.push(ec(u))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(l=>(n.value=l,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function A9(e){return new O9({type:"transform",transform:e})}const f2=pe("ZodOptional",(e,t)=>{r2.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new f2({type:"optional",innerType:e})}const D9=pe("ZodExactOptional",(e,t)=>{fI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>u2(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function z9(e){return new D9({type:"optional",innerType:e})}const L9=pe("ZodNullable",(e,t)=>{hI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function B1(e){return new L9({type:"nullable",innerType:e})}const $9=pe("ZodDefault",(e,t)=>{mI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function F9(e,t){return new $9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const I9=pe("ZodPrefault",(e,t)=>{pI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function P9(e,t){return new I9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YE(t)}})}const h2=pe("ZodNonOptional",(e,t)=>{gI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function U9(e,t){return new h2({type:"nonoptional",innerType:e,...qe(t)})}const V9=pe("ZodCatch",(e,t)=>{vI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function H9(e,t){return new V9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const q9=pe("ZodPipe",(e,t)=>{yI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TP(e,n,r,i),e.in=t.in,e.out=t.out});function G1(e,t){return new q9({type:"pipe",in:e,out:t})}const B9=pe("ZodReadonly",(e,t)=>{xI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OP(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function G9(e){return new B9({type:"readonly",innerType:e})}const K9=pe("ZodCustom",(e,t)=>{bI.init(e,t),nn.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bP(e,n)});function Z9(e,t={}){return uP(K9,e,t)}function Y9(e,t){return dP(e,t)}function Q9({className:e,...t}){return o.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:o.jsx("table",{"data-slot":"table",className:at("w-full caption-bottom text-sm",e),...t})})}function X9({className:e,...t}){return o.jsx("thead",{"data-slot":"table-header",className:at("[&_tr]:border-b",e),...t})}function W9({className:e,...t}){return o.jsx("tbody",{"data-slot":"table-body",className:at("[&_tr:last-child]:border-0",e),...t})}function K1({className:e,...t}){return o.jsx("tr",{"data-slot":"table-row",className:at("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",e),...t})}function Z1({className:e,...t}){return o.jsx("th",{"data-slot":"table-head",className:at("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function J9({className:e,...t}){return o.jsx("td",{"data-slot":"table-cell",className:at("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function eU({header:e}){const t=e.column.getIsSorted();return e.column.getCanSort()?o.jsx(Z1,{"data-sort":t||void 0,"aria-sort":t==="asc"?"ascending":t==="desc"?"descending":"none",children:o.jsxs("button",{type:"button",className:"th-sort",onClick:e.column.getToggleSortingHandler(),children:[ig(e.column.columnDef.header,e.getContext()),t==="asc"?" ↑":t==="desc"?" ↓":""]})}):o.jsx(Z1,{children:ig(e.column.columnDef.header,e.getContext())})}function m2({table:e,className:t}){return o.jsx("div",{className:"admin-list admin-card-table"+(t?" "+t:""),children:o.jsxs(Q9,{className:"admin-table",children:[o.jsx(X9,{children:e.getHeaderGroups().map(n=>o.jsx(K1,{children:n.headers.map(r=>o.jsx(eU,{header:r},r.id))},n.id))}),o.jsx(W9,{children:e.getRowModel().rows.map(n=>o.jsx(K1,{className:"admin-item",children:n.getVisibleCells().map(r=>o.jsx(J9,{children:ig(r.column.columnDef.cell,r.getContext())},r.id))},n.id))})]})})}function p2(e){return e?"expires "+new Date(e).toLocaleDateString():"no expiry"}function tU(e){if(e.opens===void 0)return null;if(e.opens===0)return"not opened yet";const t=`${e.opens} open${e.opens===1?"":"s"}`;return e.last_opened?`${t} · last opened ${new Date(e.last_opened).toLocaleDateString()}`:t}function g2(e,t){const n=[];t&&e.project_name&&n.push(e.project_name),e.creator&&n.push("by "+e.creator),e.created&&n.push(new Date(e.created).toLocaleDateString()),n.push(p2(e.expires));const r=tU(e);return r&&n.push(r),n.join(" · ")}const v2="Opens count how many times a file has been read through a public link. Repeat opens from the same browser and network within 10 minutes count once — two people on one network using the same browser still count as one.";function y2({shares:e,onChanged:t,showProject:n=!1,canRevoke:r=!0,empty:i="No public shares.",loading:l=!1}){const[u,f]=b.useState([]),h=b.useMemo(()=>bE(),[]),m=b.useMemo(()=>[h.accessor("path",{header:"Path",cell:g=>o.jsx("a",{className:"ai-main mono",title:g.getValue(),...Pn($n(g.getValue(),g.row.original.project)),children:g.getValue()})}),h.accessor(g=>g2(g,n),{id:"detail",header:n?"Project":"Shared",cell:g=>o.jsx("span",{className:"ai-tag",children:g.getValue()})}),h.display({id:"actions",header:"",cell:g=>o.jsxs("span",{className:"share-acts",children:[o.jsx("button",{className:"ai-btn","aria-label":`Copy the public link to ${g.row.original.path}`,title:"Copy link",onClick:()=>Mn(g.row.original.url).then(w=>Ne(w?"Copied.":"Select and copy the link.")),children:o.jsx(ge,{name:"copy"})}),r&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${g.row.original.path}`,onClick:()=>x2(g.row.original,t),children:"Revoke"})]})})],[h,t,n,r]),y=OE({data:e,columns:m,state:{sorting:u},onSortingChange:f,getCoreRowModel:ME(),getSortedRowModel:TE()});return l?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:"Loading…"})}):e.length===0?o.jsx("div",{className:"admin-list",children:o.jsx("div",{className:"admin-empty",children:i})}):o.jsx(m2,{table:y,className:"shares-table"})}async function x2(e,t){if(await ir("Revoke share link",`Revoke the public link to “${e.path}”? Anyone with the URL will lose access.`,"Revoke",!0))try{await en("DELETE","/api/shares/"+e.token),Ne("Share revoked."),t()}catch(n){Ne(n.message,!0)}}const nU=Xv({name:dd().trim().min(1,"Give the organization a name.").max(60,"Keep it under 60 characters.")});function sU({org:e,projects:t,myEmail:n}){const r=mn(),i=e.role==="owner",l=()=>r.invalidateQueries({queryKey:["orgs"]}),u=()=>r.invalidateQueries({queryKey:["invites",e.id]}),f=()=>r.invalidateQueries({queryKey:["orgShares",e.id]}),h=Vv({resolver:Qv(nU),values:{name:e.name}}),{data:m}=rt({queryKey:["invites",e.id],queryFn:()=>We(`/api/orgs/${e.id}/invites`),enabled:i,select:x=>x.invites||[]}),{data:y,isLoading:g}=rt({queryKey:["orgShares",e.id],queryFn:()=>We(`/api/orgs/${e.id}/shares`),enabled:i,select:x=>x.shares||[]}),w=t.filter(x=>x.org===e.id);return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{id:"org-title",children:e.name}),!i&&o.jsx("p",{className:"role-chip-row",children:o.jsx("span",{className:"ai-tag role-chip",children:"Member"})}),!i&&o.jsx("p",{className:"admin-sub",children:"Only owners can rename this organization, manage members, or issue invite links."}),i&&o.jsxs("form",{className:"admin-row",onSubmit:h.handleSubmit(async({name:x})=>{try{await en("PATCH","/api/orgs/"+e.id,{name:x}),Ne("Renamed."),l()}catch(j){Ne(j.message,!0)}}),children:[o.jsx("label",{className:"admin-lbl",htmlFor:"org-rename",children:"Organization name"}),o.jsx("input",{id:"org-rename",type:"text","aria-invalid":!!h.formState.errors.name,"aria-describedby":h.formState.errors.name?"org-rename-err":void 0,...h.register("name")}),o.jsx(Ie,{variant:"subtle",id:"org-rename-btn",type:"submit",disabled:!h.formState.isDirty,children:"Rename org"}),h.formState.errors.name&&o.jsx("span",{id:"org-rename-err",role:"alert",className:"field-err",children:h.formState.errors.name.message})]}),o.jsx("h3",{children:"Members"}),o.jsx(aU,{org:e,owner:i,myEmail:n,onChanged:l}),o.jsx("h3",{children:"Projects"}),o.jsxs("div",{className:"admin-list",children:[w.length===0&&o.jsx("div",{className:"admin-empty",children:"No projects yet."}),w.map(x=>o.jsx("div",{className:"admin-item",children:o.jsx("span",{className:"ai-main",title:x.name,children:x.name})},x.id))]}),i&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Invite links"}),o.jsx(Ie,{variant:"primary",onClick:async()=>{try{const x=await Sn(`/api/orgs/${e.id}/invites`),j=await Mn(x.url);Ne(j?"Invite link copied to clipboard.":"Invite created — copy it from the list below."),u()}catch(x){Ne(x.message,!0)}},children:"New invite"})]}),o.jsxs("div",{className:"admin-list",children:[m&&m.length===0&&o.jsx("div",{className:"admin-empty",children:"No active invite links."}),(m||[]).map(x=>o.jsxs("div",{className:"admin-item",children:[o.jsx("button",{type:"button",className:"ai-main mono ai-copy","aria-label":`Copy invite link ${x.url}`,title:x.url,onClick:()=>Mn(x.url).then(j=>Ne(j?"Copied.":"Select and copy the link.")),children:x.url}),o.jsx("span",{className:"ai-tag",children:(x.creator?"by "+x.creator+" · ":"")+(x.uses?x.uses+" joined · ":"unused · ")+"expires "+new Date(x.expires).toLocaleDateString()}),o.jsx("button",{className:"ai-del","aria-label":`Revoke invite ${x.token.slice(0,8)}`,onClick:async()=>{if(await ir("Revoke invite",`Revoke the link starting ${x.token.slice(0,8)}…? Anyone still holding it won't be able to join.`,"Revoke",!0))try{await en("DELETE",`/api/orgs/${e.id}/invites/${x.token}`),Ne("Revoked."),u()}catch(j){Ne(j.message,!0)}},children:"Revoke"})]},x.token))]}),o.jsx("h3",{children:"Public share links"}),o.jsx("p",{className:"admin-sub",children:"Every live link across this organization's projects. A project's own links are on its Settings page, and on the file itself."}),o.jsx(y2,{shares:y||[],loading:g,onChanged:f,showProject:!0})]}),o.jsx(rU,{org:e})]})}const Y1=e=>e?new Date(e).toLocaleDateString():"";function rU({org:e}){const t=mn(),n=`/api/orgs/${e.id}/apps`,{data:r}=rt({queryKey:["apps",e.id],queryFn:()=>We(n),select:u=>u.apps||[]}),i=async(u,f)=>{try{await u(),f&&Ne(f)}catch(h){Ne(h.message,!0)}t.invalidateQueries({queryKey:["apps",e.id]})},l=async u=>{await Mn(u),await Wl("New app key","Copied to your clipboard. It is not shown again.",u,"Done")};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"admin-h",children:[o.jsx("h3",{children:"Apps"}),o.jsx(Ie,{variant:"subtle",id:"org-app-new",onClick:async()=>{const u=await Wl("New app","Name of the server or service","","Create");u===null||!u.trim()||await i(()=>Sn(n,{name:u.trim()}),"App created.")},children:"New app"})]}),o.jsx("p",{className:"admin-sub",children:"A server's own key to query a project's data and read its history. Any member can create one. An app sees only what it is granted on each project."}),o.jsxs("div",{className:"admin-list",children:[r&&r.length===0&&o.jsx("div",{className:"admin-empty",children:"No apps."}),(r||[]).map(u=>o.jsxs("div",{children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",title:u.name,children:u.name}),o.jsx("button",{type:"button",className:"ai-tag mono ai-copy","aria-label":`Copy ${u.principal}`,onClick:()=>Mn(u.principal).then(f=>Ne(f?"Copied.":u.principal)),children:u.principal}),u.manage&&o.jsxs(o.Fragment,{children:[o.jsx(Ie,{variant:"subtle",onClick:()=>i(async()=>l((await Sn(`${n}/${u.id}/keys`)).key)),children:"New key"}),o.jsx("button",{className:"ai-del","aria-label":`Delete app ${u.name}`,onClick:async()=>{await ir("Delete app",`Delete “${u.name}” and every key it holds?`,"Delete",!0)&&await i(()=>en("DELETE",`${n}/${u.id}`),"Deleted.")},children:"Delete"})]})]}),u.keys.map(f=>o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main mono",children:["bda_…",f.hint]}),o.jsx("span",{className:"ai-tag",children:"created "+Y1(f.created)+" · "+(f.last_used?"last used "+Y1(f.last_used):"never used")}),o.jsx("button",{className:"ai-del","aria-label":`Revoke key ending ${f.hint}`,onClick:async()=>{await ir("Revoke key",`Revoke the key ending ${f.hint}? Anything using it stops working.`,"Revoke",!0)&&await i(()=>en("DELETE",`${n}/${u.id}/keys/${f.id}`),"Revoked.")},children:"Revoke"})]},f.id))]},u.id))]})]})}function aU({org:e,owner:t,myEmail:n,onChanged:r}){const[i,l]=b.useState([{id:"email",desc:!1}]),u=b.useMemo(()=>bE(),[]),f=b.useMemo(()=>[u.accessor("email",{id:"email",header:"Member",cell:m=>{const y=!!n&&m.getValue().toLowerCase()===n.toLowerCase();return o.jsx("span",{className:"ai-main",title:m.getValue(),children:m.getValue()+(y?"  (you)":"")})}}),u.accessor("role",{id:"role",header:"Role",cell:m=>{const y=m.row.original,g=!!n&&y.email.toLowerCase()===n.toLowerCase();return!t||g?o.jsx("span",{className:"ai-tag role-static",children:y.role}):o.jsxs("span",{className:"role-cell",children:[o.jsxs("select",{"aria-label":`Role for ${y.email}`,value:y.role,onChange:async w=>{try{await en("PATCH",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`,{role:w.target.value}),Ne("Role updated.")}catch(x){Ne(x.message,!0)}r()},children:[o.jsx("option",{value:"owner",children:"owner"}),o.jsx("option",{value:"member",children:"member"})]}),o.jsx("button",{className:"ai-del","aria-label":`Remove ${y.email}`,onClick:async()=>{if(await ir("Remove member",`Remove ${y.email} from ${e.name}?`,"Remove",!0))try{await en("DELETE",`/api/orgs/${e.id}/members/${encodeURIComponent(y.email)}`),Ne("Removed."),r()}catch(w){Ne(w.message,!0)}},children:"Remove"})]})}})],[u,e.id,e.name,t,n]),h=OE({data:e.members,columns:f,state:{sorting:i},onSortingChange:l,getCoreRowModel:ME(),getSortedRowModel:TE()});return o.jsx(m2,{table:h})}const iU=Xv({require_verification:V1(),require_approval:V1()});function oU(){const e=mn(),{data:t,error:n}=rt({queryKey:["admin","policy"],queryFn:()=>We("/api/admin/policy")}),{data:r}=pE(!0),i=Vv({resolver:Qv(iU),values:t?{require_verification:t.require_verification&&t.mailer,require_approval:t.require_approval}:{require_verification:!1,require_approval:!1}});if(b.useEffect(()=>{n&&Ne(n.message,!0)},[n]),!t)return null;const l=async(u,f,h)=>{try{await Sn(`/api/admin/pending/${u}/${f}`),Ne((f==="approve"?"Approved ":"Denied ")+h),e.invalidateQueries({queryKey:["admin","pending"]})}catch(m){Ne(m.message,!0)}};return o.jsxs("div",{className:"admin",children:[o.jsx("h1",{children:"Signup & access"}),o.jsx("p",{className:"admin-sub",children:"Who can create an account on this hub, and how new accounts are vetted."}),o.jsx("h3",{children:"New-account vetting"}),o.jsxs("form",{onSubmit:i.handleSubmit(async u=>{try{await Sn("/api/admin/policy",u),Ne("Signup policy saved."),e.invalidateQueries({queryKey:["admin","policy"]})}catch(f){Ne(f.message,!0)}}),children:[o.jsxs("div",{className:"admin-list",children:[o.jsx(Q1,{label:"Require email verification",desc:t.mailer?"New accounts must click an emailed link before they can sign in — proves they control the address.":"Configure SMTP on the server (auth.smtp) to enable email verification.",disabled:!t.mailer,inputProps:i.register("require_verification")}),o.jsx(Q1,{label:"Require admin approval",desc:"New accounts wait for a hub admin to approve them before they gain access.",inputProps:i.register("require_approval")})]}),o.jsx(Ie,{variant:"primary",type:"submit",style:{marginTop:14},disabled:!i.formState.isDirty,children:"Save policy"})]}),o.jsx("h3",{children:"Who can sign up"}),o.jsxs("div",{className:"admin-list",children:[o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Allowed email domains"}),o.jsx("span",{className:"ai-tag",children:t.allowed_domains&&t.allowed_domains.length?t.allowed_domains.map(u=>"@"+u).join(", "):"any"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Self-signup"}),o.jsx("span",{className:"ai-tag",children:t.allow_signup?"open":"invite-only"})]}),o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:"Hub admins"}),o.jsx("span",{className:"ai-tag",children:t.admins&&t.admins.length?t.admins.join(", "):"none"})]})]}),o.jsx("p",{className:"admin-sub",children:"Domains and admins are set in the server config file (they can't be widened from the browser)."}),o.jsx("h3",{children:"Pending signups"}),o.jsxs("div",{className:"admin-list",children:[(!r||r.length===0)&&o.jsx("div",{className:"admin-empty",children:"No one is waiting for approval."}),(r||[]).map(u=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"ai-main",children:(u.name?u.name+"  ·  ":"")+u.email}),o.jsx(Ie,{variant:"primary",onClick:()=>l(u.id,"approve",u.email),children:"Approve"}),o.jsx("button",{className:"ai-del",onClick:()=>l(u.id,"deny",u.email),children:"Deny"})]},u.id))]})]})}function Q1({label:e,desc:t,disabled:n,inputProps:r}){return o.jsxs("label",{className:"admin-item toggle",style:n?{opacity:.55}:void 0,children:[o.jsxs("span",{className:"ai-main",children:[o.jsx("div",{className:"tg-label",children:e}),o.jsx("div",{className:"tg-desc",children:t})]}),o.jsx("input",{type:"checkbox",disabled:n,...r})]})}function ks({className:e,...t}){return o.jsx("div",{"data-slot":"card",className:at("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rs({className:e,...t}){return o.jsx("div",{"data-slot":"card-header",className:at("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ms({className:e,...t}){return o.jsx("div",{"data-slot":"card-title",className:at("leading-none font-semibold",e),...t})}function or({className:e,...t}){return o.jsx("div",{"data-slot":"card-description",className:at("text-muted-foreground text-sm",e),...t})}function Fs({className:e,...t}){return o.jsx("div",{"data-slot":"card-content",className:at("px-6",e),...t})}function X1(e){if(!e||e.startsWith("0001-"))return"never";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function lU({projects:e}){const t=mn(),n=rt({queryKey:["mcp","grants"],queryFn:()=>We("/api/mcp/grants")}),r=FM({mutationFn:u=>en("DELETE",`/api/mcp/grants/${encodeURIComponent(u)}`),onSuccess:()=>{Ne("Disconnected. The agent's access stopped immediately."),t.invalidateQueries({queryKey:["mcp","grants"]})},onError:u=>Ne(u.message,!0)}),i=u=>e.find(f=>f.id===u)?.name||u;if(n.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.error)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Connections are unavailable"}),o.jsx("p",{children:n.error.message})]});const l=n.data?.grants??[];return o.jsxs("div",{className:"project-settings",id:"mcp-connections",children:[o.jsx("h2",{children:"Connected agents"}),o.jsxs("p",{className:"admin-sub",children:["Agents you have connected to this hub over"," ",o.jsx("a",{href:"https://modelcontextprotocol.io",target:"_blank",rel:"noreferrer",children:"MCP"}),". Each one reads and changes files in the projects you chose, acting as you — so its changes appear in History under your name, and it can never do more than you can."]}),l.length===0?o.jsx(ks,{children:o.jsxs(Rs,{children:[o.jsx(Ms,{children:"No agents connected"}),o.jsxs(or,{children:["Point an MCP client (Claude, ChatGPT, Cursor, …) at"," ",o.jsxs("code",{children:[window.location.origin,"/mcp"]}),". It will send you back here to pick which projects it may use."]})]})}):l.map(u=>o.jsxs(ks,{className:"mcp-grant",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:u.client_name||"Unnamed client"}),o.jsxs(or,{children:["Connected ",X1(u.created)," · last used ",X1(u.last_used)]})]}),o.jsxs(Fs,{children:[o.jsx("div",{className:"mcp-projects",children:u.projects.map(f=>o.jsx("span",{className:"ps-chip",children:i(f)},f))}),o.jsx(Ie,{variant:"destructive",disabled:r.isPending,onClick:()=>{r.mutate(u.id)},children:"Disconnect"})]})]},u.id))]})}function Wv({...e}){return o.jsx(Nz,{"data-slot":"dropdown-menu",...e})}function Jv({...e}){return o.jsx(kz,{"data-slot":"dropdown-menu-trigger",...e})}function ey({className:e,sideOffset:t=4,...n}){return o.jsx(Rz,{children:o.jsx(Mz,{"data-slot":"dropdown-menu-content",sideOffset:t,className:at("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})})}function Es({className:e,inset:t,variant:n="default",...r}){return o.jsx(Oz,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function cU({...e}){return o.jsx(Az,{"data-slot":"dropdown-menu-radio-group",...e})}function uU({className:e,children:t,...n}){return o.jsxs(Dz,{"data-slot":"dropdown-menu-radio-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:o.jsx(zz,{children:o.jsx(K3,{className:"size-2 fill-current"})})}),t]})}function dU({className:e,inset:t,...n}){return o.jsx(Tz,{"data-slot":"dropdown-menu-label","data-inset":t,className:at("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function pg({className:e,...t}){return o.jsx(Lz,{"data-slot":"dropdown-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function fU({className:e,...t}){return o.jsx("span",{"data-slot":"dropdown-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const Dd=e=>"bdrive.lastVisit."+e,b2=e=>"bdrive.pins."+e;function ty(e){try{return localStorage.getItem(e)}catch{return null}}function pc(e,t){try{localStorage.setItem(e,t)}catch{}}const gg=new Set;function ny(){for(const e of gg)e()}function sy(e){return gg.add(e),()=>{gg.delete(e)}}const zd=new Map;function hU(e){let t=zd.get(e);if(t===void 0){const n=Number(ty(Dd(e)));t=Number.isFinite(n)&&n>0?n:Date.now(),zd.set(e,t),n>0||pc(Dd(e),String(t))}return t}function mU(e){pc(Dd(e),String(Date.now())),zd.delete(e)}function pU(e){const t=Date.now();zd.set(e,t),pc(Dd(e),String(t)),ny()}function ry(e){return b.useSyncExternalStore(sy,()=>e?hU(e):0)}const vg=new Map,gU=[];function ay(e){let t=vg.get(e);if(!t){try{const n=JSON.parse(ty(b2(e))||"[]");t=Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{t=[]}vg.set(e,t)}return t}function W1(e,t){const n=ay(e),r=n.includes(t)?n.filter(i=>i!==t):[...n,t];vg.set(e,r),pc(b2(e),JSON.stringify(r)),ny()}function vU(e){return b.useSyncExternalStore(sy,()=>e?ay(e):gU)}const w2="bdrive.treeOrder";function yU(){return b.useSyncExternalStore(sy,()=>ty(w2)==="recent"?"recent":"name")}function xU(e){pc(w2,e),ny()}function fd(e,t,n){if(!e)return null;if(!n)return e[t]||null;const r={human:0,agent:0,share:0};for(const[i,l]of Object.entries(e))i.startsWith(t+"/")&&(r.human+=l.human||0,r.agent+=l.agent||0,r.share+=l.share||0);return r.human||r.agent||r.share?r:null}function Ps(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function Xu(e){const t=Ps(e);if(!t)return"";const n=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return n;const r=[];return e.human&&r.push(e.human+" human"),e.agent&&r.push(e.agent+" agent"),e.share&&r.push(e.share+" shared"),n+" ("+r.join(", ")+")"}const Ir="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function bU(e){const t=Ps(e);return t?t<3?1:t<10?2:t<30?3:4:0}function wU(e,t){return e?Object.keys(e).filter(n=>!t.has(n)).sort():[]}const SU=7;function jU(e){if(!e.length)return null;let t=e[0],n=e[0];for(const r of e)rn&&(n=r);return{min:t,max:n}}const CU=(e,t)=>t-el.reads-i.reads).slice(0,EU)){const i=r.path.split("/").pop();let l=r.cx+r.r+4,u="start";l+i.length*NU>t.right&&(l=r.cx-r.r-4,u="end");const f=m=>n.every(y=>Math.abs(y.y-m)>=mp);let h=r.cy;for(;h<=t.bottom&&!f(h);)h+=mp;if(h>t.bottom)for(h=r.cy;h>=t.top&&!f(h);)h-=mp;n.push({path:r.path,name:i,x:l,y:Math.min(t.bottom,Math.max(t.top,h)),anchor:u})}return n}const S2=10,j2=30,C2=(e,t)=>e>=S2&&t>=j2;function iy(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?Math.max(0,(t-n)/864e5):null}function oy(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function _2(e,t){const n=iy(t);return!e||n===null||!C2(Ps(e),n)?"":`stale · last changed ${oy(n)}`}function E2(e,t=!0){const n=rt({queryKey:["tree",e],queryFn:()=>We(e+"tree?slim=1"),enabled:t,refetchInterval:3e5}),r=b.useMemo(()=>{const i=[],l=new Map,u=(f,h)=>{for(const m of f.children||[])m.path=h?h+"/"+m.name:m.name,m.dir?(l.set(m.path,m),u(m,m.path)):i.push(m)};return n.data&&u(n.data,""),{flatFiles:i,dirIndex:l}},[n.data]);return{tree:n.data,...r,loaded:!!n.data}}const N2=e=>({...e,children:e.children?.map(N2)}),k2=e=>{if(e.children){e.children.sort((t,n)=>{if(!!t.dir!=!!n.dir)return t.dir?-1:1;const r=t.name.toLowerCase(),i=n.name.toLowerCase();return ri?1:0});for(const t of e.children)t.dir&&k2(t)}},R2=e=>{if(!e.dir)return e.time;let t="";for(const n of e.children||[]){const r=R2(n);r&&(!t||(Date.parse(r)||0)>(Date.parse(t)||0))&&(t=r)}return e.time=t||void 0,e.time};function RU(e,t){const n=N2(e);n.children||(n.children=[]);for(const r of t){const i=r.path.split("/").filter(Boolean);if(!i.length)continue;const l=i[i.length-1];if(r.op==="put"){let u=n;for(let h=0;hw.name===m);!g||!g.dir?(g={name:m,path:y,dir:!0,children:[]},u.children=u.children.filter(w=>w.name!==m),u.children.push(g)):g.children||(g.children=[]),u=g}const f={name:l,path:r.path,size:r.size,time:r.time,user:r.user,user_name:r.user_name,author:r.author,device:r.device,link:r.link};u.children=(u.children||[]).filter(h=>h.name!==l),u.children.push(f)}else if(r.op==="delete"){const u=(f,h)=>{if(!f.children)return!1;const m=i[h];if(h===i.length-1){const g=f.children.length;return f.children=f.children.filter(w=>w.name!==m||w.dir),g!==f.children.length&&f.children.length===0}const y=f.children.find(g=>g.name===m&&g.dir);return!y||!u(y,h+1)?!1:(f.children=f.children.filter(g=>g!==y),f.children.length===0)};u(n,0)}k2(n),R2(n)}return n}function MU(e,t){return rt({queryKey:["heat",e],queryFn:()=>We(e+"heat?days=30"),enabled:t,staleTime:6e4}).data?.entries??null}function TU(e,t,n){return rt({queryKey:["history",e,"prefix",t,20],queryFn:()=>We(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:n,staleTime:15e3}).data?.entries??null}const M2=e=>"/api/p/"+e+"/",Ld=100;function T2(e,t=!0){const n=ry(e),r=e?M2(e):"";return rt({queryKey:["history",r,"since",n],queryFn:()=>We(r+"history?n="+Ld+"&since="+encodeURIComponent(new Date(n).toISOString())),enabled:t&&!!e&&n>0,retry:!1,staleTime:15e3})}function O2(e,t=!0){const n=T2(e,t);return t&&n.data?(n.data.entries||[]).length:null}function OU(e,t){const n=e?M2(e):"",r=rt({queryKey:["heatDevices",n],queryFn:()=>We(n+"heat?by=device&days=30"),enabled:!!e&&t,retry:!1,staleTime:6e4}),{flatFiles:i}=E2(n,!!e),l=b.useMemo(()=>{let f=0;for(const h of i)f=Math.max(f,h.time&&Date.parse(h.time)||0);return f||void 0},[i]);return{devices:r.data?.devices?.length||void 0,synced:l}}function AU(e,t){const n=rt({queryKey:["comments",e,"open-all"],queryFn:()=>We(e+"comments?status=open"),enabled:t,retry:!1});return b.useMemo(()=>{const r=new Map;for(const i of n.data?.comments||[])r.set(i.path,(r.get(i.path)||0)+1);return r},[n.data])}function vo(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";const r=Math.round(n/60);if(r<60)return r+"m ago";const i=Math.round(r/60);return i<48?i+"h ago":Math.round(i/24)+"d ago"}let ur={query:"",sel:0},hd=0,A2=null;const yg=new Set;function Ef(e){ur=e;for(const t of yg)t()}function ly(){return b.useSyncExternalStore(e=>(yg.add(e),()=>yg.delete(e)),()=>ur)}function D2(e){e!==ur.query&&Ef({query:e,sel:0})}function xg(){D2("")}function DU(e,t){hd=e,A2=t,ur.sel>=e&&Ef({...ur,sel:Math.max(0,e-1)})}function zU(e){hd!==0&&Ef({...ur,sel:(ur.sel+e+hd)%hd})}function J1(e){e!==ur.sel&&Ef({...ur,sel:e})}function LU(){A2?.(ur.sel)}const eS=["#5b8def","#f5a623","#4cc38a","#e0679b","#8b7bf0","#3ec8c8","#e6934a"];function z2(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return eS[t%eS.length]}function gc(e){return{"--mk":z2(e)}}const L2=[["home","Home","home"],["activity","Activity","activity"],["insights","Insights","insights"]],$d=e=>e>=Ld?Ld-1+"+":String(e);function pp({projects:e,currentId:t,menu:n,account:r,onNew:i}){const l=e.find(f=>f.id===t),u=O2(n?.active==="home"?t:void 0);return o.jsxs("nav",{id:"projects","aria-label":"Projects",children:[o.jsx($2,{projects:e,current:l,menu:n,account:r,onNew:i,trigger:o.jsxs("button",{id:"project-select",className:"proj-trigger","aria-label":`Project and account menu — current project: ${l?.name??"none"}`,title:l?.name,children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:l?gc(l.name):void 0,children:o.jsx(ci,{name:l?.icon})}),o.jsx("span",{className:"proj-name",children:l?l.name:e.length?"Select a project":"No projects yet"}),o.jsx(H3,{className:"ico updown","aria-hidden":"true"})]})}),n&&o.jsx(F2,{}),n&&o.jsx("ul",{className:"nav-menu","aria-label":"Project pages",children:L2.map(([f,h,m])=>o.jsx("li",{children:o.jsxs("div",{id:"nav-"+f,className:"row"+(n.active===f?" active":""),role:"button",tabIndex:0,"aria-current":n.active===f?"page":void 0,onClick:()=>n.onNav(f),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),n.onNav(f))},children:[o.jsx(ge,{name:m}),o.jsx("span",{className:"label",children:h}),f==="activity"&&!!u&&o.jsx("span",{className:"nav-count",title:`${$d(u)} changes since your last visit`,children:$d(u)})]})},f))})]})}function $2({projects:e,current:t,menu:n,account:r,onNew:i,trigger:l,side:u="bottom"}){const[f,h]=b.useState(!1),m=()=>h(!1),{pref:y,setPref:g}=Ev(),w=r?.org??null,x=w?Pn(w.manage_url):null,j=r?.billing?Pn(r.billing.url):null,S=Pn("/connections"),E=!!w&&!w.manage_url.startsWith("/");return o.jsxs(Wv,{modal:!1,open:f,onOpenChange:h,children:[o.jsx(Jv,{asChild:!0,children:l}),o.jsxs(ey,{id:"project-menu",className:"sb-menu",side:u,align:"start",sideOffset:u==="right"?8:4,children:[o.jsx("div",{className:"sb-menu-projects",children:e.map(_=>o.jsxs(Es,{"data-project":_.id,"aria-current":_.id===t?.id?"true":void 0,onSelect:()=>{_.id!==t?.id&>("/"+_.id),fs()},children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(_.name),children:o.jsx(ci,{name:_.icon})}),o.jsx("span",{className:"label",children:_.name}),_.id===t?.id&&o.jsx(ge,{name:"check"})]},_.id))}),o.jsxs(Es,{id:"menu-new-project",onSelect:i,children:[o.jsx("span",{className:"proj-mark add","aria-hidden":"true",children:o.jsx(ge,{name:"plus"})}),o.jsx("span",{className:"label dim",children:"New project"})]}),(n||w||r?.billing||r?.admin)&&o.jsx(pg,{}),n&&t&&o.jsxs(Es,{id:"nav-settings","aria-current":n.active==="settings"?"page":void 0,onSelect:()=>n.onNav("settings"),children:[o.jsx(ge,{name:"gear"}),o.jsx("span",{className:"label",children:"Project settings"})]}),w&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-org-settings","aria-current":r?.orgActive?"page":void 0,...x,onClick:_=>{x?.onClick?.(_),m()},children:[o.jsx(ge,{name:"building"}),o.jsx("span",{className:"label",children:"Organization settings"}),o.jsx("span",{className:"meta",children:w.name}),E&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]})}),r?.billing&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-billing",...j,onClick:_=>{j?.onClick?.(_),m()},children:[o.jsx(ge,{name:"card"}),o.jsx("span",{className:"label",children:"Billing"}),o.jsx("span",{className:"ps-chip plan-chip",children:r.billing.plan})]})}),r?.admin&&o.jsxs(Es,{id:"menu-hub-admin",onSelect:r.admin.onClick,children:[o.jsx(ge,{name:"shield"}),o.jsx("span",{className:"label",children:"Signup & access"}),!!r.admin.pending&&o.jsx("span",{className:"meta",children:r.admin.pending})]}),o.jsx(pg,{}),r&&o.jsx(dU,{className:"sb-menu-label",children:r.me.email}),o.jsxs("div",{className:"sb-theme",children:[o.jsx("span",{className:"label",children:"Theme"}),o.jsx(cU,{className:"seg","aria-label":"Theme",value:y,onValueChange:_=>g(_),children:$U.map(({value:_,label:N,Glyph:R})=>o.jsx(uU,{id:`menu-theme-${_}`,className:"seg-item",value:_,"aria-label":N,title:N,onSelect:T=>T.preventDefault(),children:o.jsx(R,{className:"ico","aria-hidden":"true"})},_))})]}),r?.mcp&&o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"menu-connections",...S,onClick:_=>{S.onClick?.(_),m()},children:[o.jsx(ge,{name:"plug"}),o.jsx("span",{className:"label",children:"Connected agents"})]})}),r&&(r.signOut?o.jsxs(Es,{id:"signout",onSelect:r.signOut,children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]}):o.jsx(Es,{asChild:!0,children:o.jsxs("a",{id:"signout",href:"/auth/logout",children:[o.jsx(ge,{name:"power"}),o.jsx("span",{className:"label",children:"Log out"})]})}))]})]})}const $U=[{value:"system",label:"System",Glyph:u6},{value:"light",label:"Light",Glyph:q6},{value:"dark",label:"Dark",Glyph:f6}];function FU(){const[,e]=b.useState(0);b.useEffect(()=>{const t=window.setInterval(()=>e(n=>n+1),6e4);return()=>window.clearInterval(t)},[])}function IU({pid:e,readsEnabled:t,active:n,onOpen:r}){FU();const{devices:i,synced:l}=OU(e,t),u=[];i&&u.push(i+(i===1?" device":" devices")),l&&u.push("synced "+vo(l));const f=o.jsxs("button",{id:"nav-install",className:"row sb-sync"+(n?" active":""),onClick:r,children:[u.length?o.jsx("span",{className:"sync-dot","aria-hidden":"true"}):o.jsx(ge,{name:"laptop"}),o.jsx("span",{id:"sync-line",className:"label",children:u.length?u.join(" · "):"Connect a device"})]});return u.length?o.jsx("div",{className:"sb-foot",children:o.jsxs(cf,{delayDuration:300,children:[o.jsx(uf,{asChild:!0,children:f}),o.jsx(df,{className:"tipcard",side:"top",sideOffset:6,children:"Connect a device"})]})}):o.jsx("div",{className:"sb-foot",children:f})}function F2(){const{query:e}=ly();return o.jsxs("div",{id:"sb-search",className:e?"filtering":void 0,children:[o.jsx(ge,{name:"search"}),o.jsx("input",{id:"sb-search-input",type:"text",value:e,placeholder:"Search","aria-label":"Filter files, or press Enter to search everything",autoComplete:"off",spellCheck:!1,onMouseDown:t=>{e||t.button!==0||(t.preventDefault(),Co(),fs())},onChange:t=>D2(t.target.value),onKeyDown:t=>{t.key==="ArrowDown"||t.key==="ArrowUp"?(t.preventDefault(),zU(t.key==="ArrowDown"?1:-1)):t.key==="Enter"?(t.preventDefault(),!e.trim()||t.metaKey||t.ctrlKey?Co(e.trim()):LU()):t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),e?xg():t.currentTarget.blur())}}),e?o.jsx("button",{className:"sb-kbd","aria-label":"Clear filter",onClick:xg,children:"esc"}):o.jsxs(cf,{delayDuration:150,children:[o.jsx(uf,{asChild:!0,children:o.jsx("button",{id:"search-btn",className:"sb-kbd","aria-label":"Search",onClick:()=>{Co(),fs()},children:Xl?"⌘K":"Ctrl K"})}),o.jsxs(df,{className:"tipcard",sideOffset:6,children:["Search everything ",o.jsx("kbd",{children:Xl?"⌘K":"Ctrl+K"})]})]})]})}function PU({pid:e,menu:t}){const n=O2(t.active==="home"?e:void 0);return o.jsx(o.Fragment,{children:L2.map(([r,i,l])=>o.jsx(Cv,{id:"rail-"+r,icon:l,label:i,hint:r==="activity"&&n?$d(n)+" new":void 0,badge:r==="activity"&&n?$d(n):void 0,active:t.active===r,onClick:()=>t.onNav(r)},r))})}function UU(e){return o.jsx($2,{...e,side:"right",trigger:o.jsx("button",{id:"rail-project",className:"rail-btn rail-proj","aria-label":`Project and account menu — ${e.current.name}`,children:o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.current.name),children:o.jsx(ci,{name:e.current.icon})})})})}const VU="https://github.com/runbear-io/beardrive";function HU(){return o.jsx("svg",{viewBox:"0 0 16 16",className:"gh-mark",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"})})}function qU(){return o.jsxs("a",{className:"gh-star",href:VU,target:"_blank",rel:"noreferrer",children:[o.jsx(HU,{}),o.jsx("span",{children:"Star on GitHub"}),o.jsx("span",{className:"ext","aria-hidden":"true",children:"↗"}),o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})}function BU({onSignIn:e}){return o.jsxs("footer",{id:"accountbar",children:[o.jsx(qU,{}),o.jsxs("button",{id:"account-btn",onClick:e,"aria-label":"Sign in",children:[o.jsx("span",{className:"avatar",style:{background:"var(--hover)"},"aria-hidden":"true",children:"?"}),o.jsxs("span",{className:"acct",children:[o.jsx("b",{children:"Sign in…"}),o.jsx("small",{children:"connect to your hub"})]})]})]})}function Lr({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return o.jsx(Vz,{"data-slot":"separator",decorative:n,orientation:t,className:at("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}function GU({url:e}){const t=rt({queryKey:["billing"],queryFn:()=>We(e)});if(t.isLoading)return o.jsx("div",{className:"empty",children:"Loading…"});if(t.error||!t.data)return o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Billing is unavailable"}),o.jsx("p",{children:t.error?.message||"Try again shortly."})]});const n=t.data;return o.jsxs("div",{className:"project-settings",id:"billing-view",children:[o.jsxs("h2",{children:["Billing",o.jsx("span",{className:"ps-chip plan-chip",children:n.plan.name})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsxs(Ms,{children:[n.plan.name," plan",n.plan.status?` (${n.plan.status})`:""]}),o.jsxs(or,{children:["Organization ",n.org," · ",n.usage.used," of ",n.usage.cap," used · ",n.seats.used," of ",n.seats.cap," ",n.seats.cap===1?"seat":"seats"]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("div",{className:"usage-bar",children:o.jsx("div",{style:{width:`${n.usage.pct}%`}})})})]}),n.owner?o.jsx("div",{className:"plan-grid",children:n.plans.map(r=>o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:r.name}),o.jsx(or,{children:r.blurb})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("p",{className:"plan-price",children:[r.price,o.jsx("small",{children:" / user / month"})]}),o.jsxs("form",{method:"post",action:n.checkout_url,children:[o.jsx("input",{type:"hidden",name:"plan",value:r.id}),o.jsx(Ie,{type:"submit",disabled:r.current,variant:r.current?"subtle":"default",children:r.current?"Current plan":`Upgrade to ${r.name}`})]})]})]},r.id))}):o.jsx("p",{className:"muted-note",children:"Only an organization owner can change the plan."}),n.owner&&n.has_customer&&o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Manage subscription"}),o.jsx(or,{children:"Change seats, update the card, download invoices, or cancel."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx("form",{method:"post",action:n.portal_url,children:o.jsx(Ie,{type:"submit",variant:"subtle",children:"Open the billing portal"})})})]})]})}function md({className:e,type:t,...n}){return o.jsx("input",{type:t,"data-slot":"input",className:at("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...n})}function gp({className:e,...t}){return o.jsx(Fz,{"data-slot":"label",className:at("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function KU({className:e,...t}){return o.jsx("textarea",{"data-slot":"textarea",className:at("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}const tS={read:1,write:2,admin:3};function In(e,t){return(tS[e||""]||0)>=(tS[t]||0)}const bg=280,ZU=Xv({name:dd().trim().min(1,"Give the project a name.").max(120,"Keep the name under 120 characters."),description:dd().max(bg,`Keep the description under ${bg} characters.`),icon:dd()});function YU({project:e,org:t,onDeleted:n}){const r=gE(),i=In(e.perm,"admin"),l=Vv({resolver:Qv(ZU),defaultValues:{name:e.name,description:e.description??"",icon:e.icon??""}});b.useEffect(()=>{l.reset({name:e.name,description:e.description??"",icon:e.icon??""})},[e.id,e.name,e.description,e.icon]);const u=l.watch("icon"),f=l.watch("description"),h=l.handleSubmit(async m=>{const y=l.formState.dirtyFields,g={};if(y.name&&(g.name=m.name.trim()),y.description&&(g.description=m.description),y.icon&&(g.icon=m.icon),Object.keys(g).length!==0)try{await en("PATCH","/api/projects/"+e.id,g),Ne("Saved."),l.reset({...m,name:m.name.trim()}),await r()}catch(w){Ne(w.message,!0)}});return o.jsxs("div",{className:"project-settings",children:[o.jsxs("h2",{children:[e.name,!In(e.perm,"write")&&o.jsx("span",{className:"ps-chip",children:"Read-only"})]}),o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"General"}),o.jsx(or,{children:"Name, description and icon for this project."})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsxs("form",{className:"ps-form",onSubmit:h,children:[o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-icon-btn",children:"Icon"}),o.jsxs("div",{className:"ps-icon-row",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:u})}),o.jsxs(Wv,{children:[o.jsx(Jv,{asChild:!0,children:o.jsx(Ie,{id:"ps-icon-btn",type:"button",variant:"subtle",disabled:!i,children:"Change"})}),o.jsxs(ey,{align:"start",className:"ps-icon-grid",children:[o.jsx(Es,{className:"ps-icon-cell"+(u===""?" active":""),title:"Default","aria-label":"Default icon",onSelect:()=>l.setValue("icon","",{shouldDirty:!0}),children:o.jsx(ci,{})}),Object.keys(Qp).map(m=>o.jsx(Es,{className:"ps-icon-cell"+(u===m?" active":""),title:m,"aria-label":m,onSelect:()=>l.setValue("icon",m,{shouldDirty:!0}),children:o.jsx(ci,{name:m})},m))]})]})]})]}),o.jsxs("div",{className:"ps-field",children:[o.jsx(gp,{htmlFor:"ps-name",children:"Name"}),o.jsx(md,{id:"ps-name",disabled:!i,"aria-invalid":!!l.formState.errors.name,"aria-describedby":l.formState.errors.name?"ps-name-err":void 0,...l.register("name")}),l.formState.errors.name&&o.jsx("span",{id:"ps-name-err",role:"alert",className:"field-err",children:l.formState.errors.name.message})]}),o.jsxs("div",{className:"ps-field",children:[o.jsxs(gp,{htmlFor:"ps-desc",children:["Description ",o.jsx("span",{className:"ps-opt",children:"(optional)"})]}),o.jsx(KU,{id:"ps-desc",rows:2,disabled:!i,placeholder:"What this project is for.","aria-invalid":!!l.formState.errors.description,"aria-describedby":l.formState.errors.description?"ps-desc-err":void 0,...l.register("description")}),o.jsxs("div",{className:"ps-meta",children:[l.formState.errors.description?o.jsx("span",{id:"ps-desc-err",role:"alert",className:"field-err",children:l.formState.errors.description.message}):o.jsx("span",{}),o.jsxs("span",{className:"ps-count",children:[f.length," / ",bg]})]})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Lr,{}),o.jsx("div",{className:"ps-actions",children:o.jsx(Ie,{id:"ps-save",type:"submit",variant:"primary",disabled:!l.formState.isDirty||l.formState.isSubmitting,children:"Save changes"})})]})]})})]}),o.jsx(XU,{project:e}),o.jsx(JU,{project:e,org:t}),o.jsxs(ks,{id:"ps-devices",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Devices"}),o.jsx(or,{children:"Sync this project to another computer, or set up an agent on one."})]}),o.jsx(Fs,{children:o.jsx(Ie,{asChild:!0,variant:"outline",children:o.jsx("a",{...Pn(un("install",e.id)),children:"Connect a device"})})})]}),In(e.perm,"write")&&o.jsx(QU,{project:e,onChanged:r}),o.jsxs(ks,{children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"About"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsxs("dl",{className:"ps-facts",children:[o.jsx("dt",{children:"Project id"}),o.jsx("dd",{children:o.jsx("code",{children:e.id})}),t&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{children:t.name})]}),e.created&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Created"}),o.jsx("dd",{children:new Date(e.created).toLocaleDateString()})]})]}),o.jsxs("p",{className:"ps-note ps-export",children:[o.jsx("strong",{children:"Take your files elsewhere."})," Run ",o.jsx("code",{children:"bdrive export"})," in the synced folder to write the whole project — every device's journal and every content blob, so full history and authorship — into a single archive. ",o.jsx("code",{children:"bdrive import"})," restores it into any other BearDrive hub, self-hosted or cloud. Export warns first if this device still has changes it hasn't pushed."," ",o.jsx("a",{href:"https://docs.beardrive.ai/reference/migration/",target:"_blank",rel:"noreferrer",children:"How migration works →"})]})]})]}),i&&o.jsxs(ks,{className:"ps-danger",children:[o.jsx(Rs,{children:o.jsx(Ms,{children:"Danger zone"})}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[o.jsx("p",{children:"Deleting removes the project from this hub. Its files stay in storage. This can't be undone."}),o.jsx(Ie,{variant:"danger",onClick:async()=>{if(await Wl(`Delete “${e.name}”?`,"This can't be undone. Type the project name to confirm:","","Delete project",{match:e.name,danger:!0})!==null)try{await en("DELETE","/api/projects/"+e.id),Ne(`Deleted “${e.name}”.`),await n()}catch(y){Ne(y.message,!0)}},children:"Delete project"})]})]})]})}function QU({project:e,onChanged:t}){const n=!!e.data;return o.jsxs(ks,{id:"ps-data",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Data"}),o.jsx(or,{children:n?"Apps and agents can query this project's JSON files and Markdown frontmatter as data.":"Let apps and agents query this project's JSON files and Markdown frontmatter as data. The files stay the source."})]}),o.jsx(Fs,{children:o.jsx(Ie,{id:"ps-data-toggle",variant:"outline",onClick:async()=>{try{await en("PUT",`/api/p/${e.id}/data`,{enabled:!n}),Ne(n?"Data queries are off.":"Data queries are on. Indexing has started."),await t()}catch(r){Ne(r.message,!0)}},children:n?"Turn off data queries":"Turn on data queries"})})]})}function XU({project:e}){const t=mn(),{data:n,error:r,isLoading:i}=mE(e.id);return r?null:o.jsxs(ks,{children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"Public links"}),o.jsxs(or,{children:["Files in this project that anyone with the URL can read — no account needed.",(n||[]).some(l=>l.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]})]}),o.jsx(Lr,{}),o.jsx(Fs,{children:o.jsx(y2,{shares:n||[],loading:i,canRevoke:In(e.perm,"write"),onChanged:()=>t.invalidateQueries({queryKey:["shares",e.id]}),empty:"No public links."})})]})}const wg=[{value:"admin",label:"Admin"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],WU=Object.fromEntries(wg.map(e=>[e.value,e.label]));function JU({project:e,org:t}){const n=mn(),{data:r,error:i}=kv(e.id),l=In(e.perm,"admin"),u=()=>{n.invalidateQueries({queryKey:["permissions",e.id]}),n.invalidateQueries({queryKey:["projects"]})},f=async(x,j)=>{try{await x(),Ne(j)}catch(S){Ne(S.message,!0)}u()};if(i||!r)return null;const h=r,m=`/api/p/${e.id}/permissions`,y=new Set((t?.members||[]).filter(x=>x.role==="owner").map(x=>x.email.toLowerCase())),g=[...h.grants.filter(x=>!y.has(x.email.toLowerCase())),...[...y].sort().map(x=>({email:x,level:"admin",owner:!0}))],w=async()=>{const x=await Wl("Add an exception","Email of a workspace member, or an app's id (app:…). They get Read access; change it in the table.","","Add");x===null||!x.trim()||await f(()=>en("PUT",`${m}/${encodeURIComponent(x.trim())}`,{level:"read"}),"Added.")};return o.jsxs(ks,{className:"ps-people",children:[o.jsxs(Rs,{children:[o.jsx(Ms,{children:"People"}),o.jsx(or,{children:"Who can see and change this project."})]}),o.jsx(Lr,{}),o.jsxs(Fs,{children:[t?.role==="owner"&&o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Not in ",t.name," yet?"]}),o.jsx(Ie,{id:"ps-invite",type:"button",variant:"subtle",onClick:async()=>{try{const x=await Sn(`/api/orgs/${t.id}/invites`),j=await Mn(x.url+"?p="+e.id);Ne(j?"Invite link copied — it opens this project.":"Invite created — copy it from Organization settings.")}catch(x){Ne(x.message,!0)}},children:"Invite a teammate"})]}),o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",t?.name||"this workspace"," can"]}),o.jsx("select",{"aria-label":"Default access for workspace members",disabled:!l,value:h.default,onChange:async x=>{const j=x.target.value;if(j==="none"&&!await ir("Make this project invite-only?","Only people listed below (and workspace owners) will see this project.","Make invite-only")){u();return}await f(()=>en("PUT",m,{default:j}),"Default access updated.")},children:wg.filter(x=>x.value!=="admin").map(x=>o.jsx("option",{value:x.value,children:x.label},x.value))})]}),h.default==="none"&&o.jsx("p",{className:"ps-note",children:"This project is invite-only: only the people below and workspace owners can see it."}),o.jsxs("div",{className:"ps-people-head",children:[o.jsx("h4",{children:"Exceptions"}),l&&o.jsx(Ie,{type:"button",variant:"subtle",onClick:w,children:"+ Add"})]}),g.length===0?o.jsx("p",{className:"ps-note",children:"No exceptions — everyone gets the access above."}):o.jsx("div",{className:"admin-list",children:g.map(x=>{const j="owner"in x;return o.jsxs("div",{className:"admin-item",children:[o.jsxs("span",{className:"ai-main",title:x.email,children:[x.email,h.creator&&x.email.toLowerCase()===h.creator.toLowerCase()&&o.jsx("span",{className:"ai-tag",children:" (creator)"})]}),j?o.jsx("span",{className:"ai-tag",children:"Workspace owner — always admin"}):o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":`Access for ${x.email}`,disabled:!l,value:x.level,onChange:S=>f(()=>en("PUT",`${m}/${encodeURIComponent(x.email)}`,{level:S.target.value}),`${x.email} is now ${WU[S.target.value]||S.target.value}.`),children:wg.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))}),l&&o.jsx("button",{className:"ai-del","aria-label":`Remove exception for ${x.email}`,onClick:()=>f(()=>en("DELETE",`${m}/${encodeURIComponent(x.email)}`),"Reverted to the default access."),children:"Remove"})]})]},x.email)})})]})]})}const eV="https://raw.githubusercontent.com/runbear-io/beardrive/main/INSTALL_FOR_AGENTS.md";function Nf(e,t={}){const{project:n,folder:r,existing:i}=t,l=n?"BearDrive project "+n.id:r?`the shared ${r}/ folder in my project`:"a new BearDrive project",u=i?"I already have a folder of notes — ask me which one to sync":"Ask me which folder to sync",f=n?` (the project is named "${n.name}")`:"";return`Follow ${eV}
 to set up ${l} on ${e}. ${u}${f}.`}function I2({project:e,existing:t}){const n=window.location.origin,r=Nf(n,{project:e,existing:t}),i=`brew install runbear-io/tap/beardrive
 bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guide",children:[o.jsxs("h1",{className:"in-title gd-head",children:[o.jsx("span",{className:"proj-mark","aria-hidden":"true",style:gc(e.name),children:o.jsx(ci,{name:e.icon})}),e.name]}),e.description&&o.jsx("p",{className:"in-desc",children:e.description}),o.jsxs("div",{className:"gd-body",children:[o.jsx("p",{className:"gd-desc",children:t?"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder you already have:":"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files:"}),t&&o.jsx("p",{className:"gd-note",children:"Your files stay exactly where they are. Connecting a folder never moves, renames or overwrites anything in it — it uploads what is there and keeps it in sync."}),o.jsx(tc,{code:r}),o.jsx("p",{className:"gd-desc",children:"The agent installs the CLI, signs this machine in, and registers the sync hooks — asking before anything it changes."}),o.jsx("p",{className:"gd-desc",children:"Runs on macOS and Linux. Windows is not supported yet."}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"What exactly happens"}),o.jsxs("ul",{className:"gd-desc gd-list",children:[o.jsx("li",{children:"Sign-in uses a device code you approve in this browser — the folder itself never holds credentials."}),o.jsx("li",{children:"Sync hooks pull the latest before every agent turn, push edits seconds after they happen, and stamp each change with the session that made it; agent reads feed Insights. They register once per machine in your agent's own config, so every session is covered and nothing is written into the synced folder."}),o.jsx("li",{children:"Codex hooks are off by default: set [features] codex_hooks = true in ~/.codex/config.toml."})]})]}),o.jsxs("details",{className:"gd-manual",children:[o.jsx("summary",{children:"Or run it yourself"}),o.jsx("p",{className:"gd-desc",children:"Same result, in the folder you want the files. Install the CLI, point it at this hub, then bdrive init registers the sync hooks and starts syncing."}),o.jsx(tc,{code:i}),o.jsx("p",{className:"gd-desc",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/install/",target:"_blank",rel:"noreferrer",children:"Full manual setup guide →"})})]})]})]})}function tc({code:e}){const[t,n]=b.useState("Copy");return o.jsxs("pre",{className:"gd-code",children:[o.jsx("code",{children:e}),o.jsx("button",{className:"gd-copy",onClick:async()=>{n(await Mn(e)?"Copied":"Copy failed"),setTimeout(()=>n("Copy"),1400)},children:t})]})}function tV({onNew:e,canCreate:t}){return o.jsxs("div",{className:"onboard",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"You're signed in, but you're not part of any project yet."}),t&&o.jsxs("div",{className:"ob-card ob-start",children:[o.jsx("h3",{children:"Start a project"}),o.jsx("p",{children:"Name it and pick what it starts from — a structure, or nothing at all. Then connect a folder on any machine and it stays in sync."}),o.jsx(Ie,{variant:"primary",id:"ob-new",onClick:e,children:"New project"})]}),o.jsxs("div",{className:"ob-card ob-agent",children:[o.jsx("h3",{children:t?"Or let your agent do it":"Connect a new drive to your project"}),o.jsx("p",{children:"Paste into your coding agent — Claude Code, Cowork, Codex, Gemini CLI, Hermes — in the folder where you want the files. It creates the project and starts syncing:"}),o.jsx(tc,{code:Nf(window.location.origin)}),o.jsx("p",{className:"ob-alt",children:o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}function nV({onStart:e}){return o.jsxs("div",{className:"onboard setup-welcome",children:[o.jsx("h1",{children:"Welcome to BearDrive"}),o.jsx("p",{children:"One shared drive for your team and your AI agents — every folder you connect stays in sync, with full history."}),o.jsx(Ie,{variant:"primary",id:"setup-start",onClick:e,children:"Get started"}),o.jsx("p",{className:"setup-foot",children:"Takes about two minutes · works offline afterwards"})]})}function sV({data:e,name:t}){const n=e?.entries??[],r=e?.root_name||"your project";return o.jsxs("div",{className:"setup-tree","aria-label":"How it will look",children:[o.jsx("div",{className:"setup-tree-head",children:"HOW IT WILL LOOK"}),o.jsxs("div",{className:"setup-tree-root",children:[r,"/ ",o.jsx("span",{className:"setup-dim",children:"· private"})]}),n.map(i=>o.jsxs("div",{className:"setup-dim",children:["├── ",i]},i)),e?.entries_truncated&&o.jsx("div",{className:"setup-dim",children:"├── …"}),o.jsxs("div",{className:"setup-tree-shared",children:["└── ",t||"team","/ ",o.jsx("span",{className:"setup-shared-tag",children:"shared"})]}),o.jsxs("p",{className:"setup-tree-foot",children:["Only ",t||"team","/ syncs. Everything else never leaves this Mac. Teammates get the same"," ",t||"team","/ inside their own projects."]})]})}function rV({onStarted:e}){const[t,n]=b.useState(""),[r,i]=b.useState("team"),[l,u]=b.useState(!0),[f,h]=b.useState(null),[m,y]=b.useState(!1),[g,w]=b.useState(""),[x,j]=b.useState(!1),S=b.useCallback(async T=>{const A=window.__TAURI__?.core?.invoke;if(!(!A||!T))try{await A("prime_folder_access",{path:T})}catch{}},[]);b.useEffect(()=>{if(!t){h(null);return}const T=setTimeout(async()=>{await S(t),We(`/api/desktop/inspect?path=${encodeURIComponent(t)}&name=${encodeURIComponent(r)}`).then(h).catch(()=>h(null))},200);return()=>clearTimeout(T)},[t,r,S]);const E=b.useCallback(async()=>{const T=await vd("/api/desktop/choose-folder");if(!T.ok)return;const A=await T.json();A.path&&(await S(A.path),n(A.path))},[S]),_=b.useCallback(async()=>{y(!0),w("");const T=await vd("/api/desktop/init",{root:t,name:r,hooks:l});if(y(!1),!T.ok){w((await T.text()).trim()||"could not connect that folder");return}e(r)},[t,r,l,e]),N=!!f?.join,R=!t||!!f?.error||!!f?.conflict||m;return o.jsxs("div",{className:"setup-connect",children:[o.jsxs("header",{children:[o.jsxs("h2",{children:["Add a shared folder to your project",!N&&o.jsx("span",{className:"setup-badge",children:"RECOMMENDED"})]}),o.jsxs("p",{children:["Your project stays yours. One folder inside it is shared — your agent reads it in every session."," ",o.jsx("a",{href:"#why",onClick:T=>(T.preventDefault(),j(!x)),children:"Why this layout?"})]}),x&&o.jsxs("ul",{className:"setup-why",children:[o.jsx("li",{children:"Claude sessions here read and write it automatically — shared memory, no setup."}),o.jsx("li",{children:"Everything outside it stays on this Mac. Your code never syncs."}),o.jsx("li",{children:"Teammates get the same folder inside their own projects — one shared space."})]})]}),o.jsxs("div",{className:"setup-body",children:[o.jsxs("div",{className:"setup-form",children:[o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Your project folder"}),o.jsxs("div",{className:"setup-root",children:[o.jsx("input",{id:"setup-root",value:t,spellCheck:!1,placeholder:"/Users/you/work/your-project",onChange:T=>n(T.target.value)}),o.jsx("button",{type:"button",id:"setup-choose",onClick:E,children:"Choose…"})]})]}),o.jsxs("label",{className:"setup-field",children:[o.jsx("span",{children:"Shared folder name"}),o.jsx("input",{id:"setup-name",value:r,spellCheck:!1,onChange:T=>i(T.target.value)})]}),o.jsxs("label",{className:"setup-toggle",children:[o.jsx("input",{type:"checkbox",id:"setup-hooks",checked:l,onChange:T=>u(T.target.checked)}),o.jsx("span",{children:"Claude Code integration"})]}),f?.is_claude_project&&!f?.error&&o.jsxs("p",{className:"setup-ok",children:["Claude Code project detected — ",(f.markers??[]).join(", ")]}),N&&o.jsxs("p",{className:"setup-ok",children:["Your team already shares a “",f.join.name,"” space — you'll join it."]}),(f?.error||f?.conflict||g)&&o.jsx("p",{className:"setup-err",children:g||f?.conflict||f?.error}),f?.warning&&!f?.error&&!f?.conflict&&o.jsxs("div",{className:"setup-warn",children:[o.jsx("p",{children:f.warning}),f.helper&&o.jsxs("p",{className:"setup-helper",children:["Full Disk Access wants this binary:"," ",o.jsx("code",{children:f.helper})," ",o.jsx("button",{type:"button",onClick:()=>navigator.clipboard.writeText(f.helper),children:"Copy path"})]})]}),o.jsx(Ie,{variant:"primary",id:"setup-go",disabled:R,onClick:_,children:N?`Join ${r}/ and start syncing`:`Create ${r}/ and start syncing`}),o.jsxs("p",{className:"setup-foot",children:["Prefer to share the whole folder?"," ",o.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Advanced"})]})]}),o.jsx(sV,{data:f,name:r})]})]})}function aV({onDone:e}){const t=new URLSearchParams(window.location.search).get("name")||"",[n,r]=b.useState({phase:"creating",name:t}),i=b.useRef(!1);b.useEffect(()=>{const f=setInterval(async()=>{try{const h=await We("/api/desktop/init/status");r({...h,name:h.name||t}),!i.current&&(h.phase==="done"||h.phase==="error")&&(i.current=!0,clearInterval(f),h.phase==="done"&&e(h))}catch{}},400);return()=>clearInterval(f)},[e]);const l=["creating","connecting","syncing","done"],u=Math.max(0,l.indexOf(n.phase));return o.jsxs("div",{className:"setup-syncing",children:[o.jsxs("h2",{children:["Syncing ",n.name?n.name+"/":"your folder"]}),o.jsx("div",{className:"setup-bar",children:o.jsx("div",{style:{width:`${(u+1)/l.length*100}%`}})}),o.jsxs("ul",{className:"setup-log",children:[o.jsx("li",{className:u>0?"ok":"",children:"created the shared folder"}),o.jsx("li",{className:u>1?"ok":"",children:n.joined?"joined the project":"created the project"}),o.jsx("li",{className:u>2?"ok":"",children:"first sync"})]}),n.phase==="error"?o.jsx("p",{className:"setup-err",id:"setup-error",children:n.error}):o.jsx("p",{className:"setup-foot",children:"You can close this window — syncing continues from the menu bar."})]})}function iV({st:e}){const[t,n]=b.useState(""),[r,i]=b.useState(!1),[l,u]=b.useState(""),f=e.name||"team",h=Nf(window.location.origin,{folder:f}),m=async(g,w)=>{try{await navigator.clipboard.writeText(w),n(g)}catch{n("")}},y=async()=>{i(!0),u("");try{const w=(await We("/api/orgs")).orgs[0]?.id;if(!w)throw new Error("no organization on this hub");const x=await vd(`/api/orgs/${w}/invites`,{});if(!x.ok)throw new Error((await x.text()).trim());const j=await x.json();await navigator.clipboard.writeText(j.url),n("invite")}catch(g){u(g.message||"could not create an invite link")}finally{i(!1)}};return o.jsxs("div",{className:"setup-done",children:[o.jsxs("h2",{children:[f,"/ is live"]}),o.jsxs("p",{className:"setup-foot",children:["shared inside ",e.root?e.root.split("/").pop():"your project"," · history from here on"]}),e.error&&o.jsx("p",{className:"setup-err",children:e.error}),o.jsxs("div",{className:"setup-cards",children:[o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Open the dashboard"}),o.jsx("p",{children:"Browse files, history, and who reads what."}),o.jsx(Ie,{id:"setup-open",onClick:()=>gt(e.project?"/"+e.project:"/"),children:"Open"})]}),o.jsxs("div",{className:"setup-card setup-card-lead",children:[o.jsx("h3",{children:"Tell your agent"}),o.jsx("p",{children:"Claude sessions in this folder now share context with your team."}),o.jsx(tc,{code:h}),o.jsx(Ie,{id:"setup-copy-prompt",onClick:()=>m("prompt",h),children:t==="prompt"?"Copied":"Copy prompt"})]}),o.jsxs("div",{className:"setup-card",children:[o.jsx("h3",{children:"Invite teammates"}),o.jsx("p",{children:"A link that signs them up straight into this project."}),o.jsx(Ie,{id:"setup-invite",disabled:r,onClick:y,children:t==="invite"?"Copied":r?"…":"Copy invite link"}),l&&o.jsx("p",{className:"setup-err",id:"setup-invite-err",children:l})]})]})]})}function oV({step:e,signedIn:t,onSignIn:n}){const[r,i]=b.useState(null);return b.useEffect(()=>{e==="welcome"&&t&>("/setup/connect"),e!=="welcome"&&!t&>("/setup")},[e,t]),o.jsxs("div",{className:"setup",children:[e==="welcome"&&o.jsx(nV,{onStart:n}),e==="connect"&&o.jsx(rV,{onStarted:l=>gt("/setup/syncing?name="+encodeURIComponent(l))}),e==="syncing"&&o.jsx(aV,{onDone:l=>{i(l),gt("/setup/done")}}),e==="done"&&o.jsx(iV,{st:r??{}})]})}const P2="__existing__";function lV({templates:e,onCreate:t,onClose:n}){const r=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:P2,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[i,l]=b.useState(""),[u,f]=b.useState(r[0].value),[h,m]=b.useState(""),[y,g]=b.useState(!1),w=async()=>{if(!y){if(!i.trim()){m("Give it a name.");return}g(!0);try{await t(i.trim(),u)}finally{g(!1)}}};return o.jsx(uc,{open:!0,onOpenChange:x=>!x&&n(),children:o.jsxs(dc,{className:"modal",showCloseButton:!1,children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:"New project"})}),o.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),o.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:i,"aria-invalid":!!h,"aria-describedby":h?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),h&&m("")},onKeyDown:x=>x.key==="Enter"&&w()}),h&&o.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:h}),r.length>1&&o.jsxs("fieldset",{className:"start-points",children:[o.jsx("legend",{className:"modal-label",children:"Starting point"}),r.map((x,j)=>o.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[o.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>f(x.value)}),o.jsxs("span",{className:"sp-text",children:[o.jsxs("span",{className:"sp-title",children:[x.title,j===0&&o.jsx("span",{className:"sp-rec",children:"Recommended"})]}),o.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:n,children:"Cancel"}),o.jsx(Ie,{variant:"primary",onClick:w,disabled:y,children:"Create"})]})]})})}const U2=1<<20,cV=8192;function uV(e){if(e.byteLength>U2)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,cV).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function nc(e,t,n,r){let i=e+"blob?sha="+encodeURIComponent(t);return n&&(i+="&name="+encodeURIComponent(n)),r&&(i+="&download=1"),i}async function kf(e){const t=await qM(e),n=Number(t.headers.get("Content-Length")??t.headers.get("X-Uncompressed-Length"));if(n>U2)return{kind:"too-large",size:n};const r=uV(new Uint8Array(await t.arrayBuffer())),i=t.headers.get("ETag")?.replace(/^W\/|"/g,"");return r.kind==="text"&&i?{...r,sha:i}:r}function Mo(e,t,n){return n?nc(e,n,t):e+"file?path="+encodeURIComponent(t)}function dV(e){return!(e instanceof Hg)||e.status===429||e.status>=500}function cy(e,t,n,r){return rt({queryKey:t,queryFn:()=>kf(e),enabled:n,...r?{staleTime:1/0,gcTime:1/0}:{},retry:r?!1:(i,l)=>i<3&&dV(l),retryDelay:i=>Math.min(1e3*2**i,8e3)})}function sc(e,t,n){return cy(t?nc(e,t):"",["blob",e,t],n&&!!t,!0)}function V2(e,t,n,r){const{data:i,isError:l,refetch:u}=rt({queryKey:["frame",e,t],queryFn:()=>We(e+"frame?path="+encodeURIComponent(t)),enabled:!r,staleTime:1/0,retry:1});return{url:r||l?n:i?.url,fresh:async()=>{r||!i||i.expires-Date.now()>600*1e3||await u()}}}const fV=(e,t)=>({time:t.time||new Date().toISOString(),kind:t.op==="delete"?"delete":"edit",path:t.path,...t.size===void 0?{}:{size:t.size},user:t.user,user_name:t.user_name,author:t.author,device:{id:e.device||t.device,name:e.device_name||t.device},session:e.agent?"live":void 0});function hV(e,t=!0,n){const r=mn(),i=b.useRef(n);i.current=n,b.useEffect(()=>{if(!t||typeof EventSource>"u")return;const l=2e3;let u=null,f=null,h=!1;const m=M=>{M&&(h=!0),!f&&(f=window.setTimeout(()=>{const L=h;f=null,h=!1,r.invalidateQueries({queryKey:["history",e],predicate:L?void 0:H=>H.queryKey[2]!=="since"}),L&&r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},y=M=>{if(!M.files?.length)return;const L=M.files.map(U=>fV(M,U)),H=(U,Z,X)=>{if(!Z)return;const Q=new Set(Z.entries.map(le=>`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`)),ae=L.filter(le=>{const be=`${le.device?.id||le.device?.name||""}\0${le.time}\0${le.path}\0${le.kind}`;return Q.has(be)?!1:(Q.add(be),!0)});ae.length&&r.setQueryData(U,{...Z,entries:[...ae,...Z.entries].slice(0,X)})};for(const[U,Z]of r.getQueriesData({queryKey:["history",e]}))U[2]==="since"&&H(U,Z,100);for(const[U,Z]of r.getQueriesData({queryKey:["homeHistory",e]}))H(U,Z,200)},g=()=>{u||(u=window.setTimeout(()=>{u=null,r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]}),r.invalidateQueries({queryKey:["emptied",e]})},l))},w=M=>{let L;try{L=JSON.parse(M)}catch{return}if(L.type==="presence"){i.current?.(L.people??[]);return}if(L.type==="comments"){r.invalidateQueries({queryKey:["comments",e]});return}if(L.type==="scope"){r.invalidateQueries({queryKey:["tree",e]}),r.invalidateQueries({queryKey:["emptied",e]}),r.invalidateQueries({queryKey:["folders"]}),r.invalidateQueries({queryKey:["permissions"]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]}),r.invalidateQueries({queryKey:["history",e]}),r.invalidateQueries({queryKey:["homeHistory",e]});return}window.dispatchEvent(new CustomEvent("bdrive:changed",{detail:L.paths??[]}));const H=(L.puts||0)+(L.deletes||0),U=r.getQueryData(["tree",e]);if(L.type==="change"&&!L.more&&H>0&&!!L.files?.length&&!!U?(r.setQueryData(["tree",e],X=>X&&RU(X,L.files)),H===L.files.length?(y(L),m(!1)):m(!0)):g(),L.type==="resync"||L.more||!L.paths?.length){L.type==="resync"&&r.invalidateQueries({queryKey:["comments",e]}),r.invalidateQueries({queryKey:["render",e]}),r.invalidateQueries({queryKey:["text"]});return}for(const X of L.paths)r.invalidateQueries({queryKey:["render",e,X]}),r.invalidateQueries({queryKey:["text",Mo(e,X)]})},x=`bdrive:events:${e}`;let j=null,S=null,E=null;const _=new AbortController;let N=!1,R=!1;const T=(M=!1)=>{j=new EventSource(e+"events"),j.onopen=()=>{if(R||M){const L=JSON.stringify({type:"resync"});S?.postMessage(L),w(L)}R=!0},j.onmessage=L=>{S?.postMessage(L.data),w(L.data)},j.onerror=()=>{}},A=()=>{N=!0,_.abort(),E?.(),j?.close(),S?.close()};if(window.addEventListener("pagehide",A),typeof BroadcastChannel>"u"||!navigator.locks)T();else{S=new BroadcastChannel(x),S.onmessage=L=>w(L.data);const M=L=>new Promise(H=>{if(N)return H();E=H,T(L)});navigator.locks.request(`${x}:leader`,{ifAvailable:!0},L=>L?M(!1):navigator.locks.request(`${x}:leader`,{signal:_.signal},()=>M(!0))).catch(()=>{})}return()=>{window.removeEventListener("pagehide",A),A()}},[e,t,r])}function mV(e,t,n=!0){const[r,i]=b.useState([]),l=b.useRef(t);return l.current=t,b.useEffect(()=>{if(!n)return;let u=!0;return(async(h=!1)=>{try{const m=await Sn(e+"presence",{path:l.current,...h?{leave:!0}:{}});u&&!h&&i(m.people??[])}catch{}})(),()=>{u=!1}},[e,n,t]),b.useEffect(()=>{if(n)return()=>{Sn(e+"presence",{path:l.current,leave:!0}).catch(()=>{})}},[e,n]),{people:r,setPeople:i}}function pV(e){return/\.md$/i.test(e)&&e.split("/").slice(0,-1).includes("daily-meetings")}function uy(e){const t=[];let n=0,r=!1,i=null;const l=u=>{i&&(i.to=u,i.body=e.slice(i.headingEnd,u).split(`
 `).filter(f=>f.trim()).join(`
@@ -125,7 +125,7 @@ bdrive init --server `+n+" --project "+e.id;return o.jsxs("div",{className:"guid
 `).filter(t=>q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DzwiNrvp.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-Co88xBUl.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(dn=>{const jt=dn.user?.name;jt&&ot.push(jt)}),K([...new Set(ot)]);const Yt=uy(P.current),Nt=new Set;for(const dn of B.remoteCursors()){const jt=H2(Yt,dn.pos);jt&&Nt.add(jt.name)}D(Nt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const Nt=Yt.merge(ot.text,ot.sha,{held:Fe});re(Nt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}return!Yt||ot.askingShrink()?!1:(we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0)};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?cn("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DYseo8Gn.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DWsPYvxy.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
 `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
-`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=cn("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(cn("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(cn("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
-`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(cn("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),Nt=b.useRef(null),dn=b.useRef(null),jt=e.panel??null,Lt=!jt&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!jt&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),sn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||sn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,sn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!jt,[Ct,rn]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Et=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),an=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!an)return;const ie=an+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[an]),qn=!jt&&i&&!!l,$o=!jt&&Z&&!r.view,Oa=!jt&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!sn,_n=!jt&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",cn("history",ze)),Nn("insights","Insights",cn("dashboard",ze)),Nn("gear","Settings",cn("settings",ze)),Nn("laptop","Connect a device",cn("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(cn("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(jt)An=jt.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?cn("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(cn("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:sn,editSource:ns,me:Hs,commentable:ms,flushRef:Nt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=jt?jt.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!sn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{sn||(Cp(),gS(f,n,M))},onFocus:()=>{sn||(Cp(),gS(f,n,M))},title:sn?"Stop editing":"Edit this file",onClick:async()=>{if(!sn){gt($n(M,l?.id,L,r.full,!0));return}const ie=Nt.current;if(!(ie&&dn.current===ie)){dn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{dn.current===ie&&(dn.current=null)}}},children:[!sn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:sn?"Done":"Edit"})]}),sn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>hr(ie=>!ie),children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Et,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),an&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(cn("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&Ct!==null?{"--page-read":Ct+"px"}:void 0,children:[!jt&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:Ct,onChange:rn})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?cn(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:cn(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:cn(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(cn("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
+`).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
+`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-ifG4O60o.js b/internal/webapp/static/assets/sharedfile-CM4z2OLg.js
similarity index 99%
rename from internal/webapp/static/assets/sharedfile-ifG4O60o.js
rename to internal/webapp/static/assets/sharedfile-CM4z2OLg.js
index 1b393c0e..a8cb1bad 100644
--- a/internal/webapp/static/assets/sharedfile-ifG4O60o.js
+++ b/internal/webapp/static/assets/sharedfile-CM4z2OLg.js
@@ -1,4 +1,4 @@
-import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-BtQZiOrJ.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-YxeGfSng.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
 `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[tn]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?cn(e,(n,s)=>Us(n,t[s])):!1;class st{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[tn](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Jr(t,this),t}expect(t){return Jr(t,this),t}}class tr extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ht()};class pc extends st{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends st{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends st{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends st{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):cn(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends st{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&cn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends st{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&cn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends st{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(st);class Tc extends st{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends st{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends st{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>en(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const en=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=en(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(en));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ht()},Jr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
 ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:en(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Pr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Pr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(en(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Pc=e=>{const t=Vc();for(let n=0;n(Bi(e,Pc(t)),e),lu=(e,t=[],n=[])=>Jc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Pi(e)),Wi.forEach(t=>t.print(e))},Ji=(...e)=>{console.warn(...Pi(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Ps{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>jr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return Ze(this.restDecoder)}readBuf(){return lc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(K(t)),this.clientDecoder=new Ln(K(t)),this.leftClockDecoder=new ks(K(t)),this.rightClockDecoder=new ks(K(t)),this.infoDecoder=new Vr(K(t),Ae),this.stringDecoder=new Rl(K(t)),this.parentInfoDecoder=new Vr(K(t),Ae),this.typeRefDecoder=new Ln(K(t)),this.lenDecoder=new Ln(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ze(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ze(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,h=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(u,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)h(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),h=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,h.update])}}else l.pendingStructs=h;const u=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);u&&d?l.pendingDs=Fn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===hn)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new hn),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ht()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ht();l>=0?h=c._length:h=0}return Ca(c,h,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!an(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ht()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Jn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Js(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{so(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new hn;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!an(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Ps{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,I=b-S;I>0&&nn(f,w,S,I)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else u.push(new Ra(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ji("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,hn),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Jt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),h=Ms(c);return Ne(o,h),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Jt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const h=or(l);return Ne(i,h),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let h=i.curr;h!==null;h=i.next())Jt(l,t(h),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,hn),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return an(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Ji("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return rn(e,(s,r)=>{n.push(t(s,r,e))}),n},Pa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Z();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&sn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&sn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new un(s);break;case he:l=new fn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Z(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){rn(this,t)}[Symbol.iterator](){return Pa(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Wt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&sn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
 `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},Jl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})()
 BearDrive
 
-  
+  
   
   
   

From ad0cb0dc08aa81e304a0075a3f84da5cb898d440 Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Wed, 11 Nov 2026 23:54:56 +0900
Subject: [PATCH 14/34] fix(webapp): drain and lock VisualEdit iframe before
 staging-to-live join

---
 .../frontend/src/components/VisualEdit.tsx    | 109 +++++++++++------
 .../webapp/frontend/src/lib/sharedfile.ts     | 110 ++++++++++++------
 .../src/lib/sharedfile_restore.test.ts        |  99 ++++++++++++++++
 ...{Editor-DYseo8Gn.js => Editor-cr2ybdrO.js} |   2 +-
 .../static/assets/VisualEdit-DWsPYvxy.js      |   1 -
 .../static/assets/VisualEdit-DxYGQmno.js      |   1 +
 .../{index-YxeGfSng.js => index-BXWhn62d.js}  |   4 +-
 ...ile-CM4z2OLg.js => sharedfile-Mmk-VhrH.js} |  18 +--
 internal/webapp/static/index.html             |   2 +-
 9 files changed, 259 insertions(+), 87 deletions(-)
 rename internal/webapp/static/assets/{Editor-DYseo8Gn.js => Editor-cr2ybdrO.js} (99%)
 delete mode 100644 internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
 create mode 100644 internal/webapp/static/assets/VisualEdit-DxYGQmno.js
 rename internal/webapp/static/assets/{index-YxeGfSng.js => index-BXWhn62d.js} (99%)
 rename internal/webapp/static/assets/{sharedfile-CM4z2OLg.js => sharedfile-Mmk-VhrH.js} (65%)

diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx
index a711b385..cb356115 100644
--- a/internal/webapp/frontend/src/components/VisualEdit.tsx
+++ b/internal/webapp/frontend/src/components/VisualEdit.tsx
@@ -166,6 +166,67 @@ export function VisualEdit({
     }, 11_000);
     const stuckTimer = setTimeout(() => setStuck(true), 24_000);
 
+    /* Messages from the frame, handled one at a time in arrival order; Done's
+       save first drains them (frame.current answers a flush only after every
+       patch it posted before), so a word typed just before Done is in the
+       document — and in its save, shrink check and failure — before the save
+       decides whether the editor may close. */
+    const channel = frameChannel();
+    let frameReady = false;
+    const drainFrame = async (lock: boolean) => {
+      const el = frame.current;
+      const win = el?.contentWindow;
+      if (!el || !win) return;
+      // A frame that reloads or is replaced cannot answer: stop waiting then.
+      let reloaded = false;
+      const onLoad = () => {
+        reloaded = true;
+      };
+      el.addEventListener("load", onLoad);
+      try {
+        await channel.drain(
+          (m) => win.postMessage(m, "*"),
+          () => !frameReady || reloaded || frame.current !== el || el.contentWindow !== win,
+          lock,
+        );
+      } finally {
+        el.removeEventListener("load", onLoad);
+      }
+      // Saving now: the idle save the last patch armed has nothing left to do.
+      clearTimeout(stageTimer);
+      stageTimer = undefined;
+    };
+    /* Lock the frame and drain it: every patch it posted is in the document
+       and nothing more can be typed until the returned release. Done's save
+       and the join (a staging buffer folded into the room) both hold one;
+       counted per frame window, so neither unlocks the other early and a
+       release meant for a frame since replaced never touches the new one. */
+    const winLocks = new Map();
+    const lockFrame = async (): Promise<() => void> => {
+      const win = frame.current?.contentWindow;
+      if (!win) return () => {};
+      winLocks.set(win, (winLocks.get(win) ?? 0) + 1);
+      let released = false;
+      const release = () => {
+        if (released) return;
+        released = true;
+        const left = (winLocks.get(win) ?? 1) - 1;
+        if (left > 0) {
+          winLocks.set(win, left);
+          return;
+        }
+        winLocks.delete(win);
+        win.postMessage({ type: "bd-edit:unlock" }, "*");
+      };
+      try {
+        await drainFrame(true);
+      } catch (e) {
+        release();
+        throw e;
+      }
+      return release;
+    };
+
     const file = (fileRef.current = openSharedFile({
       apiBase,
       path,
@@ -176,6 +237,10 @@ export function VisualEdit({
       onConflictCopy: (p) => cb.current.onConflictCopy?.(p),
       onShrinkRefused: (ask) => askShrink(path, ask),
       onShrinkWithdrawn: withdrawShrink,
+      // The socket synced while staging: every patch the frame has posted
+      // must be in the staging buffer before the join reads it, and nothing
+      // typed while the join folds it into the room. Unlocked once joined.
+      beforeJoin: async () => (stageDoc ? lockFrame() : () => {}),
       // Nothing to mount either way: the surface is the iframe, which is
       // already on screen. The room is joined for the CRDT alone.
       onReady: () => {
@@ -238,50 +303,24 @@ export function VisualEdit({
         });
       },
     }));
-    /* Messages from the frame, handled one at a time in arrival order; Done's
-       save first drains them (frame.current answers a flush only after every
-       patch it posted before), so a word typed just before Done is in the
-       document — and in its save, shrink check and failure — before the save
-       decides whether the editor may close. */
-    const channel = frameChannel();
-    let frameReady = false;
-    const drainFrame = async (lock: boolean) => {
-      const el = frame.current;
-      const win = el?.contentWindow;
-      if (!el || !win) return;
-      // A frame that reloads or is replaced cannot answer: stop waiting then.
-      let reloaded = false;
-      const onLoad = () => {
-        reloaded = true;
-      };
-      el.addEventListener("load", onLoad);
-      try {
-        await channel.drain(
-          (m) => win.postMessage(m, "*"),
-          () => !frameReady || reloaded || frame.current !== el || el.contentWindow !== win,
-          lock,
-        );
-      } finally {
-        el.removeEventListener("load", onLoad);
-      }
-      // Saving now: the idle save the last patch armed has nothing left to do.
-      clearTimeout(stageTimer);
-      stageTimer = undefined;
-    };
     /* Done: the frame is drained AND locked, so nothing typed while the save
        is on the wire can be left out of it; it is unlocked again unless the
        save landed (lib/frameflush.ts saveLocked). Concurrent calls share one. */
     let savingFrame: Promise | null = null;
     const exposed: SharedFile = {
       ...file,
-      saveNow: () =>
-        (savingFrame ??= saveLocked(
-          () => drainFrame(true),
+      saveNow: () => {
+        let release = () => {};
+        return (savingFrame ??= saveLocked(
+          async () => {
+            release = await lockFrame();
+          },
           () => file.saveNow(),
-          () => frame.current?.contentWindow?.postMessage({ type: "bd-edit:unlock" }, "*"),
+          () => release(),
         ).finally(() => {
           savingFrame = null;
-        })),
+        }));
+      },
     };
     if (handle) handle.current = exposed;
 
diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts
index 1338fc10..1bb988a5 100644
--- a/internal/webapp/frontend/src/lib/sharedfile.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile.ts
@@ -168,6 +168,10 @@ export type SharedFileOptions = {
       surface cannot take one, and merge() says so rather than claiming a
       change it could not make. */
   soloApply?: (e: { from: number; to: number; insert: string }) => void;
+  /** A surface whose edits reach `soloText` asynchronously (VisualEdit's
+      iframe) brings them all in and stops taking more before the join reads
+      the buffer; the join calls the returned release once it is done. */
+  beforeJoin?: () => Promise<() => void>;
 };
 
 /* Three ways to be connected, and what writes the file in each:
@@ -1022,48 +1026,78 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile {
         return;
       }
     }
-    const local = opts.soloText?.();
-    if (local === undefined || local === saved) return finishJoin();
-    const hub = collab.text.toString();
-    const res = mergeForPath(saved, hub, local);
-    if (res.ok) return finishJoin(() => collab.applySplices(diffSplices(hub, res.text)));
-    pendingJoin = true;
-    // One name for every attempt at the same text: a retry re-writes the same
-    // copy, never a second. Newer text — or a staging park still on the wire —
-    // gets a freshly minted name, so an older PUT never lands over it.
-    if (parkedName === null || parkedText !== local) {
-      parkedName = mintConflictPath();
-      parkedText = local;
+    /* The buffer the join is about to read may still be arriving (an
+       iframe's patches over postMessage): bring it all in and hold the
+       surface still until the join is done. No checkpoint goes out meanwhile:
+       the join is what hands the buffer to the room. */
+    let unlockSurface: (() => void) | undefined;
+    if (opts.beforeJoin) {
+      waitingToJoin = true;
+      try {
+        unlockSurface = await opts.beforeJoin();
+      } catch {
+        // A surface that cannot be drained joins with what it has.
+      } finally {
+        waitingToJoin = false;
+      }
+      if (gone || hubHoldsIt) {
+        unlockSurface?.();
+        return;
+      }
+      if (!live) {
+        unlockSurface?.();
+        if (current() !== saved || roomNeedsFlush) scheduleSave();
+        return;
+      }
     }
-    joining = true;
-    let failed: { err: unknown } | null;
     try {
-      failed = await preserve(local, base ?? "", parkedName);
-    } finally {
-      joining = false;
-    }
-    if (gone) return; // destroy() parked the buffer itself
-    if (!failed) {
-      // Typing that landed in the buffer while the copy was on the wire is
-      // not in it: go round again from what was parked.
-      if (opts.soloText?.() !== local) {
-        parkedName = null;
-        parkedText = null;
-        return join();
+      const local = opts.soloText?.();
+      if (local === undefined || local === saved) return finishJoin();
+      const hub = collab.text.toString();
+      const res = mergeForPath(saved, hub, local);
+      if (res.ok) return finishJoin(() => collab.applySplices(diffSplices(hub, res.text)));
+      pendingJoin = true;
+      // One name for every attempt at the same text: a retry re-writes the same
+      // copy, never a second. Newer text — or a staging park still on the wire —
+      // gets a freshly minted name, so an older PUT never lands over it.
+      if (parkedName === null || parkedText !== local) {
+        parkedName = mintConflictPath();
+        parkedText = local;
       }
-      // Parked: the editor now shows the room's text, which is what it is built on.
-      return finishJoin(() => {
-        saved = collab.text.toString();
-      });
+      joining = true;
+      let failed: { err: unknown } | null;
+      try {
+        failed = await preserve(local, base ?? "", parkedName);
+      } finally {
+        joining = false;
+      }
+      if (gone) return; // destroy() parked the buffer itself
+      if (!failed) {
+        // Typing that landed in the buffer while the copy was on the wire is
+        // not in it: go round again from what was parked.
+        if (opts.soloText?.() !== local) {
+          parkedName = null;
+          parkedText = null;
+          return join();
+        }
+        // Parked: the editor now shows the room's text, which is what it is built on.
+        return finishJoin(() => {
+          saved = collab.text.toString();
+        });
+      }
+      const e = failed.err;
+      if (e instanceof HttpError && !(e.status >= 500 || e.status === 429)) return; // waits for the next edit
+      const delay = SAVE_RETRY_MS[Math.min(joinAttempt, SAVE_RETRY_MS.length - 1)];
+      joinAttempt++;
+      joinTimer = setTimeout(() => {
+        joinTimer = null;
+        void join();
+      }, delay);
+    } finally {
+      // Joined (onReady has run), parked, or waiting on a retry: the surface
+      // takes typing again.
+      unlockSurface?.();
     }
-    const e = failed.err;
-    if (e instanceof HttpError && !(e.status >= 500 || e.status === 429)) return; // waits for the next edit
-    const delay = SAVE_RETRY_MS[Math.min(joinAttempt, SAVE_RETRY_MS.length - 1)];
-    joinAttempt++;
-    joinTimer = setTimeout(() => {
-      joinTimer = null;
-      void join();
-    }, delay);
   };
 
   const collab = new CollabDoc(
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index 6f5c260c..8fd2e07f 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -2681,3 +2681,102 @@ for (const outcome of ["saved", "503", "shrink"] as const) {
     }
   });
 }
+
+/* The socket syncs while VisualEdit is staging and the frame's last patch is
+   still in the postMessage queue. The join must not read the staging buffer
+   without it: beforeJoin drains and locks the frame first, so the patch is
+   in the join's merge (or in the conflict copy, if it clashes with the
+   room), and the frame is unlocked once the join is done. */
+for (const room of ["merges", "clashes"] as const) {
+  test(`a join drains the frame's queued patch before reading the staging buffer (${room})`, async () => {
+    const connect = mock.method(CollabDoc.prototype, "connect", () => {});
+    const puts: Array<{ url: string; body: string }> = [];
+    const posts: string[] = [];
+    globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => {
+      if (init?.method === "PUT") {
+        puts.push({ url: decodeURIComponent(String(url)), body: String(init.body) });
+        return new Response(JSON.stringify({ sha: "sha-copy" }), { status: 200 });
+      }
+      posts.push(String(init?.body));
+      return new Response(JSON.stringify({ sha: "sha-room", text: "" }), { status: 200 });
+    }) as typeof fetch;
+    const state = { buffer: "a\nb\nc\n" };
+    const channel = frameChannel();
+    const frame = { locked: false, unlocks: 0, readAt: "" };
+    // window "message" delivery: a later task, in posting order.
+    const deliver = (msg: { type: "patch"; text: string } | { type: "flushed"; id: number }) =>
+      setImmediate(() =>
+        channel.enqueue(async () => {
+          await Promise.resolve(); // anchoring is async; order must still hold
+          if (msg.type === "patch") state.buffer = msg.text;
+          else channel.flushed(msg.id);
+        }),
+      );
+    const ready: unknown[] = [];
+    const file = openSharedFile({
+      apiBase: "/api/p/proj/",
+      path: "page.html",
+      seed: "a\nb\nc\n",
+      baseSha: "sha-a",
+      who: "tester",
+      me: { name: "t", colour: "oklch(0.7 0.1 200)" },
+      onReady: (c) => ready.push(c),
+      onSolo: () => {},
+      soloText: () => {
+        frame.readAt = state.buffer;
+        return state.buffer;
+      },
+      soloApply: (e) => {
+        state.buffer = state.buffer.slice(0, e.from) + e.insert + state.buffer.slice(e.to);
+      },
+      // VisualEdit's: drain and lock the frame, release unlocks it.
+      beforeJoin: async () => {
+        await channel.drain(
+          (m) => {
+            if (m.lock) frame.locked = true;
+            deliver({ type: "flushed", id: m.id });
+          },
+          () => false,
+          true,
+        );
+        return () => {
+          frame.locked = false;
+          frame.unlocks++;
+        };
+      },
+    });
+    try {
+      // The user's last edit is on its way from the frame...
+      deliver({ type: "patch", text: room === "merges" ? "a\nb\nc\nmine\n" : "a\nMINE\nc\n" });
+      // ...when the room's document arrives, with a peer's edit in it.
+      const sock = { destroy() {} };
+      const c = file.collab as unknown as { ws: unknown; onStatus: (s: string) => void; onReady: () => void };
+      c.ws = sock;
+      const peer = room === "merges" ? "peer\na\nb\nc\n" : "a\nPEER\nc\n";
+      file.collab.doc.transact(() => file.collab.text.insert(0, peer), sock);
+      c.onStatus("live");
+      c.onReady();
+      await waitFor(() => assert.equal(ready.length, 1));
+
+      if (room === "merges") {
+        assert.equal(frame.readAt, "a\nb\nc\nmine\n"); // read after the patch
+        assert.equal(file.collab.text.toString(), "peer\na\nb\nc\nmine\n");
+        same(puts, []);
+      } else {
+        // The same line two ways: the patched buffer is the conflict copy.
+        assert.equal(puts.length, 1);
+        assert.ok(puts[0].url.includes("page.html.bdrive-conflict-tester-"));
+        assert.equal(puts[0].body, "a\nMINE\nc\n");
+        assert.equal(file.collab.text.toString(), "a\nPEER\nc\n");
+      }
+      same(posts, []); // the join, not a checkpoint, handed the buffer over
+      assert.equal(frame.locked, false);
+      assert.equal(frame.unlocks, 1);
+    } finally {
+      channel.close();
+      file.destroy();
+      connect.mock.restore();
+      await settle();
+    }
+  });
+}
diff --git a/internal/webapp/static/assets/Editor-DYseo8Gn.js b/internal/webapp/static/assets/Editor-cr2ybdrO.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-DYseo8Gn.js
rename to internal/webapp/static/assets/Editor-cr2ybdrO.js
index 8495e821..91c178a5 100644
--- a/internal/webapp/static/assets/Editor-DYseo8Gn.js
+++ b/internal/webapp/static/assets/Editor-cr2ybdrO.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-YxeGfSng.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CM4z2OLg.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BXWhn62d.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-Mmk-VhrH.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-DWsPYvxy.js b/internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
deleted file mode 100644
index ec8f4d47..00000000
--- a/internal/webapp/static/assets/VisualEdit-DWsPYvxy.js
+++ /dev/null
@@ -1 +0,0 @@
-import{r as c,j as E,w as we,a as be}from"./index-YxeGfSng.js";import{o as ve,D as Te,c as L,a as G,m as ce,d as le}from"./sharedfile-CM4z2OLg.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Se=50;function Re(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,A=!1){if(await W(),x||j())return;const b=++f;let v;const q=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},Se)});try{d(A?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await q}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function ke(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function Ee(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Fe({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:A,onConflictCopy:b,baseSha:v,onSaved:q,onWriting:M,onRendered:J,handle:D}){const T=c.useRef(null),[K,de]=c.useState(null),[ue,Q]=c.useState(!1),[fe,U]=c.useState(!1),X=c.useRef(0),[Z,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:A,onSaved:q,onWriting:M,onRendered:J,onConflictCopy:b};const I=c.useRef(x),H=c.useRef(W);H.current=W;const $=c.useRef(v);$.current=v;const B=c.useRef(null);return c.useEffect(()=>{B.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,P=!1,r=null,m;const xe=700;Q(!1),U(!1);const he=setTimeout(()=>{!y&&X.current<1&&(X.current++,S(e=>e+1))},11e3),pe=setTimeout(()=>U(!0),24e3),s=B.current=ve({apiBase:u,path:f,seed:I.current,baseSha:$.current,who:H.current?.name,me:H.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>be(f,e),onShrinkWithdrawn:we,onReady:()=>{if(clearTimeout(m),m=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),i=s.collab.text.toString();if(y&&t===i)for(const[o,n]of g){const p=L(n.from,e),C=L(n.to,e);p&&C&&g.set(o,{from:G(s.collab.text,p.index),to:G(s.collab.text,C.index),span:n.span,orig:n.orig})}else g.clear(),y=!1,t!==i&&S(o=>o+1);e.destroy()}P=!0,k()},onSolo:()=>{s.collab.text.length||s.collab.text.insert(0,I.current),P=!0,k()},onStalled:()=>{P||r||(r=new Te,r.getText("body").insert(0,I.current),P=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>r?r.getText("body").toString():I.current,soloApply:({from:e,to:t,insert:i})=>{r&&r.transact(()=>{const o=r.getText("body");t>e&&o.delete(e,t-e),i&&o.insert(e,i)})}}),_=Re();let O=!1;const me=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let o=!1;const n=()=>{o=!0};t.addEventListener("load",n);try{await _.drain(p=>i.postMessage(p,"*"),()=>!O||o||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0};let ee=null;const te={...s,saveNow:()=>ee??=ke(()=>me(!0),()=>s.saveNow(),()=>T.current?.contentWindow?.postMessage({type:"bd-edit:unlock"},"*")).finally(()=>{ee=null})};D&&(D.current=te);const g=new Map,ne=e=>e.start+","+e.end,k=async()=>{if(y||!R||!P)return;const e=r?r.getText("body"):s.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await Ee(t);if(i!==null?i!==re:V>=0&&t.length!==V){R=null,S(n=>n+1);return}g.clear();for(const n of R)g.set(ne(n),{from:G(e,n.start),to:G(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});y=!0,Q(!0),h.current.onRendered?.()};let re="",V=-1,y=!1;const ge=async e=>{if(e.type==="bd-edit:flushed"){_.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){de("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,re=e.hash,V=e.len,O=!0,await k();return}if(e.type!=="bd-edit:patch")return;y||await k();const t=g.get(ne(e));if(!t)return;if(r){const l=L(t.from,r),F=L(t.to,r);if(!l||!F||l.index>F.index)return;const N=r.getText("body"),ye=F.index-l.index;if(l.index===0&&F.index===N.length&&t.spant.span*4+256){g.clear(),y=!1,S(w=>w+1);return}const z=N.toString().slice(l.index,F.index),ae=ce(t.orig,z,e.html);if(t.orig=e.html,z===ae)return;r.transact(()=>{for(const w of le(z,ae))w.deleteCount>0&&N.delete(l.index+w.index,w.deleteCount),w.insertText&&N.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{s.saveNow()},xe);return}const i=s.collab.doc,o=L(t.from,i),n=L(t.to,i);if(!o||!n||o.index>n.index)return;const p=s.collab.text,C=n.index-o.index;if(o.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),g.clear(),y=!1,S(l=>l+1);return}const Y=p.toString().slice(o.index,n.index),ie=ce(t.orig,Y,e.html);t.orig=e.html,Y!==ie&&s.collab.applySplices(le(Y,ie).map(l=>({...l,index:l.index+o.index})))},oe=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||_.enqueue(()=>ge(t))},se=()=>{k()};return s.collab.text.observe(se),window.addEventListener("message",oe),()=>{D?.current===te&&(D.current=null),O=!1,_.close(),clearTimeout(he),clearTimeout(pe),clearTimeout(m),s.collab.text.unobserve(se),setTimeout(()=>{window.removeEventListener("message",oe),clearTimeout(m),s.destroy(),r?.destroy()},300)}},[u,f,Z]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),fe&&!ue&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},Z)]})}export{Fe as VisualEdit};
diff --git a/internal/webapp/static/assets/VisualEdit-DxYGQmno.js b/internal/webapp/static/assets/VisualEdit-DxYGQmno.js
new file mode 100644
index 00000000..207e2efa
--- /dev/null
+++ b/internal/webapp/static/assets/VisualEdit-DxYGQmno.js
@@ -0,0 +1 @@
+import{r as c,j as E,w as ve,a as Te}from"./index-BXWhn62d.js";import{o as Se,D as Re,c as L,a as H,m as de,d as ue}from"./sharedfile-Mmk-VhrH.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const ke=50;function Ee(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,q=!1){if(await W(),x||j())return;const b=++f;let v;const D=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},ke)});try{d(q?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await D}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function Le(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function We(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ae({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:q,onConflictCopy:b,baseSha:v,onSaved:D,onWriting:M,onRendered:K,handle:I}){const T=c.useRef(null),[Q,fe]=c.useState(null),[xe,U]=c.useState(!1),[he,X]=c.useState(!1),Z=c.useRef(0),[$,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:q,onSaved:D,onWriting:M,onRendered:K,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:q,onSaved:D,onWriting:M,onRendered:K,onConflictCopy:b};const _=c.useRef(x),O=c.useRef(W);O.current=W;const B=c.useRef(v);B.current=v;const ee=c.useRef(null);return c.useEffect(()=>{ee.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,F=!1,o=null,m;const pe=700;U(!1),X(!1);const me=setTimeout(()=>{!g&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),ye=setTimeout(()=>X(!0),24e3),G=Ee();let J=!1;const ge=async e=>{const t=T.current,s=t?.contentWindow;if(!t||!s)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await G.drain(p=>s.postMessage(p,"*"),()=>!J||r||T.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0},P=new Map,te=async()=>{const e=T.current?.contentWindow;if(!e)return()=>{};P.set(e,(P.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const r=(P.get(e)??1)-1;if(r>0){P.set(e,r);return}P.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ge(!0)}catch(r){throw s(),r}return s},i=ee.current=Se({apiBase:u,path:f,seed:_.current,baseSha:B.current,who:O.current?.name,me:O.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>Te(f,e),onShrinkWithdrawn:ve,beforeJoin:async()=>o?te():()=>{},onReady:()=>{if(clearTimeout(m),m=void 0,o){const e=o;o=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(g&&t===s)for(const[r,n]of y){const p=L(n.from,e),C=L(n.to,e);p&&C&&y.set(r,{from:H(i.collab.text,p.index),to:H(i.collab.text,C.index),span:n.span,orig:n.orig})}else y.clear(),g=!1,t!==s&&S(r=>r+1);e.destroy()}F=!0,k()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,_.current),F=!0,k()},onStalled:()=>{F||o||(o=new Re,o.getText("body").insert(0,_.current),F=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():_.current,soloApply:({from:e,to:t,insert:s})=>{o&&o.transact(()=>{const r=o.getText("body");t>e&&r.delete(e,t-e),s&&r.insert(e,s)})}});let ne=null;const re={...i,saveNow:()=>{let e=()=>{};return ne??=Le(async()=>{e=await te()},()=>i.saveNow(),()=>e()).finally(()=>{ne=null})}};I&&(I.current=re);const y=new Map,oe=e=>e.start+","+e.end,k=async()=>{if(g||!R||!F)return;const e=o?o.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const s=await We(t);if(s!==null?s!==se:V>=0&&t.length!==V){R=null,S(n=>n+1);return}y.clear();for(const n of R)y.set(oe(n),{from:H(e,n.start),to:H(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});g=!0,U(!0),h.current.onRendered?.()};let se="",V=-1,g=!1;const we=async e=>{if(e.type==="bd-edit:flushed"){G.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){fe("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,se=e.hash,V=e.len,J=!0,await k();return}if(e.type!=="bd-edit:patch")return;g||await k();const t=y.get(oe(e));if(!t)return;if(o){const l=L(t.from,o),N=L(t.to,o);if(!l||!N||l.index>N.index)return;const A=o.getText("body"),be=N.index-l.index;if(l.index===0&&N.index===A.length&&t.spant.span*4+256){y.clear(),g=!1,S(w=>w+1);return}const z=A.toString().slice(l.index,N.index),le=de(t.orig,z,e.html);if(t.orig=e.html,z===le)return;o.transact(()=>{for(const w of ue(z,le))w.deleteCount>0&&A.delete(l.index+w.index,w.deleteCount),w.insertText&&A.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{i.saveNow()},pe);return}const s=i.collab.doc,r=L(t.from,s),n=L(t.to,s);if(!r||!n||r.index>n.index)return;const p=i.collab.text,C=n.index-r.index;if(r.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),y.clear(),g=!1,S(l=>l+1);return}const Y=p.toString().slice(r.index,n.index),ce=de(t.orig,Y,e.html);t.orig=e.html,Y!==ce&&i.collab.applySplices(ue(Y,ce).map(l=>({...l,index:l.index+r.index})))},ie=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||G.enqueue(()=>we(t))},ae=()=>{k()};return i.collab.text.observe(ae),window.addEventListener("message",ie),()=>{I?.current===re&&(I.current=null),J=!1,G.close(),clearTimeout(me),clearTimeout(ye),clearTimeout(m),i.collab.text.unobserve(ae),setTimeout(()=>{window.removeEventListener("message",ie),clearTimeout(m),i.destroy(),o?.destroy()},300)}},[u,f,$]),E.jsxs(E.Fragment,{children:[Q&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:Q}),he&&!xe&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ae as VisualEdit};
diff --git a/internal/webapp/static/assets/index-YxeGfSng.js b/internal/webapp/static/assets/index-BXWhn62d.js
similarity index 99%
rename from internal/webapp/static/assets/index-YxeGfSng.js
rename to internal/webapp/static/assets/index-BXWhn62d.js
index e804446f..974652be 100644
--- a/internal/webapp/static/assets/index-YxeGfSng.js
+++ b/internal/webapp/static/assets/index-BXWhn62d.js
@@ -1,4 +1,4 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-DYseo8Gn.js","assets/sharedfile-CM4z2OLg.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DWsPYvxy.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-cr2ybdrO.js","assets/sharedfile-Mmk-VhrH.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DxYGQmno.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-DYseo8Gn.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DWsPYvxy.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-cr2ybdrO.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DxYGQmno.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
 `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
 `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
 `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-CM4z2OLg.js b/internal/webapp/static/assets/sharedfile-Mmk-VhrH.js
similarity index 65%
rename from internal/webapp/static/assets/sharedfile-CM4z2OLg.js
rename to internal/webapp/static/assets/sharedfile-Mmk-VhrH.js
index a8cb1bad..9b6ff27e 100644
--- a/internal/webapp/static/assets/sharedfile-CM4z2OLg.js
+++ b/internal/webapp/static/assets/sharedfile-Mmk-VhrH.js
@@ -1,11 +1,11 @@
-import{H as nt,h as En,i as Pt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-YxeGfSng.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Js=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Xe=32,Nt=64,at=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rKe.encode(e),dl=Ke?fl:ul;let ze=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ze&&ze.decode(new Uint8Array).length===1&&(ze=null);const gl=(e,t)=>nl(t,()=>e).join("");class ln{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Q=()=>new ln,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,at|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?at:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?at:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Js(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},P=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Qe=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new ln,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new ln,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new ln;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},K=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&at)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>ze.decode(K(e)),Yt=ze?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),tn=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[tn]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Pl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Jl=e=>{for(const t in e)return!1;return!0},cn=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&cn(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[tn]!=null)return e[tn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Pr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
-`)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[tn]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?cn(e,(n,s)=>Us(n,t[s])):!1;class st{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[tn](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Jr(t,this),t}expect(t){return Jr(t,this),t}}class tr extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends st{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ht()};class pc extends st{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends st{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends st{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends st{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):cn(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends st{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&cn(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends st{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&cn(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends st{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends st{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(st);class Tc extends st{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends st{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends st{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>en(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const en=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=en(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(en));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ht()},Jr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
-${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:en(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Pr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Pr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(en(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Pc=e=>{const t=Vc();for(let n=0;n(Bi(e,Pc(t)),e),lu=(e,t=[],n=[])=>Jc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Pi(e)),Wi.forEach(t=>t.print(e))},Ji=(...e)=>{console.warn(...Pi(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,h=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Ps{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const c=()=>jr(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return Ze(this.restDecoder)}readBuf(){return lc(K(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(K(t)),this.clientDecoder=new Ln(K(t)),this.leftClockDecoder=new ks(K(t)),this.rightClockDecoder=new ks(K(t)),this.infoDecoder=new Vr(K(t),Ae),this.stringDecoder=new Rl(K(t)),this.parentInfoDecoder=new Vr(K(t),Ae),this.typeRefDecoder=new Ln(K(t)),this.lenDecoder=new Ln(K(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ze(this.restDecoder)}readBuf(){return K(this.restDecoder)}readJSON(){return Ze(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,h=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const u=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(u,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),h(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)h(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),h=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,h.update])}}else l.pendingStructs=h;const u=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);u&&d?l.pendingDs=Fn([u,d]):l.pendingDs=u||d}else l.pendingDs=u;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===hn)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new hn),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ht()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,h=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),u=a.item;if(!(u instanceof v))return null;if(c=u.parent,c._item===null||!c._item.deleted){h=u.deleted||!u.countable?0:a.diff+(l>=0?0:1);let f=u.left;for(;f!==null;)!f.deleted&&f.countable&&(h+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ht();l>=0?h=c._length:h=0}return Ca(c,h,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!an(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ht()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Jn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let h=Dt(i,l.clock),a=i[h];h{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Js(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,h=r[c];c>0&&h.id.clock>=o.clock;h=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=h,a._path=null}),c.sort((a,u)=>a.path.length-u.path.length),l.push(()=>{so(h._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,u)=>{const f=n.beforeState.get(u)||0;if(f!==a){const d=r.clients.get(u),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:f}=o[a].id,d=r.clients.get(u),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new hn;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:h}=n;(l.size>0||h.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:h},s,n]),h.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,h=t.pop(),a=new Set,u=[];let f=!1;Te(l,h.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&u.push(d)}}),Te(l,h.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!an(h.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,h.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=u.length-1;d>=0;d--){const p=u[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?h:null}l.changed.forEach((c,h)=>{c.has(null)&&h._searchMarker&&(h._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Ps{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const h=this.undoing,a=this.redoing,u=h?this.redoStack:this.undoStack;h?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,I=b-S;I>0&&nn(f,w,S,I)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!h&&!a){const b=u[u.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else u.push(new Ra(c.deleteSet,f)),p=!0;!h&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:u[u.length-1],origin:c.origin,type:h?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Ji("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,hn),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==u||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Jt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===u&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Jt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Jt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),h=Ms(c);return Ne(o,h),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,u=a.id.client,f=r.get(u)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Jt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Jt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const h=or(l);return Ne(i,h),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=Q(),e.written=0)},Jt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let h=i.curr;h!==null;h=i.next())Jt(l,t(h),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,hn),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return an(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let h=n._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=h.length,r.add(h)):this.adds(h)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(h.content.getContent()),s.add(h)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=h.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Z=()=>{Ji("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Z(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Z();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Z();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return rn(e,(s,r)=>{n.push(t(s,r,e))}),n},Pa=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Z();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let h=[];const a=()=>{h.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(h)),r.integrate(e,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new un(new Uint8Array(u))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(u)),r.integrate(e,0);break;default:if(u instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(u)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&sn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&sn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new un(s);break;case he:l=new fn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Z(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Z();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Z(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Ja(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){rn(this,t)}[Symbol.iterator](){return Pa(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Z();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Z(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,h=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,h,h&&h.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],h=n.currentAttributes.get(l)??null;if(!Wt(h,c)){o.set(l,h);const{left:a,right:u}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:h,right:a,index:u}=n;t._searchMarker&&sn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=u,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:h}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,h))l.delete(c);else{if(s===0)break t;l.set(c,h)}n.right.delete(e)}else n.currentAttributes.set(c,h);break}default:s0){let c="";for(;s>0;s--)c+=`
-`;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const h=i.content;o.set(h.key,h)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const h=t.content;if(h.constructor===Y){const{key:a,value:u}=h,f=s.get(a)??null;(o.get(a)!==h||f===u)&&(t.delete(e),l++,!c&&(r.get(a)??null)===u&&f!==u&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,h)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let h="",a=0,u=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":u>0&&(d={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(d={insert:h},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),h="";break;case"retain":a>0&&(d={retain:a},Jl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",h=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),h+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Z(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Z();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i0)&&Es(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ni(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&si(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Z();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function h(){if(l.length>0){const u={};let f=!1;i.forEach((p,k)=>{f=!0,u[k]=p});const d={insert:l};f&&(d.attributes=u),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case At:{const u=i.get("ychange");t!==void 0&&!we(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",c.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),l+=c.content.str;break}case xt:case ue:{h();const u={insert:c.content.getContent()[0]};if(i.size>0){const f={};u.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(u);break}case Y:we(c,t)&&(h(),$e(i,c.content));break}c=c.right}h()};return t||n?M(o,u=>{t&&vs(u,t),n&&vs(u,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),Es(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);Es(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{si(r,An(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!1);o.right!==null&&ni(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return dr(this,t)}getAttributes(){return bo(this)}_write(t){t.writeTypeRef(kh)}}const th=e=>new Oe;class Cs{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Z()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Z(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Cs(this,t)}querySelector(t){t=t.toUpperCase();const s=new Cs(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Cs(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){is(this,t,new sh(this,n,t))}toString(){return wo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),rn(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Bn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Ct("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return po(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return mo(this,t)}slice(t=0,n=this.length){return go(this,t,n)}forEach(t){rn(this,t)}_write(t){t.writeTypeRef(bh)}}const eh=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Hl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return dr(this,t)}hasAttribute(t){return _o(this,t)}getAttributes(t){return t?Wa(this,t):bo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return rn(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(Sh),t.writeKey(this.nodeName)}}const nh=e=>new Re(e.readKey());class sh extends ss{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class jn extends Le{constructor(t){super(),this.hookName=t}_copy(){return new jn(this.hookName)}clone(){const t=new jn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(_h),t.writeKey(this.hookName)}}const rh=e=>new jn(e.readKey());class Hn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Hn}clone(){const t=new Hn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Eh)}}const ih=e=>new Hn;class gr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw yt()}mergeWith(t){return!1}write(t,n,s){throw yt()}integrate(t,n){throw yt()}}const oh=0;class pt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),lo(t.doc.store,this)}write(t,n){t.writeInfo(oh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class un{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new un(this.content)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const lh=e=>new un(e.readBuf());class on{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new on(this.len)}splice(t){const n=new on(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){nn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ch=e=>new on(e.readLen()),Io=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class fn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new fn(Io(this.doc.guid,this.opts))}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const ah=e=>new fn(Io(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const hh=e=>new ue(e.readJSON());class Y{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Y(this.key,this.value)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const uh=e=>new Y(e.readKey(),e.readJSON());class Pn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Pn(this.arr)}splice(t){const n=new Pn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const ph=e=>new At(e.readString()),wh=[qa,Ga,th,nh,eh,rh,ih],mh=0,yh=1,kh=2,Sh=3,bh=4,_h=5,Eh=6;class xt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new xt(this.type._copy())}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Ch=e=>new xt(wh[e.readTypeRef()](e)),Fs=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},pr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Jn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ri=(e,t)=>Hs(e,n=>an(n.deletions,t)),To=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,h=t.redone;if(h!==null)return rt(e,h);let a=t.parent._item,u=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||To(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=rt(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(u=t.left,f=t;u!==null;){let w=u;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){u=w;break}u=u.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(u=t;u!==null&&u.right!==null&&(u.right.redone||an(s,u.right.id)||ri(i.undoStack,u.right.id)||ri(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=rt(e,u.redone);if(u&&u.right!==null)return null}else u=d._map.get(t.parentSub)||null;u!==null&&u.parent._item!==a&&(u=d._map.get(t.parentSub)||null)}const p=J(l,c),k=D(c,p),b=new v(k,u,u&&u.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=k,pr(b,!0),b.integrate(e,0),b};class v extends gr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Ur:0}set marker(t){(this.info&ms)>0!==t&&(this.info^=ms)}get marker(){return(this.info&ms)>0}get keep(){return(this.info&Rr)>0}set keep(t){this.keep!==t&&(this.info^=Rr)}get countable(){return(this.info&Ur)>0}get deleted(){return(this.info&ws)>0}set deleted(t){this.deleted!==t&&(this.info^=ws)}markDeleted(){this.info|=ws}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=J(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=J(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=J(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pt||this.right&&this.right.constructor===pt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===pt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Gr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),nn(t.deleteSet,this.id.client,this.id.clock,this.length),Kr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw ht();this.content.gc(t),n?Ta(t,this,new pt(this.id,this.length)):this.content=new on(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&qn|(s===null?0:at)|(r===null?0:Nt)|(i===null?0:Xe);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const h=ro(l);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):ht();i!==null&&t.writeString(i)}this.content.write(t,n)}}const xo=(e,t)=>Dh[t&qn](e),Dh=[()=>{ht()},ch,fh,lh,ph,hh,uh,Ch,gh,ah,()=>{ht()}],Ah=10;class wt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){ht()}write(t,n){t.writeInfo(Ah),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";Lo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lo[Oo]=!0;const Ro=new Map;class Ih{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:oc(n.newValue||"")}),$l(this._onChange)}postMessage(t){wi.setItem(this.room,ic(tc(t)))}close(){Fl(this._onChange)}}const Th=typeof BroadcastChannel>"u"?Ih:BroadcastChannel,wr=e=>It(Ro,e,()=>{const t=zt(),n=new Th(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),xh=(e,t)=>(wr(e).subs.add(t),t),Lh=(e,t)=>{const n=wr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Ro.delete(e)),s},me=(e,t,n=null)=>{const s=wr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Uo=0,mr=1,Mo=2,Bs=(e,t)=>{_(e,Uo);const n=Sa(t);P(e,n)},vo=(e,t,n)=>{_(e,mr),P(e,to(t,n))},Oh=(e,t,n)=>vo(t,n,K(e)),No=(e,t,n,s)=>{try{Zi(t,K(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Rh=(e,t)=>{_(e,Mo),P(e,t)},Uh=No,Mh=(e,t,n,s,r)=>{const i=C(e);switch(i){case Uo:Oh(e,t,n);break;case mr:No(e,n,s,r);break;case Mo:Uh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},vh=0,Nh=(e,t,n)=>{C(e)===vh&&n(t,Yt(e))},Ds=3e4;class $o extends sl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Gt();this.getLocalState()!==null&&Ds/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Ds<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&yr(this,s,"timeout")},kt(Ds/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Gt()});const o=[],l=[],c=[],h=[];t===null?h.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||h.length>0)&&this.emit("change",[{added:o,updated:c,removed:h},"local"]),this.emit("update",[{added:o,updated:l,removed:h},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const yr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Ge=(e,t,n=e.states)=>{const s=t.length,r=Q();_(r,s);for(let i=0;i{const s=Kt(t),r=Gt(),i=[],o=[],l=[],c=[],h=C(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Fh=e=>Pl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,Fo=3,Ce=1,Bh=2,dn=[];dn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Mh(t,e,n.doc,n);s&&i===mr&&!n.synced&&(n.synced=!0)};dn[Fo]=(e,t,n,s,r)=>{_(e,Ce),P(e,Ge(n.awareness,Array.from(n.awareness.getStates().keys())))};dn[Ce]=(e,t,n,s,r)=>{$h(n.awareness,K(t),n)};dn[Bh]=(e,t,n,s,r)=>{Nh(t,n.doc,(i,o)=>Vh(n,o))};const ii=3e4,Vh=(e,t)=>console.warn(`Permission denied to access ${e.url}.
-${t}`),Bo=(e,t,n)=>{const s=Kt(t),r=Q(),i=C(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},jh=e=>!(e.code>=4400&&e.code<4500),Vs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,yr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Vo,Js(rl(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Vo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt();const s=Bo(e,new Uint8Array(n.data),!0);Ws(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Vs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=Q();if(_(n,ne),Bs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=Q();_(s,Ce),P(s,Ge(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},As=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Hh extends Ps{constructor(t,n,s,{connect:r=!0,awareness:i=new $o(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:h=-1,maxBackoffTime:a=2500,disableBc:u=!1,shouldReconnect:f=jh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=dn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,h>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=Q();_(d,ne),Bs(d,s),this.ws.send(B(d))}},h)),this._bcSubscriber=(d,p)=>{if(p!==this){const k=Bo(this,new Uint8Array(d),!1);Ws(k)>1&&me(this.bcChannel,B(k),this)}},this._updateHandler=(d,p)=>{if(p!==this){const k=Q();_(k,ne),Rh(k,d),As(this,B(k))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:k},b)=>{const w=d.concat(p).concat(k),S=Q();_(S,Ce),P(S,Ge(i,w)),As(this,B(S))},this._exitHandler=()=>{yr(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ii{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Aa(_a(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Hh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Jh)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=to(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===oi||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?h[w-1]:null,I=new Int32Array(2*w+1);for(let L=-w;L<=w;L+=2){let R;w===0?R=0:L===-w||L!==w&&S[L-1+w-1]=r&&N>=i){a=w;break}}h.push(I)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const u=[];let f=r,d=i;for(let w=a;w>0;w--){const S=h[w-1],I=f-d,L=I===-w||I!==w&&S[I-1+w-1]F&&d>Qt;)f--,d--,u.push(f,d);f=R,d=N}for(;f>0&&d>0;)f--,d--,u.push(f,d);const p=[];let k=0,b=0;for(let w=u.length-2;w>=0;w-=2){const S=u[w],I=u[w+1];(S>k||I>b)&&p.push({aS:n+k,aE:n+S,bS:n+b,bE:n+I}),k=S+1,b=I+1}return(ki.startsWith(o)&&(o===""||o.endsWith(`
+import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-BXWhn62d.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+`)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
+${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=`
+`;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i0)&&Es(s,this,r,l,o.attributes||{})}else o.retain!==void 0?ni(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&si(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,s){this.doc??Q();const r=[],i=new Map,o=this.doc;let l="",c=this._start;function u(){if(l.length>0){const h={};let f=!1;i.forEach((p,k)=>{f=!0,h[k]=p});const d={insert:l};f&&(d.attributes=h),r.push(d),l=""}}const a=()=>{for(;c!==null;){if(we(c,t)||n!==void 0&&we(c,n))switch(c.content.constructor){case At:{const h=i.get("ychange");t!==void 0&&!we(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!we(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(u(),i.delete("ychange")),l+=c.content.str;break}case xt:case ue:{u();const h={insert:c.content.getContent()[0]};if(i.size>0){const f={};h.attributes=f,i.forEach((d,p)=>{f[p]=d})}r.push(h);break}case Y:we(c,t)&&(u(),$e(i,c.content));break}c=c.right}u()};return t||n?M(o,h=>{t&&vs(h,t),n&&vs(h,n),a()},"cleanup"):a(),r}insert(t,n,s){if(n.length<=0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);s||(s={},o.currentAttributes.forEach((l,c)=>{s[c]=l})),Es(i,this,o,n,s)}):this._pending.push(()=>this.insert(t,n,s))}insertEmbed(t,n,s){const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!s);Es(i,this,o,n,s||{})}):this._pending.push(()=>this.insertEmbed(t,n,s||{}))}delete(t,n){if(n===0)return;const s=this.doc;s!==null?M(s,r=>{si(r,An(r,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,s){if(n===0)return;const r=this.doc;r!==null?M(r,i=>{const o=An(i,this,t,!1);o.right!==null&&ni(i,this,o,n,s)}):this._pending.push(()=>this.format(t,n,s))}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return dr(this,t)}getAttributes(){return bo(this)}_write(t){t.writeTypeRef(kh)}}const th=e=>new Oe;class Cs{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Q()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===Re||n.constructor===le)&&n._start!==null)t=n._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class le extends z{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new le}clone(){const t=new le;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new Cs(this,t)}querySelector(t){t=t.toUpperCase();const s=new Cs(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),$t(new Cs(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){is(this,t,new sh(this,n,t))}toString(){return wo(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),on(this,i=>{r.insertBefore(i.toDOM(t,n,s),null)}),r}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)M(this.doc,s=>{const r=t&&t instanceof z?t._item:t;Bn(s,this,r,n)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw Ct("Reference item not found");s.splice(r,0,...n)}}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return po(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return mo(this,t)}slice(t=0,n=this.length){return go(this,t,n)}forEach(t){on(this,t)}_write(t){t.writeTypeRef(bh)}}const eh=e=>new le;class Re extends le{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Re(this.nodeName)}clone(){const t=new Re(this.nodeName),n=this.getAttributes();return Hl(n,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof z?s.clone():s)),t}toString(){const t=this.getAttributes(),n=[],s=[];for(const l in t)s.push(l);s.sort();const r=s.length;for(let l=0;l0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return dr(this,t)}hasAttribute(t){return _o(this,t)}getAttributes(t){return t?Wa(this,t):bo(this)}toDOM(t=document,n={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const l=i[o];typeof l=="string"&&r.setAttribute(o,l)}return on(this,o=>{r.appendChild(o.toDOM(t,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(Sh),t.writeKey(this.nodeName)}}const nh=e=>new Re(e.readKey());class sh extends ss{constructor(t,n,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class jn extends Le{constructor(t){super(),this.hookName=t}_copy(){return new jn(this.hookName)}clone(){const t=new jn(this.hookName);return this.forEach((n,s)=>{t.set(s,n)}),t}toDOM(t=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(_h),t.writeKey(this.hookName)}}const rh=e=>new jn(e.readKey());class Hn extends Oe{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Hn}clone(){const t=new Hn;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const n=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,l)=>o.keyr.nodeName=0;r--)s+=``;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Eh)}}const ih=e=>new Hn;class gr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw yt()}mergeWith(t){return!1}write(t,n,s){throw yt()}integrate(t,n){throw yt()}}const oh=0;class pt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),lo(t.doc.store,this)}write(t,n){t.writeInfo(oh),t.writeLen(this.length-n)}getMissing(t,n){return null}}class fn{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new fn(this.content)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const lh=e=>new fn(e.readBuf());class ln{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ln(this.len)}splice(t){const n=new ln(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){sn(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ch=e=>new ln(e.readLen()),Io=(e,t)=>new he({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class dn{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new dn(Io(this.doc.guid,this.opts))}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const ah=e=>new dn(Io(e.readString(),e.readAny()));class ue{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ue(this.embed)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const hh=e=>new ue(e.readJSON());class Y{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Y(this.key,this.value)}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const uh=e=>new Y(e.readKey(),e.readJSON());class Jn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Jn(this.arr)}splice(t){const n=new Jn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const s=this.arr.length;t.writeLen(s-n);for(let r=n;r{const t=e.readLen(),n=[];for(let s=0;s{const t=e.readLen(),n=[];for(let s=0;s=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const ph=e=>new At(e.readString()),wh=[qa,Ga,th,nh,eh,rh,ih],mh=0,yh=1,kh=2,Sh=3,bh=4,_h=5,Eh=6;class xt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new xt(this.type._copy())}splice(t){throw yt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Ch=e=>new xt(wh[e.readTypeRef()](e)),Fs=(e,t)=>{let n=t,s=0,r;do s>0&&(n=D(n.client,n.clock+s)),r=_e(e,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof v);return{item:r,diff:s}},pr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Pn=(e,t,n)=>{const{client:s,clock:r}=t.id,i=new v(D(s,r+n),t,D(s,r+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=D(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i},ri=(e,t)=>Hs(e,n=>hn(n.deletions,t)),To=(e,t,n,s,r,i)=>{const o=e.doc,l=o.store,c=o.clientID,u=t.redone;if(u!==null)return rt(e,u);let a=t.parent._item,h=null,f;if(a!==null&&a.deleted===!0){if(a.redone===null&&(!n.has(a)||To(e,a,n,s,r,i)===null))return null;for(;a.redone!==null;)a=rt(e,a.redone)}const d=a===null?t.parent:a.content.type;if(t.parentSub===null){for(h=t.left,f=t;h!==null;){let w=h;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){h=w;break}h=h.left}for(;f!==null;){let w=f;for(;w!==null&&w.parent._item!==a;)w=w.redone===null?null:rt(e,w.redone);if(w!==null&&w.parent._item===a){f=w;break}f=f.right}}else{if(f=null,t.right&&!r){for(h=t;h!==null&&h.right!==null&&(h.right.redone||hn(s,h.right.id)||ri(i.undoStack,h.right.id)||ri(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=rt(e,h.redone);if(h&&h.right!==null)return null}else h=d._map.get(t.parentSub)||null;h!==null&&h.parent._item!==a&&(h=d._map.get(t.parentSub)||null)}const p=J(l,c),k=D(c,p),b=new v(k,h,h&&h.lastId,f,f&&f.id,d,t.parentSub,t.content.copy());return t.redone=k,pr(b,!0),b.integrate(e,0),b};class v extends gr{constructor(t,n,s,r,i,o,l,c){super(t,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Ur:0}set marker(t){(this.info&ms)>0!==t&&(this.info^=ms)}get marker(){return(this.info&ms)>0}get keep(){return(this.info&Rr)>0}set keep(t){this.keep!==t&&(this.info^=Rr)}get countable(){return(this.info&Ur)>0}get deleted(){return(this.info&ws)>0}set deleted(t){this.deleted!==t&&(this.info^=ws)}markDeleted(){this.info|=ws}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=J(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=J(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=J(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gr(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pt||this.right&&this.right.constructor===pt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===v?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===v&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){const s=_e(n,this.parent);s.constructor===pt?this.parent=null:this.parent=s.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=Gr(t,t.doc.store,D(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),ye(this.origin,r.origin)){if(r.id.client{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),sn(t.deleteSet,this.id.client,this.id.clock,this.length),Kr(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw ut();this.content.gc(t),n?Ta(t,this,new pt(this.id,this.length)):this.content=new ln(this.length)}write(t,n){const s=n>0?D(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&qn|(s===null?0:ht)|(r===null?0:Nt)|(i===null?0:Ke);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const u=ro(l);t.writeParentInfo(!0),t.writeString(u)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===be?(t.writeParentInfo(!1),t.writeLeftID(l)):ut();i!==null&&t.writeString(i)}this.content.write(t,n)}}const xo=(e,t)=>Dh[t&qn](e),Dh=[()=>{ut()},ch,fh,lh,ph,hh,uh,Ch,gh,ah,()=>{ut()}],Ah=10;class wt extends gr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){ut()}write(t,n){t.writeInfo(Ah),_(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Oo="__ $YJS$ __";Lo[Oo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lo[Oo]=!0;const Ro=new Map;class Ih{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:oc(n.newValue||"")}),$l(this._onChange)}postMessage(t){wi.setItem(this.room,ic(tc(t)))}close(){Fl(this._onChange)}}const Th=typeof BroadcastChannel>"u"?Ih:BroadcastChannel,wr=e=>It(Ro,e,()=>{const t=zt(),n=new Th(e);return n.onmessage=s=>t.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:t}}),xh=(e,t)=>(wr(e).subs.add(t),t),Lh=(e,t)=>{const n=wr(e),s=n.subs.delete(t);return s&&n.subs.size===0&&(n.bc.close(),Ro.delete(e)),s},me=(e,t,n=null)=>{const s=wr(e);s.bc.postMessage(t),s.subs.forEach(r=>r(t,n))},Uo=0,mr=1,Mo=2,Bs=(e,t)=>{_(e,Uo);const n=Sa(t);H(e,n)},vo=(e,t,n)=>{_(e,mr),H(e,to(t,n))},Oh=(e,t,n)=>vo(t,n,X(e)),No=(e,t,n,s)=>{try{Zi(t,X(e),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Rh=(e,t)=>{_(e,Mo),H(e,t)},Uh=No,Mh=(e,t,n,s,r)=>{const i=C(e);switch(i){case Uo:Oh(e,t,n);break;case mr:No(e,n,s,r);break;case Mo:Uh(e,n,s,r);break;default:throw new Error("Unknown message type")}return i},vh=0,Nh=(e,t,n)=>{C(e)===vh&&n(t,Yt(e))},Ds=3e4;class $o extends sl{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Gt();this.getLocalState()!==null&&Ds/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Ds<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&yr(this,s,"timeout")},kt(Ds/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:r,lastUpdated:Gt()});const o=[],l=[],c=[],u=[];t===null?u.push(n):i==null?t!=null&&o.push(n):(l.push(n),ke(i,t)||c.push(n)),(o.length>0||c.length>0||u.length>0)&&this.emit("change",[{added:o,updated:c,removed:u},"local"]),this.emit("update",[{added:o,updated:l,removed:u},"local"])}setLocalStateField(t,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[t]:n})}getStates(){return this.states}}const yr=(e,t,n)=>{const s=[];for(let r=0;r0&&(e.emit("change",[{added:[],updated:[],removed:s},n]),e.emit("update",[{added:[],updated:[],removed:s},n]))},Xe=(e,t,n=e.states)=>{const s=t.length,r=K();_(r,s);for(let i=0;i{const s=Kt(t),r=Gt(),i=[],o=[],l=[],c=[],u=C(s);for(let a=0;a0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])},Fh=e=>Jl(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&"),ne=0,Fo=3,Ce=1,Bh=2,gn=[];gn[ne]=(e,t,n,s,r)=>{_(e,ne);const i=Mh(t,e,n.doc,n);s&&i===mr&&!n.synced&&(n.synced=!0)};gn[Fo]=(e,t,n,s,r)=>{_(e,Ce),H(e,Xe(n.awareness,Array.from(n.awareness.getStates().keys())))};gn[Ce]=(e,t,n,s,r)=>{$h(n.awareness,X(t),n)};gn[Bh]=(e,t,n,s,r)=>{Nh(t,n.doc,(i,o)=>Vh(n,o))};const ii=3e4,Vh=(e,t)=>console.warn(`Permission denied to access ${e.url}.
+${t}`),Bo=(e,t,n)=>{const s=Kt(t),r=K(),i=C(s),o=e.messageHandlers[i];return o?o(r,s,e,n,i):console.error("Unable to compute message"),r},jh=e=>!(e.code>=4400&&e.code<4500),Vs=(e,t,n)=>{if(t!==null&&t===e.ws){e.emit("connection-close",[n,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,yr(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])),e.wsUnsuccessfulReconnects++;let s=null;n!=null&&!e.shouldReconnect(n,e)&&(e.shouldConnect=!1,s={code:n.code,reason:n.reason}),setTimeout(Vo,Ps(rl(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),s!==null&&e.emit("closed",[s,e])}},Vo=e=>{if(e.shouldConnect&&e.ws===null){const t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt();const s=Bo(e,new Uint8Array(n.data),!0);Ws(s)>1&&t.send(B(s))},t.onerror=n=>{e.ws===t&&e.emit("connection-error",[n,e])},t.onclose=n=>{Vs(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=Gt(),e.wsconnecting=!1,e.wsconnected=!0,e.emit("status",[{status:"connected"}]);const n=K();if(_(n,ne),Bs(n,e.doc),t.send(B(n)),e.awareness.getLocalState()!==null){const s=K();_(s,Ce),H(s,Xe(e.awareness,[e.doc.clientID])),t.send(B(s))}},e.emit("status",[{status:"connecting"}])}},As=(e,t)=>{const n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&me(e.bcChannel,t,e)};class Hh extends Js{constructor(t,n,s,{connect:r=!0,awareness:i=new $o(s),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:a=2500,disableBc:h=!1,shouldReconnect:f=jh}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=a,this.shouldReconnect=f,this.params=o,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=gn.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,u>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const d=K();_(d,ne),Bs(d,s),this.ws.send(B(d))}},u)),this._bcSubscriber=(d,p)=>{if(p!==this){const k=Bo(this,new Uint8Array(d),!1);Ws(k)>1&&me(this.bcChannel,B(k),this)}},this._updateHandler=(d,p)=>{if(p!==this){const k=K();_(k,ne),Rh(k,d),As(this,B(k))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:d,updated:p,removed:k},b)=>{const w=d.concat(p).concat(k),S=K();_(S,Ce),H(S,Xe(i,w)),As(this,B(S))},this._exitHandler=()=>{yr(this.awareness,[s.clientID],"app closed")},Xt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ii{if(s===this.doc.clientID)return;const r=n.cursor;if(!r?.head)return;const i=Aa(_a(r.head),this.doc);i&&t.push({name:n.user?.name??"Someone",pos:i.index})}),t}connect(){this.onStatus("connecting");const t=new URL(this.url,location.href),n=t.searchParams.get("path")??"",s=(t.protocol==="https:"?"wss://":"ws://")+t.host+t.pathname,r=new Hh(s,encodeURIComponent(n),this.doc,{params:{path:n},awareness:this.awareness,connect:!0,disableBc:!0});this.ws=r,r.on("status",i=>{this.closed||this.onStatus(i.status==="connected"?r.synced?"live":"connecting":"offline")}),r.on("sync",i=>{i&&!this.closed&&this.onStatus("live"),i&&!this.closed&&(this.reached=!0,this.onReady())}),this.stallTimer=setTimeout(()=>{this.stallTimer=null,!(this.closed||this.reached)&&this.onStalled()},Ph)}stop(){this.closed||(this.closed=!0,this.stallTimer&&clearTimeout(this.stallTimer),this.ws?.destroy(),this.ws=null,this.onStatus("solo"))}encodeState(){const t=to(this.doc);let n="";for(let s=0;s{for(const n of t)n.deleteCount&&this.text.delete(n.index,n.deleteCount),n.insertText&&this.text.insert(n.index,n.insertText)})}isRemote(t){return t===oi||this.ws!==null&&t===this.ws}applyRemoteUpdate(t){const n=atob(t),s=new Uint8Array(n.length);for(let r=0;r0?u[w-1]:null,A=new Int32Array(2*w+1);for(let O=-w;O<=w;O+=2){let U;w===0?U=0:O===-w||O!==w&&S[O-1+w-1]=r&&N>=i){a=w;break}}u.push(A)}if(a<0)return[{aS:n,aE:n+r,bS:n,bE:n+i}];const h=[];let f=r,d=i;for(let w=a;w>0;w--){const S=u[w-1],A=f-d,O=A===-w||A!==w&&S[A-1+w-1]F&&d>Qt;)f--,d--,h.push(f,d);f=U,d=N}for(;f>0&&d>0;)f--,d--,h.push(f,d);const p=[];let k=0,b=0;for(let w=h.length-2;w>=0;w-=2){const S=h[w],A=h[w+1];(S>k||A>b)&&p.push({aS:n+k,aE:n+S,bS:n+b,bE:n+A}),k=S+1,b=A+1}return(ki.startsWith(o)&&(o===""||o.endsWith(`
 `)||i[o.length]===`
-`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Gh(e,t)<=0?e+t:t+e:null}function Yn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=_t(e,s),l=_t(t,s),c=_t(n,s),h=Et(o,i),a=[...Ue(h,Et(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(h,Et(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const u=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,I)=>{let L="",R=S;for(const N of b)N.side===w&&(L+=u(o,R,N.h.aS)+u(N.toks,N.h.bS,N.h.bE),R=N.h.aE);return L+u(o,R,I)};let d="",p=0,k=0;for(;kF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const L=f(b,0,w,S),R=f(b,1,w,S);if(L===R){d+=L;continue}if(w===S){const F=Xh(L,R,s!==Is,o.length===0);if(F===null){if(!r)return null;d+=R;continue}d+=F;continue}if(s===Is)return null;const N=s===Wn?Yn(u(o,w,S),L,R,Is):Yn(u(o,w,S),L,R,s+1,r);if(N===null){if(!r)return null;d+=R;continue}d+=N}return d+u(o,p,o.length)}const se=e=>e===""||e.endsWith(`
+`);return e.length>=t.length&&r(e,t)?e:t.length>e.length&&r(t,e)?t:null}return n?Gh(e,t)<=0?e+t:t+e:null}function Yn(e,t,n,s,r=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,o=_t(e,s),l=_t(t,s),c=_t(n,s),u=Et(o,i),a=[...Ue(u,Et(l,i)).map(b=>({h:b,toks:l,side:0})),...Ue(u,Et(c,i)).map(b=>({h:b,toks:c,side:1}))];a.sort((b,w)=>b.h.aS-w.h.aS||b.h.aE-w.h.aE||b.side-w.side);const h=(b,w,S)=>b.slice(w,S).join(""),f=(b,w,S,A)=>{let O="",U=S;for(const N of b)N.side===w&&(O+=h(o,U,N.h.aS)+h(N.toks,N.h.bS,N.h.bE),U=N.h.aE);return O+h(o,U,A)};let d="",p=0,k=0;for(;kF.side)).size===1){d+=f(b,b[0].side,w,S);continue}const O=f(b,0,w,S),U=f(b,1,w,S);if(O===U){d+=O;continue}if(w===S){const F=Xh(O,U,s!==Is,o.length===0);if(F===null){if(!r)return null;d+=U;continue}d+=F;continue}if(s===Is)return null;const N=s===Wn?Yn(h(o,w,S),O,U,Is):Yn(h(o,w,S),O,U,s+1,r);if(N===null){if(!r)return null;d+=U;continue}d+=N}return d+h(o,p,o.length)}const se=e=>e===""||e.endsWith(`
 `)?e:e+`
 `;function jo(e,t,n,s){let r=t.endsWith(`
 `);return r===e.endsWith(`
@@ -13,5 +13,5 @@ ${t}`),Bo=(e,t,n)=>{const s=Kt(t),r=Q(),i=C(s),o=e.messageHandlers[i];return o?o
 `)),s===""||r===s.endsWith(`
 `)?s:r?s+`
 `:s.slice(0,-1)}function Kh(e,t,n){const s=Yn(se(e),se(t),se(n),qt);return s===null?{ok:!1}:{ok:!0,text:jo(e,t,n,s)}}function du(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Yn(se(e),se(t),se(n),qt,!0)??se(n);return jo(e,t,n,s)}function Qh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(`
-`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Zh(e,t,n,s){const r=Kh(t,n,s);return!r.ok||n===s||n===t||s===t||Qh(e,r.text)?r:{ok:!1}}function li(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,qt),i=_t(t,qt),o=h=>{const a=new Array(h.length+1);a[0]=0;for(let u=0;u0?p.charCodeAt(w-1):0;I>=55296&&I<=56319&&w--;const L=S>0?p.charCodeAt(p.length-S):0;L>=56320&&L<=57343&&S--,b+=w,p=p.slice(w,p.length-S),k=k.slice(w,k.length-S),(p.length||k.length)&&s.push({index:b,deleteCount:p.length,insertText:k}),h=f,a=d}}function In(e,t,n){const s=new Map,r=Et(_t(t,qt),s),i=Ue(Et(_t(e,qt),s),r),o=Ue(r,Et(_t(n,qt),s));for(const c of i)for(const h of o)if(c.bSc.bE):!(h.aE<=c.bS||h.aS>=c.bE))return!1}else if(h.bSc.endsWith(`
-`);return!(l(t)!==l(e)&&l(n)!==l(t))}function qe(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ci=700,pe=[2e3,4e3,8e3,15e3],ai=2e3,eu=4,nu=64,su=8,ru=32e3,iu=32;function gu(e){const t=(g,m,y)=>Zh(e.path,g,m,y);let n=e.seed,s=e.baseSha;const r=(g,m)=>{n=g,i=m,lt(m);const y=Bt.lastIndexOf(g);y>=0?Bt.splice(0,y+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const m=[];for(let y=g;y!==null&&m.length<4;y=y.prev)y.sent!==y.from&&!m.includes(y.sent)&&m.push(y.sent);return m.length?m:void 0},l=(g,m=tt)=>{const y=o(m);return i&&i===s&&n.length>ru?{base:s,text:g,...y?{prior_sent:y}:{}}:{base:s,base_text:n,text:g,...y?{prior_sent:y}:{}}};let c=!1,h=!1,a=!1,u=!1,f=!1,d=0,p=null,k=!1,b=!1,w=!1,S=null,I=null,L="",R=0;const N=(g=Date.now())=>{const m=Math.max(g,R+1e3);return R=m,Qo(e.path,e.who||"browser",new Date(m))},F=new Map;let Qt=0,St=!1,ut=null,Fe=0,os=!1,tt=null,ft=!1;const Bt=[],kr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>iu&&Bt.shift())};let Lt=!1,Be=null,Zt=0;const Ve=()=>{Lt=!1,Be=null},ls=g=>{Zt===g&&Ve()};let et=0,ot=0,gn=null,Vt=null,pn=!1,jt=null,Ot=null,je=!1,te=null,dt=null;const $=g=>e.onState?.(g),wn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ht=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let mn=null,cs=0;const He=()=>{clearTimeout(mn??void 0),mn=null},yn=g=>{if(!(g instanceof nt?g.status>=500||g.status===429:!0)||f||a)return;He();const y=pe[Math.min(cs,pe.length-1)];cs++,mn=setTimeout(()=>{mn=null,!f&&!a&&Pe()},y)},Sr=()=>{He(),cs=0},kn=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},ci)},Rt=g=>{if(f)return p=g,!0;const m=O();if(m===g)return!0;const y=li(m,g);if(Dr())return x.applySplices(y),!0;if(!e.soloApply)return!1;for(const A of y)e.soloApply({from:A.index,to:A.index+A.deleteCount,insert:A.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(k)return b?Promise.resolve():Je();if(Vt)return pn=!0,Vt;const g=(async()=>{try{for(;jt;)await jt;await Ho()}finally{Vt=null}})();return Vt=g,g},Ho=async()=>{let g=0;for(;;){if(pn=!1,V||a||w)return;const m=O();if(m===n&&!ft){$("clean");return}if($("saving"),e.onWriting?.(),St){if(S!==null&&I===m){if(await Sn(m,L)==="stop")return;continue}St=!1}const y=c||h?await Po(m):await Wo(m);if(y==="stop")return;if(y==="rebased"){if(++g>eu){await Sn(O(),s??"");return}continue}if(!pn){$(O()===n&&!ft?"clean":"dirty");return}}};let mt=!1;const Po=async g=>{Ot=g,je=!1;let m;try{m=await En(wn(e.path),g,s,mt)}catch(y){return Ot=null,y instanceof nt&&y.status===422&&qe(y)?(mt=!1,ee(g),"stop"):y instanceof nt&&y.status===409?await as(n,!1)?"rebased":"stop":($("error"),yn(y),"stop")}return Ot=null,mt=!1,Sr(),m.merged?await as(g,!0)?"rebased":"stop":(je||r(g,m.sha),e.onSaved?.(g),"done")},as=async(g,m)=>{let y;try{y=await Lr(Or(e.apiBase,e.path))}catch(U){return $("error"),O()!==n&&yn(U),!1}if(y.kind!=="text")return $("error"),!1;const A=O(),E=t(g,y.text,A);return!E.ok||!Rt(E.text)?(m&<(y.sha),await Sn(A,y.sha??"")==="rebased"):(r(y.text,y.sha),m&&e.onSaved?.(y.text),!0)},Jo=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){tt=null;return}let m=null;for(let y=tt;y!==null;y=y.prev)if(y.sent!==y.from&&In(y.from,y.sent,g.text)){m=y;break}if(tt=null,m){ft=!0;const y=t(m.sent,g.text,O());y.ok&&Rt(y.text)?(n=g.text,i=void 0,lt(g.sha)):(n=m.sent,i=void 0)}},Wo=async g=>{Ot=g,je=!1;let m;const y=tt;try{tt={sent:g,from:n,prev:y},m=await Pt(Ht,{...l(g,y),...mt?{confirm_shrink:!0}:{}})}catch(E){if(Ot=null,E instanceof nt&&[400,401,403,404,405,409,413].includes(E.status)&&(tt=y),E instanceof nt&&(E.status===404||E.status===405))return h=!0,"rebased";if(E instanceof nt&&E.status===422&&qe(E))return mt=!1,ee(g),"stop";if(E instanceof nt&&E.status===409&&!a){let U={};try{U=JSON.parse(E.body)}catch{}const H=typeof U.text=="string"?U.text:null;if(H!==null){const X=t(n,H,O());if(X.ok&&Rt(X.text))return n=H,i=void 0,lt(U.sha),"rebased"}return Sn(O(),U.sha??"")}return $(a?"dirty":"error"),yn(E),"stop"}if(Ot=null,mt=!1,Sr(),m.update&&x.applyRemoteUpdate(m.update),tt=null,ft=!1,a)return"stop";const A=t(g,m.text,O());return A.ok&&Rt(A.text)&&(je||r(m.text,m.sha)),e.onSaved?.(m.text),"done"};let V=null;const ee=g=>{V||f||!e.onShrinkRefused||($("error"),V={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const m=et,y=Zt;try{const A=await Pt(Ht,{update:x.encodeState(),base:s,confirm_shrink:!0});r(A.text,A.sha),hs(m,y);const E=!Lt&&ot>=et;$(E?"clean":"dirty"),e.onSaved?.(n),!u&&!f&&ot{if(!f)try{const m=await Lr(Or(e.apiBase,e.path));if(f||m.kind!=="text")return;if(r(m.text,m.sha),Rt(m.text),V=null,a&&!u){if(await fe(!1),f)return;$(ot>=et&&!Lt?"clean":"dirty");return}ot=et,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{V=null}}},e.onShrinkRefused(V))};let gt=null;const Yo=()=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{const g=O();xr(de(n),de(g))&&ee(g)},ci)},br=async(g,m,y=N())=>{const A=++Qt;let E=y;for(let U=1;;U++){const H=E;F.set(H,g);try{return await En(wn(H),g,void 0,!1,!1,!1,!0),A===Qt&&!a&&(n=g,i=void 0,m&&(s=m),$("clean")),e.onConflictCopy?.(H),null}catch(X){if(X instanceof nt&&X.status===409&&U{const E=(U,H)=>{En(wn(U),m,void 0,!1,!0,!0,!0).then(X=>A?.(X.parked??U),X=>{if(X instanceof nt&&X.status===409&&H{(S===null||I!==g)&&(S=N(),I=g);const y=S;L=m,St=!0;const A=await br(g,m,y);return f?"stop":A?(yn(A.err),"stop"):(St=!1,I===g&&(S=null,I=null,L=""),O()!==g?"rebased":"stop")},hs=(g,m)=>{ot=Math.max(ot,g),ls(m),!(f||u)&&(d=et-ot,e.onPending?.(d))},qo=()=>{f||u||V||dt||(dt=setTimeout(()=>{dt=null,!u&&!f&&fe(!1)},ai))},fe=g=>{if(clearTimeout(dt??void 0),dt=null,g){if(ot>=et)return Promise.resolve();const y=et,A=Zt;return Pt(Ht,{update:x.encodeState(),base:s},!0).then(E=>{lt(E.sha),hs(y,A)})}if(gn)return gn;const m=(async()=>{try{for(;!u&&!f&&!V&&ot{k=!1,S=null,I=null,Fe=0,clearTimeout(ut??void 0),ut=null,ft=!1,a=!0,kr(x.text.toString()),g?.(),os&&(os=!1,e.onReady(x))},Je=async()=>{if(f||a||b||w)return;if(clearTimeout(ut??void 0),ut=null,te&&clearTimeout(te),te=null,Vt||jt){w=!0;try{for(;Vt||jt;)await(Vt??jt)}finally{w=!1}if(f||a)return;if(!u){O()!==n&&kn();return}}if(tt!==null&&!h){let H;w=!0;try{H=await Pt(Ht,{peek:!0})}catch{if(f||a)return;const X=pe[Math.min(Fe,pe.length-1)];Fe++,ut=setTimeout(()=>{ut=null,Je()},X);return}finally{w=!1}if(f||a)return;if(Jo(H),!u){(O()!==n||ft)&&kn();return}}const g=e.soloText?.();if(g===void 0||g===n)return us();const m=x.text.toString(),y=t(n,m,g);if(y.ok)return us(()=>x.applySplices(li(m,y.text)));k=!0,(S===null||I!==g)&&(S=N(),I=g),b=!0;let A;try{A=await br(g,s??"",S)}finally{b=!1}if(f)return;if(!A)return e.soloText?.()!==g?(S=null,I=null,Je()):us(()=>{n=x.text.toString()});const E=A.err;if(E instanceof nt&&!(E.status>=500||E.status===429))return;const U=pe[Math.min(Fe,pe.length-1)];Fe++,ut=setTimeout(()=>{ut=null,Je()},U)},x=new Ph(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{u=g==="live",g==="solo"&&(c=!0),u&&(dt&&clearTimeout(dt),dt=null,He(),a||Je(),ot=et,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):os=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),Er=(g,m)=>{const y=a?x.text.toString():null;if(y!==null&&kr(y),!x.isRemote(m?.origin)){if($("dirty"),a){Lt=!0,Be=y,Zt+=1,u||(et+=1,d=et-ot,e.onPending?.(d),clearTimeout(dt??void 0),dt=setTimeout(()=>{dt=null,!u&&!f&&fe(!1)},ai)),Yo();return}kn()}};x.text.observe(Er);const Cr=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Cr),Wh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const O=()=>p!==null?p:Dr()?x.text.toString():e.soloText?.()??"",Dr=()=>a||c&&x.text.length>0,lt=g=>{g&&(s=g)},zo=(g,m,y)=>{if(y?.held)return r(g,m),"same";if(g===n||g===Ot)return lt(m),"same";const A=O();if(g===A)return r(g,m),a&&(Ve(),$("clean")),"same";if(a){const U=n;return Bt.includes(g)||In(U,g,A)?(r(g,m),Lt&&(Be===null||g===Be||In(U,Be,g))&&(Ve(),$("clean")),"same"):A!==n||x.peerCount()>0?"blocked":(r(g,m),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const E=t(n,g,A);return E.ok?(Ot!==null&&(je=!0),r(g,m),Rt(E.text),E.text!==g?kn():Ot===null&&$("clean"),E.text===A?"same":"merged"):"blocked"},bn=()=>f?!1:a?u?Lt:otmt||!e.onShrinkRefused||!xr(de(n),de(O()))?!1:(clearTimeout(gt??void 0),gt=null,ee(O()),!0),Xo=async()=>{const g=Zt;$("saving");try{const m=await Pt(Ht,{update:x.encodeState()});return f?!1:(m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),ls(g),$(Lt?"dirty":"clean"),e.onSaved?.(n),!0)}catch(m){return f||m instanceof nt&&m.status===422&&qe(m)&&(clearTimeout(gt??void 0),gt=null,ee(O()),V)||$(Lt?"dirty":"clean"),!1}};let We=null;const Ko=()=>{if(We)return Vt&&(pn=!0),We;if(f||V)return Promise.resolve(!1);if(!bn())return Promise.resolve(!0);const m=(async()=>{for(;!f&&!V&&bn();){if(Go())return!1;if(a){if(u){if(!await Xo())return!1;continue}if(await fe(!1),f||V||!u&&ot{We===m&&(We=null)});return We=m,m};let Ut=null;const _n=g=>()=>{Ut===g&&(Ut=null)},Ar=(g,m)=>{if(V)return;if(a){const T=!u&&d>0;if(!T&&!(u&&Lt))return;const j="room\0"+x.text.toString();if(Ut===j)return;Ut=j;const Mt=Zt;(T?fe(!0):Pt(Ht,{update:x.encodeState()},!0).then(gs=>lt(gs.sha))).then(()=>ls(Mt),_n(j));return}if(k||St){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let j=S!==null&&I===g?S:null;for(const[Mt,ct]of F)j===null&&ct===g&&(j=Mt);j??=N(),_r(j,g,T);return}if(g===n&&!ft)return;const y="text\0"+g;if(Ut===y)return;if((c||h)&&!m){Pe();return}Ut=y;const A=n,E=!(c||h),U=tt,H={sent:g,from:A,prev:U};E&&(tt=H);const X=T=>{if(E&&T instanceof nt&&[400,401,403,404,405,409,413].includes(T.status)&&tt===H&&(tt=U),T instanceof nt&&T.status===422&&qe(T)){_n(y)(),f||(clearTimeout(gt??void 0),gt=null,ee(O()));return}if(!(T instanceof nt&&T.status===409))return _n(y)();let j={};try{const ct=JSON.parse(T.body);ct&&typeof ct=="object"&&(j=ct)}catch{}if(typeof j.text=="string"&&(j.text===g||In(A,g,j.text))){if(!f&&!a){const ct=t(g,j.text,O());ct.ok&&Rt(ct.text)&&(n=j.text,i=void 0,typeof j.sha=="string"&<(j.sha))}return}if(!g.trim())return;St=!0;let Mt=S!==null&&I===g?S:null;for(const[ct,gs]of F)Mt===null&&gs===g&&(Mt=ct);Mt??=N(),S=Mt,I=g,_r(Mt,g,y,ct=>{St=!1,e.onConflictCopy?.(ct)})},Ye=(T,j)=>{n=g,i=void 0,lt(j),!f&&O()===g&&$("clean"),e.onConflictCopy?.(T)};let fs;E?fs=Pt(Ht,{...l(g,U),park_on_conflict:!0},!0).then(T=>{if(mt=!1,tt===H&&(tt=null),ft=!1,T.parked)return Ye(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){lt(T.sha);return}const j=t(g,T.text,O());j.ok&&Rt(j.text)&&(r(T.text,T.sha),O()===n&&$("clean")),e.onSaved?.(T.text)},X):fs=En(wn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return Ye(T.parked,T.sha);if(T.merged){f?lt(T.sha):as(g,!0);return}r(g,T.sha),!f&&O()===n&&$("clean"),e.onSaved?.(g)},X);const ds=fs.then(()=>{},()=>{});jt=ds,ds.then(()=>{jt===ds&&(jt=null)})},Ir=()=>{f||Ar(O(),!0)},Tr=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ir),window.addEventListener("pageshow",Tr)),{collab:x,current:O,merge:zo,rebase:lt,saveNow:Ko,askingShrink:()=>V!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ir),window.removeEventListener("pageshow",Tr)),clearTimeout(te??void 0),clearTimeout(gt??void 0),He(),clearTimeout(ut??void 0),ut=null;const g=O();f=!0,p=g,V?e.onShrinkWithdrawn?.(V):Ar(g,!1),clearTimeout(dt??void 0),x.awareness.off("change",Cr),x.text.unobserve(Er),x.destroy()}}}export{he as D,ci as S,fu as U,hu as a,_a as b,Aa as c,li as d,uu as e,Js as f,ae as g,lu as h,vt as i,du as m,gu as o,au as r,cu as t};
+`)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Zh(e,t,n,s){const r=Kh(t,n,s);return!r.ok||n===s||n===t||s===t||Qh(e,r.text)?r:{ok:!1}}function li(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,qt),i=_t(t,qt),o=u=>{const a=new Array(u.length+1);a[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),k=k.slice(w,k.length-S),(p.length||k.length)&&s.push({index:b,deleteCount:p.length,insertText:k}),u=f,a=d}}function In(e,t,n){const s=new Map,r=Et(_t(t,qt),s),i=Ue(Et(_t(e,qt),s),r),o=Ue(r,Et(_t(n,qt),s));for(const c of i)for(const u of o)if(c.bSc.bE):!(u.aE<=c.bS||u.aS>=c.bE))return!1}else if(u.bSc.endsWith(`
+`);return!(l(t)!==l(e)&&l(n)!==l(t))}function ze(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ci=700,pe=[2e3,4e3,8e3,15e3],ai=2e3,eu=4,nu=64,su=8,ru=32e3,iu=32;function gu(e){const t=(g,m,y)=>Zh(e.path,g,m,y);let n=e.seed,s=e.baseSha;const r=(g,m)=>{n=g,i=m,ct(m);const y=Bt.lastIndexOf(g);y>=0?Bt.splice(0,y+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const m=[];for(let y=g;y!==null&&m.length<4;y=y.prev)y.sent!==y.from&&!m.includes(y.sent)&&m.push(y.sent);return m.length?m:void 0},l=(g,m=Z)=>{const y=o(m);return i&&i===s&&n.length>ru?{base:s,text:g,...y?{prior_sent:y}:{}}:{base:s,base_text:n,text:g,...y?{prior_sent:y}:{}}};let c=!1,u=!1,a=!1,h=!1,f=!1,d=0,p=null,k=!1,b=!1,w=!1,S=null,A=null,O="",U=0;const N=(g=Date.now())=>{const m=Math.max(g,U+1e3);return U=m,Qo(e.path,e.who||"browser",new Date(m))},F=new Map;let Qt=0,St=!1,ft=null,Fe=0,os=!1,Z=null,ot=!1;const Bt=[],kr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>iu&&Bt.shift())};let Lt=!1,Be=null,Zt=0;const Ve=()=>{Lt=!1,Be=null},ls=g=>{Zt===g&&Ve()};let tt=0,lt=0,pn=null,Vt=null,wn=!1,jt=null,Ot=null,je=!1,te=null,dt=null;const $=g=>e.onState?.(g),mn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ht=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let yn=null,cs=0;const He=()=>{clearTimeout(yn??void 0),yn=null},kn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const y=pe[Math.min(cs,pe.length-1)];cs++,yn=setTimeout(()=>{yn=null,!f&&!a&&Pe()},y)},Sr=()=>{He(),cs=0},Je=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},ci)},Rt=g=>{if(f)return p=g,!0;const m=L();if(m===g)return!0;const y=li(m,g);if(Dr())return x.applySplices(y),!0;if(!e.soloApply)return!1;for(const I of y)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(k)return b?Promise.resolve():We();if(Vt)return wn=!0,Vt;const g=(async()=>{try{for(;jt;)await jt;await Ho()}finally{Vt=null}})();return Vt=g,g},Ho=async()=>{let g=0;for(;;){if(wn=!1,V||a||w)return;const m=L();if(m===n&&!ot){$("clean");return}if($("saving"),e.onWriting?.(),St){if(S!==null&&A===m){if(await Sn(m,O)==="stop")return;continue}St=!1}const y=c||u?await Jo(m):await Wo(m);if(y==="stop")return;if(y==="rebased"){if(++g>eu){await Sn(L(),s??"");return}continue}if(!wn){$(L()===n&&!ot?"clean":"dirty");return}}};let mt=!1;const Jo=async g=>{Ot=g,je=!1;let m;try{m=await En(mn(e.path),g,s,mt)}catch(y){return Ot=null,y instanceof et&&y.status===422&&ze(y)?(mt=!1,ee(g),"stop"):y instanceof et&&y.status===409?await as(n,!1)?"rebased":"stop":($("error"),kn(y),"stop")}return Ot=null,mt=!1,Sr(),m.merged?await as(g,!0)?"rebased":"stop":(je||r(g,m.sha),e.onSaved?.(g),"done")},as=async(g,m)=>{let y;try{y=await Lr(Or(e.apiBase,e.path))}catch(R){return $("error"),L()!==n&&kn(R),!1}if(y.kind!=="text")return $("error"),!1;const I=L(),E=t(g,y.text,I);return!E.ok||!Rt(E.text)?(m&&ct(y.sha),await Sn(I,y.sha??"")==="rebased"):(r(y.text,y.sha),m&&e.onSaved?.(y.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){Z=null;return}let m=null;for(let y=Z;y!==null;y=y.prev)if(y.sent!==y.from&&In(y.from,y.sent,g.text)){m=y;break}if(Z=null,m){ot=!0;const y=t(m.sent,g.text,L());y.ok&&Rt(y.text)?(n=g.text,i=void 0,ct(g.sha)):(n=m.sent,i=void 0)}},Wo=async g=>{Ot=g,je=!1;let m;const y=Z;try{Z={sent:g,from:n,prev:y},m=await Jt(Ht,{...l(g,y),...mt?{confirm_shrink:!0}:{}})}catch(E){if(Ot=null,E instanceof et&&[400,401,403,404,405,409,413].includes(E.status)&&(Z=y),E instanceof et&&(E.status===404||E.status===405))return u=!0,"rebased";if(E instanceof et&&E.status===422&&ze(E))return mt=!1,ee(g),"stop";if(E instanceof et&&E.status===409&&!a){let R={};try{R=JSON.parse(E.body)}catch{}const P=typeof R.text=="string"?R.text:null;if(P!==null){const st=t(n,P,L());if(st.ok&&Rt(st.text))return n=P,i=void 0,ct(R.sha),"rebased"}return Sn(L(),R.sha??"")}return $(a?"dirty":"error"),kn(E),"stop"}if(Ot=null,mt=!1,Sr(),m.update&&x.applyRemoteUpdate(m.update),Z=null,ot=!1,a)return"stop";const I=t(g,m.text,L());return I.ok&&Rt(I.text)&&(je||r(m.text,m.sha)),e.onSaved?.(m.text),"done"};let V=null;const ee=g=>{V||f||!e.onShrinkRefused||($("error"),V={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const m=tt,y=Zt;try{const I=await Jt(Ht,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),hs(m,y);const E=!Lt&<>=tt;$(E?"clean":"dirty"),e.onSaved?.(n),!h&&!f&<{if(!f)try{const m=await Lr(Or(e.apiBase,e.path));if(f||m.kind!=="text")return;if(r(m.text,m.sha),Rt(m.text),V=null,a&&!h){if(await fe(!1),f)return;$(lt>=tt&&!Lt?"clean":"dirty");return}lt=tt,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{V=null}}},e.onShrinkRefused(V))};let gt=null;const Yo=()=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{const g=L();xr(de(n),de(g))&&ee(g)},ci)},br=async(g,m,y=N())=>{const I=++Qt;let E=y;for(let R=1;;R++){const P=E;F.set(P,g);try{return await En(mn(P),g,void 0,!1,!1,!1,!0),I===Qt&&!a&&(n=g,i=void 0,m&&(s=m),$("clean")),e.onConflictCopy?.(P),null}catch(st){if(st instanceof et&&st.status===409&&R{const E=(R,P)=>{En(mn(R),m,void 0,!1,!0,!0,!0).then(st=>I?.(st.parked??R),st=>{if(st instanceof et&&st.status===409&&P{(S===null||A!==g)&&(S=N(),A=g);const y=S;O=m,St=!0;const I=await br(g,m,y);return f?"stop":I?(kn(I.err),"stop"):(St=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},hs=(g,m)=>{lt=Math.max(lt,g),ls(m),!(f||h)&&(d=tt-lt,e.onPending?.(d))},qo=()=>{f||h||V||dt||(dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai))},fe=g=>{if(clearTimeout(dt??void 0),dt=null,g){if(lt>=tt)return Promise.resolve();const y=tt,I=Zt;return Jt(Ht,{update:x.encodeState(),base:s},!0).then(E=>{ct(E.sha),hs(y,I)})}if(pn)return pn;const m=(async()=>{try{for(;!h&&!f&&!V&<{k=!1,S=null,A=null,Fe=0,clearTimeout(ft??void 0),ft=null,ot=!1,a=!0,kr(x.text.toString()),g?.(),os&&(os=!1,e.onReady(x))},We=async()=>{if(f||a||b||w)return;if(clearTimeout(ft??void 0),ft=null,te&&clearTimeout(te),te=null,Vt||jt){w=!0;try{for(;Vt||jt;)await(Vt??jt)}finally{w=!1}if(f||a)return;if(!h){L()!==n&&Je();return}}if(Z!==null&&!u){let m;w=!0;try{m=await Jt(Ht,{peek:!0})}catch{if(f||a)return;const y=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},y);return}finally{w=!1}if(f||a)return;if(Po(m),!h){(L()!==n||ot)&&Je();return}}let g;if(e.beforeJoin){w=!0;try{g=await e.beforeJoin()}catch{}finally{w=!1}if(f||a){g?.();return}if(!h){g?.(),(L()!==n||ot)&&Je();return}}try{const m=e.soloText?.();if(m===void 0||m===n)return us();const y=x.text.toString(),I=t(n,y,m);if(I.ok)return us(()=>x.applySplices(li(y,I.text)));k=!0,(S===null||A!==m)&&(S=N(),A=m),b=!0;let E;try{E=await br(m,s??"",S)}finally{b=!1}if(f)return;if(!E)return e.soloText?.()!==m?(S=null,A=null,We()):us(()=>{n=x.text.toString()});const R=E.err;if(R instanceof et&&!(R.status>=500||R.status===429))return;const P=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},P)}finally{g?.()}},x=new Jh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{h=g==="live",g==="solo"&&(c=!0),h&&(dt&&clearTimeout(dt),dt=null,He(),a||We(),lt=tt,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):os=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),Er=(g,m)=>{const y=a?x.text.toString():null;if(y!==null&&kr(y),!x.isRemote(m?.origin)){if($("dirty"),a){Lt=!0,Be=y,Zt+=1,h||(tt+=1,d=tt-lt,e.onPending?.(d),clearTimeout(dt??void 0),dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai)),Yo();return}Je()}};x.text.observe(Er);const Cr=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Cr),Wh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Dr()?x.text.toString():e.soloText?.()??"",Dr=()=>a||c&&x.text.length>0,ct=g=>{g&&(s=g)},zo=(g,m,y)=>{if(y?.held)return r(g,m),"same";if(g===n||g===Ot)return ct(m),"same";const I=L();if(g===I)return r(g,m),a&&(Ve(),$("clean")),"same";if(a){const R=n;return Bt.includes(g)||In(R,g,I)?(r(g,m),Lt&&(Be===null||g===Be||In(R,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,m),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const E=t(n,g,I);return E.ok?(Ot!==null&&(je=!0),r(g,m),Rt(E.text),E.text!==g?Je():Ot===null&&$("clean"),E.text===I?"same":"merged"):"blocked"},bn=()=>f?!1:a?h?Lt:ltmt||!e.onShrinkRefused||!xr(de(n),de(L()))?!1:(clearTimeout(gt??void 0),gt=null,ee(L()),!0),Xo=async()=>{const g=Zt;$("saving");try{const m=await Jt(Ht,{update:x.encodeState()});return f?!1:(m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),ls(g),$(Lt?"dirty":"clean"),e.onSaved?.(n),!0)}catch(m){return f||m instanceof et&&m.status===422&&ze(m)&&(clearTimeout(gt??void 0),gt=null,ee(L()),V)||$(Lt?"dirty":"clean"),!1}};let Ye=null;const Ko=()=>{if(Ye)return Vt&&(wn=!0),Ye;if(f||V)return Promise.resolve(!1);if(!bn())return Promise.resolve(!0);const m=(async()=>{for(;!f&&!V&&bn();){if(Go())return!1;if(a){if(h){if(!await Xo())return!1;continue}if(await fe(!1),f||V||!h&<{Ye===m&&(Ye=null)});return Ye=m,m};let Ut=null;const _n=g=>()=>{Ut===g&&(Ut=null)},Ar=(g,m)=>{if(V)return;if(a){const T=!h&&d>0;if(!T&&!(h&&Lt))return;const j="room\0"+x.text.toString();if(Ut===j)return;Ut=j;const Mt=Zt;(T?fe(!0):Jt(Ht,{update:x.encodeState()},!0).then(gs=>ct(gs.sha))).then(()=>ls(Mt),_n(j));return}if(k||St){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let j=S!==null&&A===g?S:null;for(const[Mt,at]of F)j===null&&at===g&&(j=Mt);j??=N(),_r(j,g,T);return}if(g===n&&!ot)return;const y="text\0"+g;if(Ut===y)return;if((c||u)&&!m){Pe();return}Ut=y;const I=n,E=!(c||u),R=Z,P={sent:g,from:I,prev:R};E&&(Z=P);const st=T=>{if(E&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&Z===P&&(Z=R),T instanceof et&&T.status===422&&ze(T)){_n(y)(),f||(clearTimeout(gt??void 0),gt=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return _n(y)();let j={};try{const at=JSON.parse(T.body);at&&typeof at=="object"&&(j=at)}catch{}if(typeof j.text=="string"&&(j.text===g||In(I,g,j.text))){if(!f&&!a){const at=t(g,j.text,L());at.ok&&Rt(at.text)&&(n=j.text,i=void 0,typeof j.sha=="string"&&ct(j.sha))}return}if(!g.trim())return;St=!0;let Mt=S!==null&&A===g?S:null;for(const[at,gs]of F)Mt===null&&gs===g&&(Mt=at);Mt??=N(),S=Mt,A=g,_r(Mt,g,y,at=>{St=!1,e.onConflictCopy?.(at)})},qe=(T,j)=>{n=g,i=void 0,ct(j),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let fs;E?fs=Jt(Ht,{...l(g,R),park_on_conflict:!0},!0).then(T=>{if(mt=!1,Z===P&&(Z=null),ot=!1,T.parked)return qe(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ct(T.sha);return}const j=t(g,T.text,L());j.ok&&Rt(j.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},st):fs=En(mn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return qe(T.parked,T.sha);if(T.merged){f?ct(T.sha):as(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},st);const ds=fs.then(()=>{},()=>{});jt=ds,ds.then(()=>{jt===ds&&(jt=null)})},Ir=()=>{f||Ar(L(),!0)},Tr=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ir),window.addEventListener("pageshow",Tr)),{collab:x,current:L,merge:zo,rebase:ct,saveNow:Ko,askingShrink:()=>V!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ir),window.removeEventListener("pageshow",Tr)),clearTimeout(te??void 0),clearTimeout(gt??void 0),He(),clearTimeout(ft??void 0),ft=null;const g=L();f=!0,p=g,V?e.onShrinkWithdrawn?.(V):Ar(g,!1),clearTimeout(dt??void 0),x.awareness.off("change",Cr),x.text.unobserve(Er),x.destroy()}}}export{he as D,ci as S,fu as U,hu as a,_a as b,Aa as c,li as d,uu as e,Ps as f,ae as g,lu as h,vt as i,du as m,gu as o,au as r,cu as t};
diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html
index b980ab46..24360fc3 100644
--- a/internal/webapp/static/index.html
+++ b/internal/webapp/static/index.html
@@ -9,7 +9,7 @@
 
 BearDrive
 
-  
+  
   
   
   

From f1ba6e15b8b9c65f24443ff25fbbf0e6cb20ba5d Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Thu, 12 Nov 2026 00:07:09 +0900
Subject: [PATCH 15/34] fix(webapp): splice anchored VisualEdit patches
 synchronously before pagehide

---
 .../frontend/src/components/VisualEdit.tsx    | 15 +++--
 internal/webapp/frontend/src/inline-edit.ts   |  5 ++
 .../webapp/frontend/src/lib/frameflush.ts     | 38 +++++++++--
 .../src/lib/sharedfile_restore.test.ts        | 64 +++++++++++++++++++
 ...{Editor-cr2ybdrO.js => Editor-RcQTadDR.js} |  2 +-
 .../static/assets/VisualEdit-D4m3q3oV.js      |  1 +
 .../static/assets/VisualEdit-DxYGQmno.js      |  1 -
 .../{index-BXWhn62d.js => index-DRxt8NHx.js}  |  4 +-
 ...ile-Mmk-VhrH.js => sharedfile-BBwLL1qp.js} |  2 +-
 internal/webapp/static/index.html             |  2 +-
 internal/webapp/static/inline-edit.js         | 22 +++----
 11 files changed, 129 insertions(+), 27 deletions(-)
 rename internal/webapp/static/assets/{Editor-cr2ybdrO.js => Editor-RcQTadDR.js} (99%)
 create mode 100644 internal/webapp/static/assets/VisualEdit-D4m3q3oV.js
 delete mode 100644 internal/webapp/static/assets/VisualEdit-DxYGQmno.js
 rename internal/webapp/static/assets/{index-BXWhn62d.js => index-DRxt8NHx.js} (99%)
 rename internal/webapp/static/assets/{sharedfile-Mmk-VhrH.js => sharedfile-BBwLL1qp.js} (99%)

diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx
index cb356115..1fc5ce8a 100644
--- a/internal/webapp/frontend/src/components/VisualEdit.tsx
+++ b/internal/webapp/frontend/src/components/VisualEdit.tsx
@@ -407,7 +407,12 @@ export function VisualEdit({
     let srcLen = -1;
     let anchored = false;
 
-    const handleMessage = async (msg: FromFrame) => {
+    /* Synchronous unless it has to wait for anchoring: a patch that arrives
+       with the ranges anchored is in the document before this returns, so a
+       pagehide right after its message event (before any microtask) already
+       sends it. Only `ready`, and a patch that comes before anchoring, wait —
+       and the channel holds every message behind them meanwhile. */
+    const handleMessage = (msg: FromFrame): void | Promise => {
       if (msg.type === "bd-edit:flushed") {
         channel.flushed(msg.id);
         return;
@@ -425,12 +430,14 @@ export function VisualEdit({
         srcHash = msg.hash;
         srcLen = msg.len;
         frameReady = true;
-        await anchorRanges(); // no-op until the document is seeded too
-        return;
+        return anchorRanges(); // no-op until the document is seeded too
       }
 
       if (msg.type !== "bd-edit:patch") return;
-      if (!anchored) await anchorRanges();
+      if (!anchored) return anchorRanges().then(() => applyPatch(msg));
+      applyPatch(msg);
+    };
+    const applyPatch = (msg: Patch) => {
       const a = anchors.get(key(msg));
       if (!a) return; // a range from a render this side has already replaced
       if (stageDoc) {
diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts
index 999bb6d0..1d6eca3a 100644
--- a/internal/webapp/frontend/src/inline-edit.ts
+++ b/internal/webapp/frontend/src/inline-edit.ts
@@ -396,6 +396,11 @@ send({
 document.documentElement.setAttribute("data-bd-ready", "");
 
 window.addEventListener("beforeunload", unmount);
+// Flush on pagehide too; keep the open element mounted when entering bfcache.
+window.addEventListener("pagehide", (e: PageTransitionEvent) => {
+  if (e.persisted) flush();
+  else unmount();
+});
 
 /* Done in the app: post what the open editor holds, then answer. The answer
    follows every patch on the same channel, so once the app has handled it, it
diff --git a/internal/webapp/frontend/src/lib/frameflush.ts b/internal/webapp/frontend/src/lib/frameflush.ts
index 771acf9d..0edb8e1a 100644
--- a/internal/webapp/frontend/src/lib/frameflush.ts
+++ b/internal/webapp/frontend/src/lib/frameflush.ts
@@ -10,14 +10,21 @@
    before it has finished (anchoring is async), and draining asks the frame to
    post what it holds and answer `bd-edit:flushed`. The frame sends that answer
    after its last patch on the same channel, so by the time it is handled here
-   every patch before it has been spliced into the document. */
+   every patch before it has been spliced into the document.
+
+   Order must not cost time, though. With nothing waiting, a message is
+   handled synchronously inside its own event: a page that is going
+   (pagehide straight after the message, before any microtask) must already
+   have the patch in the document it sends. Only a handler that returns a
+   promise holds the messages after it. */
 
 // `lock`: the frame also stops taking edits until `bd-edit:unlock`, so nothing
 // typed while the save that follows is on the wire can be left out of it.
 export type FlushRequest = { type: "bd-edit:flush"; id: number; lock?: true };
 
 export type FrameChannel = {
-  /** Handle one message, after every message before it has been handled. */
+  /** Handle one message, after every message before it has been handled —
+      at once, synchronously, when nothing is still waiting. */
   enqueue(handle: () => unknown): void;
   /** The frame answered flush request `id` (called from a queued handler). */
   flushed(id: number): void;
@@ -33,16 +40,35 @@ export type FrameChannel = {
 // How often a drain checks that the frame it asked is still there to answer.
 const GONE_POLL_MS = 50;
 
+const isPromiseLike = (v: unknown): v is PromiseLike =>
+  v !== null && (typeof v === "object" || typeof v === "function") && "then" in v && typeof v.then === "function";
+
 export function frameChannel(): FrameChannel {
-  let queue: Promise = Promise.resolve();
+  // The async handler still running, and everything queued behind it.
+  let pending: Promise | null = null;
   const waiting = new Map void>();
   let seq = 0;
   let closed = false;
-  const settled = () => queue.then(() => {});
+  const settled = (): Promise => (pending ? pending.then(() => {}) : Promise.resolve());
+  // A handler that throws must not stall every message after it.
+  const hold = (p: Promise) => {
+    const held: Promise = p.catch(() => {}).finally(() => {
+      if (pending === held) pending = null;
+    });
+    pending = held;
+  };
   return {
     enqueue(handle) {
-      // A handler that throws must not stall every message after it.
-      queue = queue.then(handle).catch(() => {});
+      if (pending) {
+        hold(pending.then(handle));
+        return;
+      }
+      try {
+        const out = handle();
+        if (isPromiseLike(out)) hold(Promise.resolve(out));
+      } catch {
+        // as above: the next message is handled regardless
+      }
     },
     flushed(id) {
       waiting.get(id)?.();
diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
index 8fd2e07f..5a7cc896 100644
--- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
+++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts
@@ -2780,3 +2780,67 @@ for (const room of ["merges", "clashes"] as const) {
     }
   });
 }
+
+/* A patch whose message event is followed at once by pagehide — no await, no
+   microtask in between — must already be in the document pagehide sends.
+   With nothing waiting in the channel (the ranges anchored), the handler
+   runs inside enqueue itself. */
+for (const mode of ["staging", "live"] as const) {
+  test(`an anchored patch is in the document before an immediate pagehide (${mode})`, async () => {
+    const Y = await import("yjs");
+    fakeTimers();
+    const h = await heldRoom();
+    const channel = frameChannel();
+    try {
+      if (mode === "live") await h.goLive();
+      // VisualEdit's handler for an anchored patch: synchronous.
+      channel.enqueue(() => {
+        if (mode === "live") h.localEdit((t) => t.insert(t.length, "patched\n"));
+        else h.state.buffer += "patched\n";
+      });
+      window.dispatchEvent(new Event("pagehide"));
+
+      assert.equal(h.reqs.length, 1);
+      assert.equal(h.reqs[0].keepalive, true);
+      const body = JSON.parse(h.reqs[0].body) as { text?: string; update?: string };
+      if (mode === "staging") assert.equal(body.text, "a\nb\nc\npatched\n");
+      else {
+        const d = new Y.Doc();
+        Y.applyUpdate(d, Uint8Array.from(atob(body.update ?? ""), (ch) => ch.charCodeAt(0)));
+        assert.equal(d.getText("body").toString(), "a\nb\nc\npatched\n");
+      }
+    } finally {
+      channel.close();
+      h.done();
+      realTimers();
+    }
+  });
+}
+
+/* Order still holds when a handler waits (`ready` anchoring): every message
+   after it waits too, and runs in arrival order; once the channel is idle
+   again, a message is handled at once. */
+test("frameChannel keeps arrival order behind an async handler, then handles at once again", async () => {
+  const channel = frameChannel();
+  const log: string[] = [];
+  const anchoring = Promise.withResolvers();
+  channel.enqueue(async () => {
+    await anchoring.promise;
+    log.push("ready");
+  });
+  channel.enqueue(() => log.push("patch 1"));
+  channel.enqueue(() => {
+    throw new Error("a bad message");
+  });
+  channel.enqueue(() => log.push("patch 2"));
+  await settle();
+  same(log, []); // all held behind the anchoring
+
+  anchoring.resolve();
+  await settle();
+  same(log, ["ready", "patch 1", "patch 2"]); // a throwing handler stalls nothing
+
+  channel.enqueue(() => log.push("patch 3"));
+  same(log, ["ready", "patch 1", "patch 2", "patch 3"]); // idle: synchronous
+  channel.close();
+});
diff --git a/internal/webapp/static/assets/Editor-cr2ybdrO.js b/internal/webapp/static/assets/Editor-RcQTadDR.js
similarity index 99%
rename from internal/webapp/static/assets/Editor-cr2ybdrO.js
rename to internal/webapp/static/assets/Editor-RcQTadDR.js
index 91c178a5..18b78145 100644
--- a/internal/webapp/static/assets/Editor-cr2ybdrO.js
+++ b/internal/webapp/static/assets/Editor-RcQTadDR.js
@@ -1,4 +1,4 @@
-import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-BXWhn62d.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-Mmk-VhrH.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
+import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DRxt8NHx.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BBwLL1qp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
 `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
 `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||`
diff --git a/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js b/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js
new file mode 100644
index 00000000..e70cdd90
--- /dev/null
+++ b/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js
@@ -0,0 +1 @@
+import{r as u,j as E,w as Te,a as Se}from"./index-DRxt8NHx.js";import{o as Re,D as ke,c as L,a as O,m as de,d as fe}from"./sharedfile-BBwLL1qp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Ee=50,Le=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function Pe(){let o=null;const l=new Map;let x=0,h=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),j=c=>{const f=c.catch(()=>{}).finally(()=>{o===f&&(o=null)});o=f};return{enqueue(c){if(o){j(o.then(c));return}try{const f=c();Le(f)&&j(Promise.resolve(f))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,f,I=!1){if(await P(),h||f())return;const p=++x;let W;const _=new Promise(M=>{l.set(p,M),W=setInterval(()=>{!h&&!f()||(l.delete(p),M())},Ee)});try{c(I?{type:"bd-edit:flush",id:p,lock:!0}:{type:"bd-edit:flush",id:p}),await _}finally{clearInterval(W)}await P()},close(){h=!0;for(const c of l.values())c();l.clear()}}}async function je(o,l,x){let h=!1;try{return await o(),h=await l(),h}finally{h||x()}}async function We(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(x=>x.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ie({apiBase:o,fileURL:l,path:x,initial:h,me:P,onStateChange:j,onCollab:c,onPeers:f,onConflictCopy:I,baseSha:p,onSaved:W,onWriting:_,onRendered:M,handle:q}){const T=u.useRef(null),[Q,xe]=u.useState(null),[he,U]=u.useState(!1),[pe,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:j,onCollab:c,onPeers:f,onSaved:W,onWriting:_,onRendered:M,onConflictCopy:I});y.current={onStateChange:j,onCollab:c,onPeers:f,onSaved:W,onWriting:_,onRendered:M,onConflictCopy:I};const G=u.useRef(h),J=u.useRef(P);J.current=P;const B=u.useRef(p);B.current=p;const ee=u.useRef(null);return u.useEffect(()=>{ee.current?.rebase(p)},[p]),u.useEffect(()=>{let R=null,F=!1,s=null,g;const ye=700;U(!1),X(!1);const me=setTimeout(()=>{!b&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),ge=setTimeout(()=>X(!0),24e3),H=Pe();let V=!1;const we=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!V||r||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},C=new Map,te=async()=>{const e=T.current?.contentWindow;if(!e)return()=>{};C.set(e,(C.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(C.get(e)??1)-1;if(r>0){C.set(e,r);return}C.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await we(!0)}catch(r){throw i(),r}return i},a=ee.current=Re({apiBase:o,path:x,seed:G.current,baseSha:B.current,who:J.current?.name,me:J.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>Se(x,e),onShrinkWithdrawn:Te,beforeJoin:async()=>s?te():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(b&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:O(a.collab.text,m.index),to:O(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),b=!1,t!==i&&S(r=>r+1);e.destroy()}F=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),F=!0,k()},onStalled:()=>{F||s||(s=new ke,s.getText("body").insert(0,G.current),F=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ne=null;const re={...a,saveNow:()=>{let e=()=>{};return ne??=je(async()=>{e=await te()},()=>a.saveNow(),()=>e()).finally(()=>{ne=null})}};q&&(q.current=re);const w=new Map,oe=e=>e.start+","+e.end,k=async()=>{if(b||!R||!F)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await We(t);if(i!==null?i!==se:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(oe(n),{from:O(e,n.start),to:O(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});b=!0,U(!0),y.current.onRendered?.()};let se="",Y=-1,b=!1;const be=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){xe("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,se=e.hash,Y=e.len,V=!0,k();if(e.type==="bd-edit:patch"){if(!b)return k().then(()=>ie(e));ie(e)}},ie=e=>{const t=w.get(oe(e));if(!t)return;if(s){const d=L(t.from,s),A=L(t.to,s);if(!d||!A||d.index>A.index)return;const D=s.getText("body"),ve=A.index-d.index;if(d.index===0&&A.index===D.length&&t.spant.span*4+256){w.clear(),b=!1,S(v=>v+1);return}const K=D.toString().slice(d.index,A.index),ue=de(t.orig,K,e.html);if(t.orig=e.html,K===ue)return;s.transact(()=>{for(const v of fe(K,ue))v.deleteCount>0&&D.delete(d.index+v.index,v.deleteCount),v.insertText&&D.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ye);return}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),b=!1,S(d=>d+1);return}const z=m.toString().slice(r.index,n.index),le=de(t.orig,z,e.html);t.orig=e.html,z!==le&&a.collab.applySplices(fe(z,le).map(d=>({...d,index:d.index+r.index})))},ae=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>be(t))},ce=()=>{k()};return a.collab.text.observe(ce),window.addEventListener("message",ae),()=>{q?.current===re&&(q.current=null),V=!1,H.close(),clearTimeout(me),clearTimeout(ge),clearTimeout(g),a.collab.text.unobserve(ce),setTimeout(()=>{window.removeEventListener("message",ae),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,x,$]),E.jsxs(E.Fragment,{children:[Q&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:Q}),pe&&!he&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:x},$)]})}export{Ie as VisualEdit};
diff --git a/internal/webapp/static/assets/VisualEdit-DxYGQmno.js b/internal/webapp/static/assets/VisualEdit-DxYGQmno.js
deleted file mode 100644
index 207e2efa..00000000
--- a/internal/webapp/static/assets/VisualEdit-DxYGQmno.js
+++ /dev/null
@@ -1 +0,0 @@
-import{r as c,j as E,w as ve,a as Te}from"./index-BXWhn62d.js";import{o as Se,D as Re,c as L,a as H,m as de,d as ue}from"./sharedfile-Mmk-VhrH.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const ke=50;function Ee(){let u=Promise.resolve();const a=new Map;let f=0,x=!1;const W=()=>u.then(()=>{});return{enqueue(d){u=u.then(d).catch(()=>{})},flushed(d){a.get(d)?.(),a.delete(d)},async drain(d,j,q=!1){if(await W(),x||j())return;const b=++f;let v;const D=new Promise(M=>{a.set(b,M),v=setInterval(()=>{!x&&!j()||(a.delete(b),M())},ke)});try{d(q?{type:"bd-edit:flush",id:b,lock:!0}:{type:"bd-edit:flush",id:b}),await D}finally{clearInterval(v)}await W()},close(){x=!0;for(const d of a.values())d();a.clear()}}}async function Le(u,a,f){let x=!1;try{return await u(),x=await a(),x}finally{x||f()}}async function We(u){if(!globalThis.crypto?.subtle)return null;try{const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return[...new Uint8Array(a)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ae({apiBase:u,fileURL:a,path:f,initial:x,me:W,onStateChange:d,onCollab:j,onPeers:q,onConflictCopy:b,baseSha:v,onSaved:D,onWriting:M,onRendered:K,handle:I}){const T=c.useRef(null),[Q,fe]=c.useState(null),[xe,U]=c.useState(!1),[he,X]=c.useState(!1),Z=c.useRef(0),[$,S]=c.useState(0),h=c.useRef({onStateChange:d,onCollab:j,onPeers:q,onSaved:D,onWriting:M,onRendered:K,onConflictCopy:b});h.current={onStateChange:d,onCollab:j,onPeers:q,onSaved:D,onWriting:M,onRendered:K,onConflictCopy:b};const _=c.useRef(x),O=c.useRef(W);O.current=W;const B=c.useRef(v);B.current=v;const ee=c.useRef(null);return c.useEffect(()=>{ee.current?.rebase(v)},[v]),c.useEffect(()=>{let R=null,F=!1,o=null,m;const pe=700;U(!1),X(!1);const me=setTimeout(()=>{!g&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),ye=setTimeout(()=>X(!0),24e3),G=Ee();let J=!1;const ge=async e=>{const t=T.current,s=t?.contentWindow;if(!t||!s)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await G.drain(p=>s.postMessage(p,"*"),()=>!J||r||T.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(m),m=void 0},P=new Map,te=async()=>{const e=T.current?.contentWindow;if(!e)return()=>{};P.set(e,(P.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const r=(P.get(e)??1)-1;if(r>0){P.set(e,r);return}P.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ge(!0)}catch(r){throw s(),r}return s},i=ee.current=Se({apiBase:u,path:f,seed:_.current,baseSha:B.current,who:O.current?.name,me:O.current,onConflictCopy:e=>h.current.onConflictCopy?.(e),onShrinkRefused:e=>Te(f,e),onShrinkWithdrawn:ve,beforeJoin:async()=>o?te():()=>{},onReady:()=>{if(clearTimeout(m),m=void 0,o){const e=o;o=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(g&&t===s)for(const[r,n]of y){const p=L(n.from,e),C=L(n.to,e);p&&C&&y.set(r,{from:H(i.collab.text,p.index),to:H(i.collab.text,C.index),span:n.span,orig:n.orig})}else y.clear(),g=!1,t!==s&&S(r=>r+1);e.destroy()}F=!0,k()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,_.current),F=!0,k()},onStalled:()=>{F||o||(o=new Re,o.getText("body").insert(0,_.current),F=!0,k())},onState:e=>h.current.onStateChange?.(e),onCollab:e=>h.current.onCollab?.(e),onPeers:e=>h.current.onPeers?.(e),onSaved:e=>h.current.onSaved?.(e),onWriting:()=>h.current.onWriting?.(),soloText:()=>o?o.getText("body").toString():_.current,soloApply:({from:e,to:t,insert:s})=>{o&&o.transact(()=>{const r=o.getText("body");t>e&&r.delete(e,t-e),s&&r.insert(e,s)})}});let ne=null;const re={...i,saveNow:()=>{let e=()=>{};return ne??=Le(async()=>{e=await te()},()=>i.saveNow(),()=>e()).finally(()=>{ne=null})}};I&&(I.current=re);const y=new Map,oe=e=>e.start+","+e.end,k=async()=>{if(g||!R||!F)return;const e=o?o.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const s=await We(t);if(s!==null?s!==se:V>=0&&t.length!==V){R=null,S(n=>n+1);return}y.clear();for(const n of R)y.set(oe(n),{from:H(e,n.start),to:H(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});g=!0,U(!0),h.current.onRendered?.()};let se="",V=-1,g=!1;const we=async e=>{if(e.type==="bd-edit:flushed"){G.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){fe("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready"){R=e.ranges,se=e.hash,V=e.len,J=!0,await k();return}if(e.type!=="bd-edit:patch")return;g||await k();const t=y.get(oe(e));if(!t)return;if(o){const l=L(t.from,o),N=L(t.to,o);if(!l||!N||l.index>N.index)return;const A=o.getText("body"),be=N.index-l.index;if(l.index===0&&N.index===A.length&&t.spant.span*4+256){y.clear(),g=!1,S(w=>w+1);return}const z=A.toString().slice(l.index,N.index),le=de(t.orig,z,e.html);if(t.orig=e.html,z===le)return;o.transact(()=>{for(const w of ue(z,le))w.deleteCount>0&&A.delete(l.index+w.index,w.deleteCount),w.insertText&&A.insert(l.index+w.index,w.insertText)}),h.current.onStateChange?.("dirty"),clearTimeout(m),m=setTimeout(()=>{i.saveNow()},pe);return}const s=i.collab.doc,r=L(t.from,s),n=L(t.to,s);if(!r||!n||r.index>n.index)return;const p=i.collab.text,C=n.index-r.index;if(r.index===0&&n.index===p.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:C,stamped:t.span,docLength:p.length}),y.clear(),g=!1,S(l=>l+1);return}const Y=p.toString().slice(r.index,n.index),ce=de(t.orig,Y,e.html);t.orig=e.html,Y!==ce&&i.collab.applySplices(ue(Y,ce).map(l=>({...l,index:l.index+r.index})))},ie=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||G.enqueue(()=>we(t))},ae=()=>{k()};return i.collab.text.observe(ae),window.addEventListener("message",ie),()=>{I?.current===re&&(I.current=null),J=!1,G.close(),clearTimeout(me),clearTimeout(ye),clearTimeout(m),i.collab.text.unobserve(ae),setTimeout(()=>{window.removeEventListener("message",ie),clearTimeout(m),i.destroy(),o?.destroy()},300)}},[u,f,$]),E.jsxs(E.Fragment,{children:[Q&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:Q}),he&&!xe&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:a+(a.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ae as VisualEdit};
diff --git a/internal/webapp/static/assets/index-BXWhn62d.js b/internal/webapp/static/assets/index-DRxt8NHx.js
similarity index 99%
rename from internal/webapp/static/assets/index-BXWhn62d.js
rename to internal/webapp/static/assets/index-DRxt8NHx.js
index 974652be..1e3725ae 100644
--- a/internal/webapp/static/assets/index-BXWhn62d.js
+++ b/internal/webapp/static/assets/index-DRxt8NHx.js
@@ -1,4 +1,4 @@
-const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-cr2ybdrO.js","assets/sharedfile-Mmk-VhrH.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DxYGQmno.js"])))=>i.map(i=>d[i]);
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-RcQTadDR.js","assets/sharedfile-BBwLL1qp.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-D4m3q3oV.js"])))=>i.map(i=>d[i]);
 import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(`
 `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-cr2ybdrO.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DxYGQmno.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
+`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-RcQTadDR.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-D4m3q3oV.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?"	":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(`
 `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(`
 `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(`
 `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w};
diff --git a/internal/webapp/static/assets/sharedfile-Mmk-VhrH.js b/internal/webapp/static/assets/sharedfile-BBwLL1qp.js
similarity index 99%
rename from internal/webapp/static/assets/sharedfile-Mmk-VhrH.js
rename to internal/webapp/static/assets/sharedfile-BBwLL1qp.js
index 9b6ff27e..668d9ae9 100644
--- a/internal/webapp/static/assets/sharedfile-Mmk-VhrH.js
+++ b/internal/webapp/static/assets/sharedfile-BBwLL1qp.js
@@ -1,4 +1,4 @@
-import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-BXWhn62d.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
+import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-DRxt8NHx.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
 `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}.
 ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=`
 `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})()
 BearDrive
 
-  
+  
   
   
   
diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js
index 4ce28bc3..f7cb2f72 100644
--- a/internal/webapp/static/inline-edit.js
+++ b/internal/webapp/static/inline-edit.js
@@ -1,21 +1,21 @@
-(function(){"use strict";var Nr=Object.defineProperty,al=(n,e)=>{let t={};for(var r in n)Nr(t,r,{get:n[r],enumerable:!0});return Nr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Er(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ir(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Ft(t+1,s):Ft(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=vr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Rr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Rr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Rr(s.content,e-i-1,t-i-1)))}function vr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=vr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function cl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Pr(n,e,t,0)}function Pr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Mn(n,e,i+1),o=r.depth>i&&Mn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Br(s,o),Pe(Be(s,zr(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,Vt(n,e,i+1)),l),pt(e,t,i,l),o&&Pe(Be(o,Vt(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function Vt(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Mn(n,e,t+1);Pe(Be(i,Vt(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function fl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new $t(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Fr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Lr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class Wt extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Lr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Wt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Wt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Lr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new pl(e,t);if(r.next==null)return Fe.empty;let i=Vr(r);r.next&&r.err("Unexpected trailing text");let s=Sl(xl(i));return Ml(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
-`)}}Fe.empty=new Fe(!0);class pl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Vr(n){let e=[];do e.push(ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ml(n){let e=[];do e.push(gl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function gl(n){let e=kl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=yl(n,e);else break;return e}function $r(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function yl(n,e){let t=$r(n),r=t;return n.eat(",")&&(n.next!="}"?r=$r(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function bl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function kl(n){if(n.eat("(")){let e=Vr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=bl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function xl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Hr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new rl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Cl(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class wl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Cl(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Kr(e,i.attrs),this.excluded=null;let s=Jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Hr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Ur{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=_r.compile(this.spec.nodes,this),this.marks=jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Gr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Gr(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _r){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Wt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Gr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Tl(n){return n.tag!=null}function Ol(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Tl(i))this.tags.push(i);else if(Ol(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Zr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Zr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ei(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ei(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Yr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Nl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Xr={ol:!0,ul:!0},gt=1,Cn=2,yt=4;function Qr(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Cn:0):n&&n.whitespace=="pre"?gt|Cn:t&~yt}class Jt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Yr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Zr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Qr(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new Jt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Jt(null,null,E.none,!0,null,o):s=new Jt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Cn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
+(function(){"use strict";var Nr=Object.defineProperty,al=(n,e)=>{let t={};for(var r in n)Nr(t,r,{get:n[r],enumerable:!0});return Nr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Er(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ir(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=vr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Rr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Rr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Rr(s.content,e-i-1,t-i-1)))}function vr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=vr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function cl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Pr(n,e,t,0)}function Pr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Cn(n,e,i+1),o=r.depth>i&&Cn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Br(s,o),Pe(Be(s,zr(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Pe(Be(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Cn(n,e,t+1);Pe(Be(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function fl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Fr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Lr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class jt extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Lr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Lr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new pl(e,t);if(r.next==null)return Fe.empty;let i=Vr(r);r.next&&r.err("Unexpected trailing text");let s=Sl(xl(i));return Ml(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(`
+`)}}Fe.empty=new Fe(!0);class pl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Vr(n){let e=[];do e.push(ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ml(n){let e=[];do e.push(gl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function gl(n){let e=kl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=yl(n,e);else break;return e}function $r(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function yl(n,e){let t=$r(n),r=t;return n.eat(",")&&(n.next!="}"?r=$r(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function bl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function kl(n){if(n.eat("(")){let e=Vr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=bl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function xl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Hr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new rl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Cl(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class wl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Cl(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Kr(e,i.attrs),this.excluded=null;let s=Jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Hr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Ur{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=_r.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Gr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Gr(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _r){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Gr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Tl(n){return n.tag!=null}function Ol(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Tl(i))this.tags.push(i);else if(Ol(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Zr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Zr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ei(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ei(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Yr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Nl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Xr={ol:!0,ul:!0},gt=1,wn=2,yt=4;function Qr(n,e,t){return e!=null?(e?gt:0)|(e==="full"?wn:0):n&&n.whitespace=="pre"?gt|wn:t&~yt}class Ht{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Yr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Zr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Qr(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new Ht(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Ht(null,null,E.none,!0,null,o):s=new Ht(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&wn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
 `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ti(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Jt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function El(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Xr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Dl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ei(n){let e={};for(let t in n)e[t]=n[t];return e}function ti(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&qt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:qt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ni(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ni(e.marks)}}function ni(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const ri=new WeakMap;function Al(n){let e=ri.get(n);return e===void 0&&ri.set(n,e=Il(n)),e}function Il(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=qt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ii=65535,si=Math.pow(2,16);function Rl(n,e){return n+e*si}function oi(n){return n&ii}function vl(n){return(n-(n&ii))/si}const li=1,ai=2,Kt=4,ci=8;class wn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ci)>0}get deletedBefore(){return(this.delInfo&(li|Kt))>0}get deletedAfter(){return(this.delInfo&(ai|Kt))>0}get deletedAcross(){return(this.delInfo&Kt)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=oi(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Rl(l/3,e-a),m=e==a?ai:e==u?li:Kt;return(t<0?e!=a:e!=u)&&(m|=ci),new wn(h,m,p)}i+=f-c}return r?e+i:new wn(e+i,0,null)}touches(e,t){let r=0,i=oi(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(On(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Nn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Pl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Bl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function En(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function zl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function et(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Wl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&jl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&hi(n,o,l,s),En(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&di(n,o,l,s),!1}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function hi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
-`))}})}function jl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Hl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return pi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&pi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Kl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);hi(n,f.node(),f.before(),l)}o.inlineContent&&En(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);di(n,f.node(),f.before(),n.steps.length)}return n}function _l(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Ut(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return mi(i,s,r)?new R(e,t,r):new Gl(i,s,r).fit()}function mi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Gl{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=gi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return bi(e,-1)<=t?!1:(this.unplaced.size>1&&bi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=gi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(yi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=Dn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function gi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,yi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function Dn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Yl(t,s.content,o)?l:null}function Yl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Xl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function ki(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Zl(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=_l(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ea(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=xi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function xi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class tt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new tt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new tt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new tt(t.pos,t.attr,t.value)}}W.jsonID("attr",tt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let nt=class extends Error{};nt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},nt.prototype=Object.create(Error.prototype),nt.prototype.constructor=nt,nt.prototype.name="TransformError";class Si{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new nt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Ut(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Ql(this,e,t,r),this}replaceRangeWith(e,t,r){return Zl(this,e,t,r),this}deleteRange(e,t){return ea(this,e,t),this}lift(e,t){return Fl(this,e,t),this}join(e,t=1){return Kl(this,e,t),this}wrap(e,t){return $l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Wl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new tt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Hl(this,e,t,r),this}addMark(e,t,r){return Pl(this,e,t,r),this}removeMark(e,t,r){return Bl(this,e,t,r),this}clearIncompatible(e,t,r){return En(this,e,t,r),this}}const An=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ta(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?rt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):rt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return rt(e,e,0,0,1)||new U(e)}static atEnd(e){return rt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=An[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in An)throw new RangeError("Duplicate use of selection JSON ID "+e);return An[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ta{constructor(e,t){this.$from=e,this.$to=t}}let Mi=!1;function Ci(n){!Mi&&!n.parent.inlineContent&&(Mi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ci(e),Ci(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Gt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=rt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function wi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ti=1,Yt=2,Oi=4;class ra extends Si{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Yt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Yt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Yt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Oi,this}get scrolledIntoView(){return(this.updated&Oi)>0}}function Ni(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ni(t.init,r),this.apply=Ni(t.apply,r)}}const ia=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Rn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ia.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class it{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Rn(e.schema,e.plugins),s=new it(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ei(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ei(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ei(e.props,this,this.props),this.key=e.key?e.key.key:Di("plugin")}getState(e){return e[this.key]}}const vn=Object.create(null);function Di(n){return n in vn?n+"$"+ ++vn[n]:(vn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Di(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ai=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ii(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ri=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Pn(r);if(!i){let o=r.blockRange(),l=o&&et(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(ji(n,i,e,-1))return!0;if(r.parent.content.size==0&&(st(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Ut(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},sa=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Pn(r);return i?vi(n,i,e):!1},oa=(n,e,t)=>{let r=Bi(n,t);if(!r)return!1;let i=Bn(r);return i?vi(n,i,e):!1};function vi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Ut(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function st(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Pi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Pn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Pn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Bi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Bi(n,t);if(!r)return!1;let i=Bn(r);if(!i)return!1;let s=i.nodeAfter;if(ji(n,i,e,1))return!0;if(r.parent.content.size==0&&(st(s,"start")||x.isSelectable(s))){let o=Ut(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=_t(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},aa=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=_t(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ca=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&et(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Li=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
-`).scrollIntoView()),!0)};function zn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=zn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},$i=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=zn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&et(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function fa(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=zn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ua=fa(),da=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ha=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function pa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function ji(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&pa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&et(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&st(s,"start",!0)&&st(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Hi=Ji(-1),qi=Ji(1);function ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&fi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ki(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function _i(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ga(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new $t(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ma(e,t,n,s):Ca(e,t,s):!0:!1}}function Ma(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function wa(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},ot=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Vn=null;const me=function(n,e,t){let r=Vn||(Vn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ta=function(){Vn=null},We=function(n,e,t,r){return t&&(Yi(n,e,t,r,-1)||Yi(n,e,t,r,1))},Oa=/^(img|br|input|textarea|hr)$/i;function Yi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Oa.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Na(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ea(n,e){for(;;){if(n.nodeType==3&&e2),ee=lt||(ce?/Mac/.test(ce.platform):!1),es=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),wt=!!Xi&&"webkitFontSmoothing"in Xi.documentElement.style,Ra=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function va(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function Pa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function ts(n,e,t){if(!Hn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=ot(o);continue}let l=o,a=l==s.body,c=a?va(s):Pa(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:ot(o)}}function Ba(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ns(n.dom)}}function ns(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=ot(r));return e}function za({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;rs(t,r==0?0:r-e)}function rs(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?La(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:is(t,i)}function La(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Jn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Va(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Wa(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function ss(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Wa(n,r,i,e))}l==null&&(l=$a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Hn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return qn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(we(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function qn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function as(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ha(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return as(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ls(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const qa=/[\u0590-\u08ac]/;function Ka(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:as(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let cs=null,fs=null,us=!1;function _a(n,e,t){return cs==e&&fs==t?us:(cs=e,fs=t,us=t=="up"||t=="down"?Ha(n,e,t):Ka(n,e,t))}const te=0,ds=1,Je=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ms){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof hs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:ds,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:ds;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Ua extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=_n(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=bs(f,r,t),c?a=new Ga(e,t,r,i,f,u||null,d,c):t.isText?new Qt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&Zt(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Xa(this,o&&o.node,e);ec(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),gs(this.contentDOM,this.children,e),lt&&tc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=nc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Ua(this,s,t,i);e.input.compositionNodes.push(o),this.children=_n(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(Zt(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ys(this.dom,this.nodeDOM,Kn(this.outerDeco,this.node,t),Kn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ps(n,e,t,r,i){bs(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Qt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Qt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ms extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ga extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function gs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Za(n,e){return n.type.side-e.type.side}function ec(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function tc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function nc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function _n(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Un(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Xt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Da(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!xs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function ic(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function ws(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ts(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ts(n)}function Ts(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Yn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Os(n){return n.editable&&!n.hasFocus()?!1:Ns(n)}function Ns(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function sc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Xn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Es(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Xn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Xn(n.state,e);return i?Ne(n,i):!1}}}function en(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ct(n,e){return e<0?oc(n):lc(n)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Ds(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=en(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Qn(n,t,r):i&&Qn(n,i,s)}function lc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=en(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function As(n,e){let t=n.state.doc.resolve(e);if(!(V||es)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Is(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Xn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Rs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function vs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function fc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;vs(n,r,"true"),setTimeout(()=>vs(n,r,"false"),20)}return!1}function uc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function dc(n,e){let t=e.keyCode,r=uc(e);if(t==8||ee&&t==72&&r=="c")return Rs(n,-1)||ct(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Rs(n,1)||ct(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?As(n,n.state.selection.from)=="ltr"?-1:1:-1;return Es(n,i,r)||ct(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?As(n,n.state.selection.from)=="ltr"?1:-1:1;return Es(n,i,r)||ct(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Is(n,-1,r)||ct(n,-1);if(t==40||ee&&t==78&&r=="c")return fc(n)||Is(n,1,r)||ct(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Zn(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=$s(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Vs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
+`),t)}ignoreFallback(e,t){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),t,!0)}readStyles(e,t){let r=e.style;if(r&&r.length)for(let i=0;i!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ti(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Ht(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function El(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Xr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Dl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ei(n){let e={};for(let t in n)e[t]=n[t];return e}function ti(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(qt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ni(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ni(e.marks)}}function ni(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function qt(n){return n.document||window.document}const ri=new WeakMap;function Al(n){let e=ri.get(n);return e===void 0&&ri.set(n,e=Il(n)),e}function Il(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ii=65535,si=Math.pow(2,16);function Rl(n,e){return n+e*si}function oi(n){return n&ii}function vl(n){return(n-(n&ii))/si}const li=1,ai=2,_t=4,ci=8;class Tn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ci)>0}get deletedBefore(){return(this.delInfo&(li|_t))>0}get deletedAfter(){return(this.delInfo&(ai|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=oi(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Rl(l/3,e-a),m=e==a?ai:e==u?li:_t;return(t<0?e!=a:e!=u)&&(m|=ci),new Tn(h,m,p)}i+=f-c}return r?e+i:new Tn(e+i,0,null)}touches(e,t){let r=0,i=oi(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Nn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function En(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Pl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Bl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function Dn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function zl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function et(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Wl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&jl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&hi(n,o,l,s),Dn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&di(n,o,l,s),!1}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function hi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(`
+`))}})}function jl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Hl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return pi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&pi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Kl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);hi(n,f.node(),f.before(),l)}o.inlineContent&&Dn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);di(n,f.node(),f.before(),n.steps.length)}return n}function _l(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return mi(i,s,r)?new R(e,t,r):new Gl(i,s,r).fit()}function mi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Gl{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=gi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return bi(e,-1)<=t?!1:(this.unplaced.size>1&&bi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=gi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(yi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=An(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function gi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,yi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function An(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Yl(t,s.content,o)?l:null}function Yl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Xl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function ki(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Zl(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=_l(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ea(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=xi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function xi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class tt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new tt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new tt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new tt(t.pos,t.attr,t.value)}}W.jsonID("attr",tt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let nt=class extends Error{};nt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},nt.prototype=Object.create(Error.prototype),nt.prototype.constructor=nt,nt.prototype.name="TransformError";class Si{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new nt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Ql(this,e,t,r),this}replaceRangeWith(e,t,r){return Zl(this,e,t,r),this}deleteRange(e,t){return ea(this,e,t),this}lift(e,t){return Fl(this,e,t),this}join(e,t=1){return Kl(this,e,t),this}wrap(e,t){return $l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Wl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new tt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Hl(this,e,t,r),this}addMark(e,t,r){return Pl(this,e,t,r),this}removeMark(e,t,r){return Bl(this,e,t,r),this}clearIncompatible(e,t,r){return Dn(this,e,t,r),this}}const In=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ta(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?rt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):rt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return rt(e,e,0,0,1)||new U(e)}static atEnd(e){return rt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=In[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in In)throw new RangeError("Duplicate use of selection JSON ID "+e);return In[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ta{constructor(e,t){this.$from=e,this.$to=t}}let Mi=!1;function Ci(n){!Mi&&!n.parent.inlineContent&&(Mi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ci(e),Ci(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=rt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function wi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ti=1,Xt=2,Oi=4;class ra extends Si{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Oi,this}get scrolledIntoView(){return(this.updated&Oi)>0}}function Ni(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ni(t.init,r),this.apply=Ni(t.apply,r)}}const ia=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class vn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ia.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class it{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new vn(e.schema,e.plugins),s=new it(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ei(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ei(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ei(e.props,this,this.props),this.key=e.key?e.key.key:Di("plugin")}getState(e){return e[this.key]}}const Pn=Object.create(null);function Di(n){return n in Pn?n+"$"+ ++Pn[n]:(Pn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Di(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ai=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ii(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ri=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Bn(r);if(!i){let o=r.blockRange(),l=o&&et(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(ji(n,i,e,-1))return!0;if(r.parent.content.size==0&&(st(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},sa=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Bn(r);return i?vi(n,i,e):!1},oa=(n,e,t)=>{let r=Bi(n,t);if(!r)return!1;let i=zn(r);return i?vi(n,i,e):!1};function vi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function st(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Pi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Bn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Bn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Bi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Bi(n,t);if(!r)return!1;let i=zn(r);if(!i)return!1;let s=i.nodeAfter;if(ji(n,i,e,1))return!0;if(r.parent.content.size==0&&(st(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},aa=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ca=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&et(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Li=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
+`).scrollIntoView()),!0)};function Fn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Fn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},$i=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Fn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&et(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function fa(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Fn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ua=fa(),da=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ha=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function pa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function ji(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&pa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&et(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&st(s,"start",!0)&&st(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Hi=Ji(-1),qi=Ji(1);function ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&fi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ki(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function _i(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ga(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ma(e,t,n,s):Ca(e,t,s):!0:!1}}function Ma(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function wa(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},ot=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let $n=null;const me=function(n,e,t){let r=$n||($n=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ta=function(){$n=null},We=function(n,e,t,r){return t&&(Yi(n,e,t,r,-1)||Yi(n,e,t,r,1))},Oa=/^(img|br|input|textarea|hr)$/i;function Yi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Oa.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Na(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ea(n,e){for(;;){if(n.nodeType==3&&e2),ee=lt||(ce?/Mac/.test(ce.platform):!1),es=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),wt=!!Xi&&"webkitFontSmoothing"in Xi.documentElement.style,Ra=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function va(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function Pa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function ts(n,e,t){if(!qn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=ot(o);continue}let l=o,a=l==s.body,c=a?va(s):Pa(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:ot(o)}}function Ba(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ns(n.dom)}}function ns(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=ot(r));return e}function za({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;rs(t,r==0?0:r-e)}function rs(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?La(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:is(t,i)}function La(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Va(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Wa(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function ss(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Wa(n,r,i,e))}l==null&&(l=$a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function qn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Kn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(we(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Kn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function as(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ha(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return as(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ls(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const qa=/[\u0590-\u08ac]/;function Ka(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:as(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let cs=null,fs=null,us=!1;function _a(n,e,t){return cs==e&&fs==t?us:(cs=e,fs=t,us=t=="up"||t=="down"?Ha(n,e,t):Ka(n,e,t))}const te=0,ds=1,Je=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ms){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof hs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:ds,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:ds;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Ua extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Un(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=bs(f,r,t),c?a=new Ga(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Xa(this,o&&o.node,e);ec(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),gs(this.contentDOM,this.children,e),lt&&tc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=nc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Ua(this,s,t,i);e.input.compositionNodes.push(o),this.children=Un(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ys(this.dom,this.nodeDOM,_n(this.outerDeco,this.node,t),_n(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ps(n,e,t,r,i){bs(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ms extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ga extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function gs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Za(n,e){return n.type.side-e.type.side}function ec(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function tc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function nc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Un(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Gn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Da(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!xs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function ic(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function ws(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ts(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ts(n)}function Ts(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Xn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Os(n){return n.editable&&!n.hasFocus()?!1:Ns(n)}function Ns(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function sc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Qn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Es(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Qn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Qn(n.state,e);return i?Ne(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ct(n,e){return e<0?oc(n):lc(n)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Ds(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Zn(n,t,r):i&&Zn(n,i,s)}function lc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function As(n,e){let t=n.state.doc.resolve(e);if(!(V||es)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Is(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Qn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Rs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function vs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function fc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;vs(n,r,"true"),setTimeout(()=>vs(n,r,"false"),20)}return!1}function uc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function dc(n,e){let t=e.keyCode,r=uc(e);if(t==8||ee&&t==72&&r=="c")return Rs(n,-1)||ct(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Rs(n,1)||ct(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?As(n,n.state.selection.from)=="ltr"?-1:1:-1;return Es(n,i,r)||ct(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?As(n,n.state.selection.from)=="ltr"?1:-1:1;return Es(n,i,r)||ct(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Is(n,-1,r)||ct(n,-1);if(t==40||ee&&t==78&&r=="c")return fc(n)||Is(n,1,r)||ct(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function er(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=$s(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Vs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,`
 
 `);return{dom:a,text:d,slice:e}}function Ps(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,`
-`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=gc(t),wt&&yc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!hc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=bc(Ls(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(pc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const hc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function pc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&zs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Fs(o[o.length-1],s.length));let f=Bs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Bs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function zs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ls(n,e,t){return et})}return Dt.createHTML(n)}function gc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=$s(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Vs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},kc={touchstart:!0,touchmove:!0};class xc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Sc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Cc(n,r)&&!nr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},kc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),tr(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Mc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function tr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>nr(n,r))})}function nr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Cc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function wc(n,e){!nr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Hs(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),lt&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||dc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Hs(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Tc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function rr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Oc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Nc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ec(n,e,t,r,i){return rr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Nc(n,t):Oc(n,t))}function Dc(n,e,t,r){return rr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Ac(n,e,t,r){return rr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ic(n,t,r)}function Ic(n,e,t){if(t.button!=0)return!1;let r=Ws(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new vc(n,r)),!0):!1}function Ws(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function ir(n){return tn(n)}const js=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=ir(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Tc(t,n.input.lastClick)&&!t[js]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Rc(n,o,t,!!r):(s=="doubleClick"?Dc:Ac)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class Js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Rc extends Js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[js],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Ec(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class vc extends Js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Ws(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),ir(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>ir(n);function Hs(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Pc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&es&&Bc(n)))n.markCursor=n.state.storedMarks||t.marks(),tn(n,!0),n.markCursor=null;else if(tn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}qs(n,Pc)};function Bc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,qs(n,20))};function qs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>tn(n),e))}function Ks(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function zc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Na(e.focusNode,e.focusOffset),r=Ea(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function tn(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Ks(n),e||n.docView&&n.docView.dirty){let t=Un(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Fc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&Ce<15||lt&&Ra<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Zn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Fc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Lc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Vc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Ps(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Lc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function _s(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,_s(r),r.getData("text/html"),i,t)?t.preventDefault():Vc(n,t)};class Us{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const $c=ee?"altKey":"ctrlKey";function Gs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[$c]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Zn(n,l);(!t.dataTransfer.files.length||!V||Zi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Us(f,Gs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Wc(n,e,n.dragging)}finally{n.dragging=null}};function Wc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Ps(n,_s(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Gs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Ul(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Yn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class nn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof nn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Xs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Jc(l,n,e,t,i,s,o),f=rn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Xs(n,l,a+t);if(c){s=!0;let f=rn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Ys(s?Qs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function lr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Hc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qc=G&&Ce<=11;class Kc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class _c{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Kc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Hc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Os(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=ot(s))t.add(s);for(let s=e.anchorNode;s;s=ot(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Os(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Yc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Uc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Xc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Zc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Zc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},ef=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function tf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Un(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Qe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Qc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!ef.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=ro(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((lt&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&rf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=ro(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=nf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function ro(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Yn(n,e.resolve(t.anchor),e.resolve(t.head))}function nf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||ar(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function sf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class io{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new xc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(co),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=lo(this),oo(this),this.nodeViews=ao(this),this.docView=ps(this.state.doc,so(this),lr(this),this.dom,this),this.domObserver=new _c(this,(r,i,s,o)=>tf(this,r,i,s,o)),this.domObserver.start(),Sc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&tr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(co),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Ks(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=ao(this);lf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&tr(this),this.editable=lo(this),oo(this);let a=lr(this),c=so(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Ba(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&of(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=zc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ps(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sc(this)&&p.delaySelUpdate())?be(this,h):(ws(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&za(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&ts(this,t.getBoundingClientRect(),e)}else ts(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ja(this,e)}coordsAtPos(e,t=1){return ls(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return _a(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Zn(this,e)}destroy(){this.docView&&(Mc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],lr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ta())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return wc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Aa(this.dom.ownerDocument)==this.dom&&Gc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}io.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function so(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function oo(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function lo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function of(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function ao(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function lf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function co(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},sn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},af=typeof navigator<"u"&&/Mac/.test(navigator.platform),cf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),sn[$]=String.fromCharCode($);for(var cr in Ae)sn.hasOwnProperty(cr)||(sn[cr]=Ae[cr]);function ff(n){var e=af&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||cf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?sn:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const uf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),df=typeof navigator<"u"&&/Win/.test(navigator.platform);function hf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=il.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:uo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const yf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),bf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),kf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=et(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},xf=n=>e=>n(e),Sf=()=>({state:n,dispatch:e})=>$i(n,e),Mf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Cf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const wf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Tf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Of=n=>n.content?/^text(\*|\+)/.test(n.content):!1,ho=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:ho(n,t,"left"),to:ho(e,t,"right")}),Ef=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Nf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Df=()=>({commands:n})=>n.keyboardShortcut("Enter"),Af=()=>({state:n,dispatch:e})=>Vi(n,e);function If(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function on(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:If(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function po(n,e,t={}){return n.find(r=>r.type===e&&on(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function mo(n,e,t={}){return!!po(n,e,t)}function ur(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!po([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&mo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=ur(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},vf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(ln()||yo())&&r.dom.focus(),Bf()&&!ln()&&!yo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!go(t.state.selection))return o(),!0;const l=Pf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Ff=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Lf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),bo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&bo(r)}return n};function an(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return bo(t)}function ko(n){return typeof n?.nodesBetween=="function"}function ut(n,e,t){if(ko(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ut("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Ur({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(an(n),t.parseOptions):de.fromSchema(a).parse(an(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(an(n),t.parseOptions).content:s.parse(an(n),t.parseOptions)}return ut("",e,t)}function xo(n){return!("type"in n)}function So(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Vf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=xo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):ko(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&So(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function Mo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=Mo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ut(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&So(e,e.steps.length-1,-1)),!0):!1},Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>aa(n,e),Jf=()=>({state:n,dispatch:e})=>Ri(n,e),Hf=()=>({state:n,dispatch:e})=>zi(n,e),qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=_t(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=_t(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},_f=()=>({state:n,dispatch:e})=>sa(n,e),Uf=()=>({state:n,dispatch:e})=>oa(n,e);function Co(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Gf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Gf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function dr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>on(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Xf=(n,e={})=>({state:t,dispatch:r})=>dr(t,H(n,t.schema),e)?ca(t,r):!1,Qf=()=>({state:n,dispatch:e})=>Wi(n,e),Zf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Sa(r)(e,t)},eu=()=>({state:n,dispatch:e})=>Li(n,e);function wo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function To(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const tu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,To(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(To(d.attrs,e))))})})}),a},nu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ru=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},iu=()=>({state:n,dispatch:e})=>Pi(n,e),su=()=>({state:n,dispatch:e})=>Fi(n,e),ou=()=>({state:n,dispatch:e})=>da(n,e),lu=()=>({state:n,dispatch:e})=>qi(n,e),au=()=>({state:n,dispatch:e})=>Hi(n,e);function cu(n,e,t={},r={}){return ut(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const fu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=cu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=xo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function uu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function du(n,e){const t=new Si(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function hu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function hr(n){return e=>hu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Oo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Oo(t())]:e}).flat(10)}function pu(n){return typeof n=="function"}function D(n,e=void 0,...t){return pu(n)?e?n.bind(e)(...t):n(...t):n}function mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function cn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function gu(n){const e=[],{nodeExtensions:t,markExtensions:r}=cn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function yu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function No(n){const e=[],t=yu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...No(r[i]),...No(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Eo(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>fn(t,r),{})}function bu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Do(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):bu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ao(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&mu(t)?!1:t!=null))}function Io(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function ku(n,e){var t;const r=gu(n),{nodeExtensions:i,markExtensions:s}=cn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Do(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Eo(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Do(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Eo(m,f)})),[c.name,d]}));return new Ur({topNode:o,nodes:l,marks:a})}function xu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Su(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Cu(n,e){return ku(Mu(n),e)}function wu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
+`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=gc(t),wt&&yc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!hc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=bc(Ls(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(pc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const hc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function pc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&zs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Fs(o[o.length-1],s.length));let f=Bs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Bs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function zs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ls(n,e,t){return et})}return Dt.createHTML(n)}function gc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=$s(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Vs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},kc={touchstart:!0,touchmove:!0};class xc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Sc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Cc(n,r)&&!rr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},kc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),nr(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Mc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function nr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>rr(n,r))})}function rr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Cc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function wc(n,e){!rr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Hs(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),lt&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||dc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Hs(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Tc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function ir(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Oc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Nc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ec(n,e,t,r,i){return ir(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Nc(n,t):Oc(n,t))}function Dc(n,e,t,r){return ir(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Ac(n,e,t,r){return ir(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ic(n,t,r)}function Ic(n,e,t){if(t.button!=0)return!1;let r=Ws(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new vc(n,r)),!0):!1}function Ws(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function sr(n){return nn(n)}const js=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=sr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Tc(t,n.input.lastClick)&&!t[js]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Rc(n,o,t,!!r):(s=="doubleClick"?Dc:Ac)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class Js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Rc extends Js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[js],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Ec(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class vc extends Js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Ws(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),sr(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>sr(n);function Hs(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Pc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&es&&Bc(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}qs(n,Pc)};function Bc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,qs(n,20))};function qs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Ks(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function zc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Na(e.focusNode,e.focusOffset),r=Ea(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Ks(n),e||n.docView&&n.docView.dirty){let t=Gn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Fc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&Ce<15||lt&&Ra<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=er(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Fc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Lc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Vc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Ps(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Lc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function _s(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,_s(r),r.getData("text/html"),i,t)?t.preventDefault():Vc(n,t)};class Us{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const $c=ee?"altKey":"ctrlKey";function Gs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[$c]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=er(n,l);(!t.dataTransfer.files.length||!V||Zi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Us(f,Gs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Wc(n,e,n.dragging)}finally{n.dragging=null}};function Wc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Ps(n,_s(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Gs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Ul(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Xn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Xs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Jc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Xs(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Ys(s?Qs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function ar(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Hc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qc=G&&Ce<=11;class Kc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class _c{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Kc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Hc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Os(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=ot(s))t.add(s);for(let s=e.anchorNode;s;s=ot(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Os(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Yc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Uc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Xc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Zc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Zc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},ef=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function tf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Gn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Qe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Qc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!ef.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=ro(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((lt&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&rf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=ro(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=nf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function ro(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Xn(n,e.resolve(t.anchor),e.resolve(t.head))}function nf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||cr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function sf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class io{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new xc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(co),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=lo(this),oo(this),this.nodeViews=ao(this),this.docView=ps(this.state.doc,so(this),ar(this),this.dom,this),this.domObserver=new _c(this,(r,i,s,o)=>tf(this,r,i,s,o)),this.domObserver.start(),Sc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&nr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(co),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Ks(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=ao(this);lf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&nr(this),this.editable=lo(this),oo(this);let a=ar(this),c=so(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Ba(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&of(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=zc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ps(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sc(this)&&p.delaySelUpdate())?be(this,h):(ws(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&za(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&ts(this,t.getBoundingClientRect(),e)}else ts(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ja(this,e)}coordsAtPos(e,t=1){return ls(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return _a(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return er(this,e)}destroy(){this.docView&&(Mc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ar(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ta())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return wc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Aa(this.dom.ownerDocument)==this.dom&&Gc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}io.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function so(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function oo(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function lo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function of(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function ao(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function lf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function co(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},af=typeof navigator<"u"&&/Mac/.test(navigator.platform),cf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var fr in Ae)on.hasOwnProperty(fr)||(on[fr]=Ae[fr]);function ff(n){var e=af&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||cf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const uf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),df=typeof navigator<"u"&&/Win/.test(navigator.platform);function hf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=il.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:uo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const yf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),bf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),kf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=et(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},xf=n=>e=>n(e),Sf=()=>({state:n,dispatch:e})=>$i(n,e),Mf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Cf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const wf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Tf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Of=n=>n.content?/^text(\*|\+)/.test(n.content):!1,ho=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:ho(n,t,"left"),to:ho(e,t,"right")}),Ef=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Nf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Df=()=>({commands:n})=>n.keyboardShortcut("Enter"),Af=()=>({state:n,dispatch:e})=>Vi(n,e);function If(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:If(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function po(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function mo(n,e,t={}){return!!po(n,e,t)}function dr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!po([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&mo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=dr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},vf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||yo())&&r.dom.focus(),Bf()&&!an()&&!yo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!go(t.state.selection))return o(),!0;const l=Pf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Ff=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Lf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),bo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&bo(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return bo(t)}function ko(n){return typeof n?.nodesBetween=="function"}function ut(n,e,t){if(ko(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ut("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Ur({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(cn(n),t.parseOptions):de.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return ut("",e,t)}function xo(n){return!("type"in n)}function So(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Vf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=xo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):ko(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&So(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function Mo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=Mo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ut(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&So(e,e.steps.length-1,-1)),!0):!1},Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>aa(n,e),Jf=()=>({state:n,dispatch:e})=>Ri(n,e),Hf=()=>({state:n,dispatch:e})=>zi(n,e),qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},_f=()=>({state:n,dispatch:e})=>sa(n,e),Uf=()=>({state:n,dispatch:e})=>oa(n,e);function Co(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Gf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Gf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function hr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Xf=(n,e={})=>({state:t,dispatch:r})=>hr(t,H(n,t.schema),e)?ca(t,r):!1,Qf=()=>({state:n,dispatch:e})=>Wi(n,e),Zf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Sa(r)(e,t)},eu=()=>({state:n,dispatch:e})=>Li(n,e);function wo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function To(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const tu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,To(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(To(d.attrs,e))))})})}),a},nu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ru=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},iu=()=>({state:n,dispatch:e})=>Pi(n,e),su=()=>({state:n,dispatch:e})=>Fi(n,e),ou=()=>({state:n,dispatch:e})=>da(n,e),lu=()=>({state:n,dispatch:e})=>qi(n,e),au=()=>({state:n,dispatch:e})=>Hi(n,e);function cu(n,e,t={},r={}){return ut(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const fu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=cu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=xo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function uu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function du(n,e){const t=new Si(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function hu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function pr(n){return e=>hu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Oo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Oo(t())]:e}).flat(10)}function pu(n){return typeof n=="function"}function D(n,e=void 0,...t){return pu(n)?e?n.bind(e)(...t):n(...t):n}function mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function gu(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function yu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function No(n){const e=[],t=yu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...No(r[i]),...No(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Eo(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function bu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Do(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):bu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ao(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&mu(t)?!1:t!=null))}function Io(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function ku(n,e){var t;const r=gu(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Do(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Eo(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Do(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Eo(m,f)})),[c.name,d]}));return new Ur({topNode:o,nodes:l,marks:a})}function xu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Su(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Cu(n,e){return ku(Mu(n),e)}function wu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=`
 
-`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Tu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Ou(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Nu(n){const e=Ou(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Eu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Nu(r)}function Ro(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=ur(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function un(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Du(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>on(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>on(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function pr(n,e){const{nodeExtensions:t}=cn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function vo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(vo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Au(n,e,t){const{selection:r}=e;let i=null;if(go(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Iu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=uu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Au(r,t,a)},Ru=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),vu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ki(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ki(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Bu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},zu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},Fu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)};function Po(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Lu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=un(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&Po(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:Mo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Po(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Vu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...un(u,f.type.name,f.attrs),...e},m={...un(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Bo(n){return!n||n==="1"?null:n}function zo(n,e){return Bo(n)===Bo(e)}const mr=(n,e)=>{const t=hr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},gr=(n,e)=>{const t=hr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function $u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Wu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=hr(Ze=>pr(Ze.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&pr(N.type.name,u)?{node:N,pos:0}:null,Qe=_??v,Vd=!!_&&w.depth>=1&&w.depth-_.depth<=1,nl=!!v;if((Vd||nl)&&Qe){if(Qe.node.type===h)return ne&&nl?a().command(({tr:Ze,dispatch:kn})=>{const xn=$u(Ze);return xn?(Ze.setSelection(xn),kn&&kn(Ze),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(pr(Qe.node.type.name,u)&&h.validContent(Qe.node.content))return a().command(()=>(s.setNodeMarkup(Qe.pos,h),!0)).command(()=>mr(s,h)).command(()=>gr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>mr(s,h)).command(()=>gr(s,h)).run():a().command(()=>{const Ze=f().wrapInList(h,r),kn=A.filter(xn=>d.includes(xn.type.name));return s.ensureMarks(kn),Ze?!0:c.clearNodes()}).wrapInList(h,r).command(()=>mr(s,h)).command(()=>gr(s,h)).run()},ju=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Du(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=dr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Hu=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return dr(t,i,e)?r.lift(i):r.wrapIn(i,e)},qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Ku=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},_u=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=ur(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Uu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Gu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Yu=new ie("__tiptap_decorations__"),Xu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Yu,{type:"force",name:n}),!0),Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ma(i,e)(t,r)},Zu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)};var ed=al({blur:()=>yf,clearContent:()=>bf,clearNodes:()=>kf,command:()=>xf,createParagraphNear:()=>Sf,cut:()=>Mf,deleteCurrentNode:()=>Cf,deleteNode:()=>wf,deleteRange:()=>Tf,deleteSelection:()=>Ef,enter:()=>Df,exitCode:()=>Af,extendMarkRange:()=>Rf,first:()=>vf,focus:()=>zf,forEach:()=>Ff,insertContent:()=>Lf,insertContentAt:()=>Vf,insertDefaultBlock:()=>$f,joinBackward:()=>Jf,joinDown:()=>jf,joinForward:()=>Hf,joinItemBackward:()=>qf,joinItemForward:()=>Kf,joinTextblockBackward:()=>_f,joinTextblockForward:()=>Uf,joinUp:()=>Wf,keyboardShortcut:()=>Yf,lift:()=>Xf,liftEmptyBlock:()=>Qf,liftListItem:()=>Zf,newlineInCode:()=>eu,resetAttributes:()=>tu,scrollIntoView:()=>nu,selectAll:()=>ru,selectNodeBackward:()=>iu,selectNodeForward:()=>su,selectParentNode:()=>ou,selectTextblockEnd:()=>lu,selectTextblockStart:()=>au,setContent:()=>fu,setMark:()=>Iu,setMeta:()=>Ru,setNode:()=>vu,setNodeSelection:()=>Pu,setTextDirection:()=>Bu,setTextSelection:()=>zu,sinkListItem:()=>Fu,splitBlock:()=>Lu,splitListItem:()=>Vu,toggleList:()=>Wu,toggleMark:()=>ju,toggleNode:()=>Ju,toggleWrap:()=>Hu,undoInputRule:()=>qu,unsetAllMarks:()=>Ku,unsetMark:()=>_u,unsetTextDirection:()=>Uu,updateAttributes:()=>Gu,updateDecorations:()=>Xu,wrapIn:()=>Qu,wrapInList:()=>Zu});typeof process<"u"&&process.env.NODE_ENV;function td(n){return Object.prototype.toString.call(n).slice(8,-1)}function dn(n){return td(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Fo(n,e){const t={...n};return dn(n)&&dn(e)&&Object.keys(e).forEach(r=>{dn(e[r])&&dn(n[r])?t[r]=Fo(n[r],e[r]):t[r]=e[r]}),t}var nd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},yr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Fo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},hn=class sl extends yr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},rd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ol extends yr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Tu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>wu(r,{from:a.pos,to:c.pos},l)).join(o??`
+`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Tu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Ou(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Nu(n){const e=Ou(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Eu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Nu(r)}function Ro(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=dr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Du(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function mr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function vo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(vo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Au(n,e,t){const{selection:r}=e;let i=null;if(go(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Iu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=uu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Au(r,t,a)},Ru=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),vu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ki(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ki(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Bu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},zu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},Fu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)};function Po(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Lu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&Po(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:Mo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Po(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Vu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Bo(n){return!n||n==="1"?null:n}function zo(n,e){return Bo(n)===Bo(e)}const gr=(n,e)=>{const t=pr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},yr=(n,e)=>{const t=pr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function $u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Wu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=pr(Ze=>mr(Ze.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&mr(N.type.name,u)?{node:N,pos:0}:null,Qe=_??v,Vd=!!_&&w.depth>=1&&w.depth-_.depth<=1,nl=!!v;if((Vd||nl)&&Qe){if(Qe.node.type===h)return ne&&nl?a().command(({tr:Ze,dispatch:xn})=>{const Sn=$u(Ze);return Sn?(Ze.setSelection(Sn),xn&&xn(Ze),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(mr(Qe.node.type.name,u)&&h.validContent(Qe.node.content))return a().command(()=>(s.setNodeMarkup(Qe.pos,h),!0)).command(()=>gr(s,h)).command(()=>yr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>gr(s,h)).command(()=>yr(s,h)).run():a().command(()=>{const Ze=f().wrapInList(h,r),xn=A.filter(Sn=>d.includes(Sn.type.name));return s.ensureMarks(xn),Ze?!0:c.clearNodes()}).wrapInList(h,r).command(()=>gr(s,h)).command(()=>yr(s,h)).run()},ju=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Du(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=hr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Hu=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return hr(t,i,e)?r.lift(i):r.wrapIn(i,e)},qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Ku=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},_u=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=dr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Uu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Gu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Yu=new ie("__tiptap_decorations__"),Xu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Yu,{type:"force",name:n}),!0),Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ma(i,e)(t,r)},Zu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)};var ed=al({blur:()=>yf,clearContent:()=>bf,clearNodes:()=>kf,command:()=>xf,createParagraphNear:()=>Sf,cut:()=>Mf,deleteCurrentNode:()=>Cf,deleteNode:()=>wf,deleteRange:()=>Tf,deleteSelection:()=>Ef,enter:()=>Df,exitCode:()=>Af,extendMarkRange:()=>Rf,first:()=>vf,focus:()=>zf,forEach:()=>Ff,insertContent:()=>Lf,insertContentAt:()=>Vf,insertDefaultBlock:()=>$f,joinBackward:()=>Jf,joinDown:()=>jf,joinForward:()=>Hf,joinItemBackward:()=>qf,joinItemForward:()=>Kf,joinTextblockBackward:()=>_f,joinTextblockForward:()=>Uf,joinUp:()=>Wf,keyboardShortcut:()=>Yf,lift:()=>Xf,liftEmptyBlock:()=>Qf,liftListItem:()=>Zf,newlineInCode:()=>eu,resetAttributes:()=>tu,scrollIntoView:()=>nu,selectAll:()=>ru,selectNodeBackward:()=>iu,selectNodeForward:()=>su,selectParentNode:()=>ou,selectTextblockEnd:()=>lu,selectTextblockStart:()=>au,setContent:()=>fu,setMark:()=>Iu,setMeta:()=>Ru,setNode:()=>vu,setNodeSelection:()=>Pu,setTextDirection:()=>Bu,setTextSelection:()=>zu,sinkListItem:()=>Fu,splitBlock:()=>Lu,splitListItem:()=>Vu,toggleList:()=>Wu,toggleMark:()=>ju,toggleNode:()=>Ju,toggleWrap:()=>Hu,undoInputRule:()=>qu,unsetAllMarks:()=>Ku,unsetMark:()=>_u,unsetTextDirection:()=>Uu,updateAttributes:()=>Gu,updateDecorations:()=>Xu,wrapIn:()=>Qu,wrapInList:()=>Zu});typeof process<"u"&&process.env.NODE_ENV;function td(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return td(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Fo(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=Fo(n[r],e[r]):t[r]=e[r]}),t}var nd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},br=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Fo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class sl extends br{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},rd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ol extends br{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Tu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>wu(r,{from:a.pos,to:c.pos},l)).join(o??`
 
-`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ed}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=du(n.before,[n,...e]);Eu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const id=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:id,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return ln()||Co()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!vo(t.doc))return;const f=t.tr,u=uo({state:t,transaction:f}),{commands:d}=new gf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=cn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Ro(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Lo=class ll extends yr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ll(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new rd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Ro(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var sd=Lo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
+`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ed}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=du(n.before,[n,...e]);Eu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const id=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:id,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||Co()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!vo(t.doc))return;const f=t.tr,u=uo({state:t,transaction:f}),{commands:d}=new gf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Ro(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Lo=class ll extends br{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ll(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new rd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Ro(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var sd=Lo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
 
-`):""}),od=Lo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Vo=new WeakSet,$o=new WeakSet;function Ue(n){const e=n;return Vo.add(e),e}function br(n){return Array.isArray(n)&&Vo.has(n)}function Wo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&$o.has(e)&&!br(e)?Wo(e):[e])}function ld(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!br(i)&&!$o.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(br(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=Wo(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const jo=(n,e)=>ld(n,e),ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,ud=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var dd=hn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return jo("strong",{...fn(this.options.HTMLAttributes,n),children:jo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]},addPasteRules(){return[zt({find:cd,type:this.type}),zt({find:ud,type:this.type})]}});const hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,pd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,gd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var yd=hn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",fn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},kd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var xd=hn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",fn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type})]}}),pn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Jo(e):z.empty};var Jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=pn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=pn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Jo([]);var Sd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Md=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fwd&&(l=Cd(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dMd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Cd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const wd=20;function Td(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Ed)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,mn(e)),n.undone,Ho(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,mn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Od(t,n.prevRanges)),c=o?kr(n.prevRanges,t.mapping):Ho(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,mn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),kr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),kr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Od(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ho(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function kr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Nd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const _o=Ko(!1,!0),Sr=Ko(!0,!0),Ye="data-bd-src",Ad=hn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),gn=Cu([sd.extend({content:"inline*"}),od,dd,yd,xd,Ad]),Id=de.fromSchema(gn),Rd=Le.fromSchema(gn),vd={preserveWhitespace:"full"};function Uo(n){return Id.parse(n,vd)}function Go(n){const e=document.createElement("div");return e.appendChild(Rd.serializeFragment(n.content)),e.innerHTML}function Pd(n){try{return Go(Uo(n))===n.innerHTML}catch{return!1}}function Yo(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const yn=n=>parent.postMessage(n,"*"),Mr=new WeakMap;function Xo(n){let e=Mr.get(n);return e===void 0&&(e=Pd(n),Mr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,ve=null,dt=null,Cr="",Xe=!1;function Qo(){return Y?Go(Y.state.doc):null}function wr(){if(!ve||!dt)return;const n=Qo();n===null||n===Cr||(Cr=n,yn({type:"bd-edit:patch",start:dt.start,end:dt.end,html:n}))}function bn(){if(!Y)return;wr();const n=ve,e=Qo();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Mr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,dt=null}function Bd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function zd(n,e,t){if(ve===n)return;bn();const r=Yo(n);if(!r)return;ve=n,dt=r,Cr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=it.create({doc:Uo(n),plugins:[Dd(),fo({"Mod-b":_i(gn.marks.bold),"Mod-i":_i(gn.marks.italic),"Mod-z":_o,"Mod-y":Sr,"Shift-Mod-z":Sr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(bn(),!0)}),fo(ya)]});Y=new io({mount:n},{state:i,editable:()=>!Xe,dispatchTransaction(s){Xe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&wr())}}),Y.focus(),e!==void 0&&t!==void 0&&Bd(Y,e,t)}function Zo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Xe)return;const e=Zo(n.target);if(!e){bn();return}Xo(e)&&zd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Zo(n.target);e&&Xo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(yn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,ve=null,dt=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const el=document.createElement("style");el.textContent=`
+`):""}),od=Lo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Vo=new WeakSet,$o=new WeakSet;function Ue(n){const e=n;return Vo.add(e),e}function kr(n){return Array.isArray(n)&&Vo.has(n)}function Wo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&$o.has(e)&&!kr(e)?Wo(e):[e])}function ld(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!kr(i)&&!$o.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(kr(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=Wo(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const jo=(n,e)=>ld(n,e),ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,ud=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var dd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return jo("strong",{...un(this.options.HTMLAttributes,n),children:jo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]},addPasteRules(){return[zt({find:cd,type:this.type}),zt({find:ud,type:this.type})]}});const hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,pd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,gd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var yd=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},kd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var xd=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Jo(e):z.empty};var Jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Jo([]);var Sd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Md=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fwd&&(l=Cd(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dMd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Cd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const wd=20;function Td(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Ed)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,gn(e)),n.undone,Ho(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Od(t,n.prevRanges)),c=o?xr(n.prevRanges,t.mapping):Ho(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),xr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),xr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Od(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ho(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function xr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Nd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const _o=Ko(!1,!0),Mr=Ko(!0,!0),Ye="data-bd-src",Ad=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Cu([sd.extend({content:"inline*"}),od,dd,yd,xd,Ad]),Id=de.fromSchema(yn),Rd=Le.fromSchema(yn),vd={preserveWhitespace:"full"};function Uo(n){return Id.parse(n,vd)}function Go(n){const e=document.createElement("div");return e.appendChild(Rd.serializeFragment(n.content)),e.innerHTML}function Pd(n){try{return Go(Uo(n))===n.innerHTML}catch{return!1}}function Yo(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),Cr=new WeakMap;function Xo(n){let e=Cr.get(n);return e===void 0&&(e=Pd(n),Cr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,ve=null,dt=null,wr="",Xe=!1;function Qo(){return Y?Go(Y.state.doc):null}function kn(){if(!ve||!dt)return;const n=Qo();n===null||n===wr||(wr=n,bn({type:"bd-edit:patch",start:dt.start,end:dt.end,html:n}))}function Ft(){if(!Y)return;kn();const n=ve,e=Qo();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Cr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,dt=null}function Bd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function zd(n,e,t){if(ve===n)return;Ft();const r=Yo(n);if(!r)return;ve=n,dt=r,wr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=it.create({doc:Uo(n),plugins:[Dd(),fo({"Mod-b":_i(yn.marks.bold),"Mod-i":_i(yn.marks.italic),"Mod-z":_o,"Mod-y":Mr,"Shift-Mod-z":Mr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),fo(ya)]});Y=new io({mount:n},{state:i,editable:()=>!Xe,dispatchTransaction(s){Xe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&kn())}}),Y.focus(),e!==void 0&&t!==void 0&&Bd(Y,e,t)}function Zo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Xe)return;const e=Zo(n.target);if(!e){Ft();return}Xo(e)&&zd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Zo(n.target);e&&Xo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,ve=null,dt=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const el=document.createElement("style");el.textContent=`
   [${Ye}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; }
   [${Ye}][data-bd-edit="no"]:hover  { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; }
   [${Ye}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; }
   [${Ye}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); }
-`,document.head.appendChild(el);const tl=document.currentScript??document.querySelector("script[data-src-hash]"),Fd=tl?.dataset.srcHash??"",Ld=Number(tl?.dataset.srcLen??"-1");yn({type:"bd-edit:ready",hash:Fd,len:Ld,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Yo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",bn),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:flush"&&typeof e.id=="number"){wr(),e.lock===!0&&(Xe=!0,Y?.setProps({editable:()=>!Xe})),yn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Xe=!1,Y?.setProps({editable:()=>!Xe}))}})})();
+`,document.head.appendChild(el);const tl=document.currentScript??document.querySelector("script[data-src-hash]"),Fd=tl?.dataset.srcHash??"",Ld=Number(tl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:Fd,len:Ld,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Yo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",Ft),window.addEventListener("pagehide",n=>{n.persisted?kn():Ft()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:flush"&&typeof e.id=="number"){kn(),e.lock===!0&&(Xe=!0,Y?.setProps({editable:()=>!Xe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Xe=!1,Y?.setProps({editable:()=>!Xe}))}})})();

From 6a39d02bbd1116ba71346bc7db75585f2d515faa Mon Sep 17 00:00:00 2001
From: Byeonghoon Yoo 
Date: Thu, 12 Nov 2026 00:32:11 +0900
Subject: [PATCH 16/34] fix(webapp): beacon unacked VisualEdit iframe patches
 across opaque sandbox on unload

---
 CHANGELOG.md                                  |   1 +
 architecture/webapp-frontend.md               |   2 +
 architecture/webapp-server.md                 |  13 +-
 cmd/bdrive/desktop.go                         |   4 +
 internal/webapp/frame.go                      | 313 +++++++++++++++++-
 internal/webapp/frame_test.go                 | 130 +++++++-
 .../webapp/frontend/e2e/inline-edit.spec.ts   |  53 +++
 .../frontend/src/components/VisualEdit.tsx    |  45 ++-
 internal/webapp/frontend/src/inline-edit.ts   |  52 ++-
 .../webapp/frontend/src/lib/editbeacon.ts     |  36 ++
 .../src/lib/sharedfile_restore.test.ts        |  26 ++
 internal/webapp/server.go                     |   4 +
 ...{Editor-RcQTadDR.js => Editor-Bx08jARu.js} |   2 +-
 .../static/assets/VisualEdit-BgeFGAnP.js      |   1 +
 .../static/assets/VisualEdit-D4m3q3oV.js      |   1 -
 .../{index-DRxt8NHx.js => index-Dib7WV0J.js}  |   6 +-
 ...ile-BBwLL1qp.js => sharedfile-gwqfKQrv.js} |   2 +-
 internal/webapp/static/index.html             |   2 +-
 internal/webapp/static/inline-edit.js         |  34 +-
 19 files changed, 686 insertions(+), 41 deletions(-)
 create mode 100644 internal/webapp/frontend/src/lib/editbeacon.ts
 rename internal/webapp/static/assets/{Editor-RcQTadDR.js => Editor-Bx08jARu.js} (99%)
 create mode 100644 internal/webapp/static/assets/VisualEdit-BgeFGAnP.js
 delete mode 100644 internal/webapp/static/assets/VisualEdit-D4m3q3oV.js
 rename internal/webapp/static/assets/{index-DRxt8NHx.js => index-Dib7WV0J.js} (99%)
 rename internal/webapp/static/assets/{sharedfile-BBwLL1qp.js => sharedfile-gwqfKQrv.js} (99%)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c9ee432..02960b3d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root.
 - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict.
 - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op.
 - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element.
+- **`VisualEdit` saves edits the app never received when the tab closes.** The editing iframe stays sandboxed without `allow-same-origin`, so it has no session of its own. The app acknowledges each numbered patch (`bd-edit:ack`) and hands the iframe a single-file token URL from `POST /api/p//ycollab/frame`. When the iframe unloads with an unacknowledged patch, it posts its edited spans with the source hash, cookie-free (`no-cors`, `keepalive` up to 60,000 bytes), to `POST /api/p//ycollab/frame/`. The hub splices them onto that version and merges the result through `ycollab/sync`; a repeat of an edit the app already saved changes nothing, and a same-word clash parks a conflict copy. `bdrive desktop` proxies both routes.
 
 ## v0.18.9 — 2026-11-11
 
diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md
index fe9e81c7..46f3c31b 100644
--- a/architecture/webapp-frontend.md
+++ b/architecture/webapp-frontend.md
@@ -191,6 +191,7 @@ classDiagram
         +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once)
         +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them)
         +frameflush.ts frameChannel FrameChannel saveLocked (FIFO queue of iframe messages; drain posts bd-edit:flush, optionally with lock, and waits for bd-edit:flushed; saveLocked unlocks with bd-edit:unlock unless the save landed)
+        +editbeacon.ts beaconBody EditedSpan (the iframe's exit beacon body: src_hash, src_len, every span edited on this render; null when every patch is acknowledged)
         +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink
         +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room)
         +sharedfile.ts rebase (the head sha moved because a co-editor saved)
@@ -247,6 +248,7 @@ classDiagram
     inlineComment --> lib : anchor.ts (no app imports)
     components --> lib : rangeFor describe hitTest (Comments)
     components --> lib : merge3PreferRight diffSplices frameChannel saveLocked (VisualEdit), saveNow askingShrink (FileView flush)
+    note for lib "editbeacon.ts is the VisualEdit iframe's last word. inline-edit.ts numbers each bd-edit:patch (seq) and VisualEdit answers bd-edit:ack once the patch is in the document. VisualEdit fetches a single-file edit URL from POST {prefix}ycollab/frame and hands it to the iframe as bd-edit:beacon. On the iframe's beforeunload or pagehide, if any patch is unacknowledged (patchSeq greater than ackedSeq), inline-edit.ts posts beaconBody straight to POST ycollab/frame/{token}: cookie-free (credentials omit, no-cors), with keepalive when the body is at most 60,000 bytes. The iframe keeps sandbox allow-scripts allow-downloads, with no allow-same-origin; the token, not a session, authorizes the write, and the hub merges it like a staging checkpoint"
     Browser ..> components : Done awaits FileView's flushRef
     lib --> api : syncCollab putText keepalive (sharedfile)
     components ..> inlineComment : postMessage via the ?comment=1 iframe
diff --git a/architecture/webapp-server.md b/architecture/webapp-server.md
index 51c58284..3789a62b 100644
--- a/architecture/webapp-server.md
+++ b/architecture/webapp-server.md
@@ -52,6 +52,8 @@ classDiagram
         -syncDurable / awaitDurable(ctx, room, text, synced) sha, snapFailure
         -mergeStaleUpload(w, r, v, path, base, head, tmp, size) handled, now
         -moveDocLive(ctx, room, text, to, sha, filed, recompute)
+        -handleEditFrame() POST {prefix}ycollab/frame, PermWrite
+        -handleEditFrameFlush() POST {prefix}ycollab/frame/{token}
     }
     class recordingMux {
         <>
@@ -591,12 +593,14 @@ classDiagram
     }
     note for printView "The one thing allowed to relax sandboxInline's wall, and by exactly one flag. The app shell cannot print synced HTML: it renders in a cross-origin frame, and a cross-origin frame prints CLIPPED to its box — the parent may not measure the content to size it, and an over-tall guess prints the slack as blank pages. So ?print=1 serves the document as a TOP-LEVEL page that presses Print itself, which needs allow-modals (the flag that gates print/alert/confirm in a sandbox). allow-same-origin stays off, so the document is still opaque and can no more reach the API or the session cookie than the frame it replaces. text/html only, because the suffix is appended AFTER the stored bytes: HTML's parser accepts that and XHTML — parsed as XML — does not. Never on a download door, where it would corrupt the saved file, and Content-Length is dropped when it fires or the promised length truncates the script straight back off"
     class frameToken {
-        <>
-        HMAC over project, folder, reader, expiry
+        <>
+        HMAC over project, folder or file, reader, expiry, write flag
         key shared at hub/frame-key in Root
-        reads the page's folder as its reader, inline only
+        read token: the page's folder as its reader, inline only
+        edit token (frameClaims Write true, Path): one file, exit beacon only
     }
     note for frameToken "Synced HTML renders in an opaque-origin sandbox, so the browser sends no session cookie for the page's own images, and /file?path= cannot be the base a relative src resolves against. /frame mints a path-shaped URL for a signed-in reader; authGate's frameUser resolves its token before the provider, and handleRaw re-checks the folder scope and serves through serveBlob, so the reader's current permissions decide every request. The page can read its own URL, so the token is assumed to leak to the page's authors: what leaks is one reader's read access to one folder for frameTokenTTL"
+    note for frameToken "The VisualEdit exit beacon. The editing iframe is sandboxed without allow-same-origin, so it has no session to save an edit the app never acknowledged. POST {prefix}ycollab/frame (handleEditFrame, PermWrite, uploads enabled) mints a single-file edit token (Write true, Path) and returns its URL. On the way out the iframe POSTs to ycollab/frame/{token} cookie-free (no-cors, keepalive up to 60,000 bytes) the body { src_hash, src_len, patches }. handleEditFrameFlush checks the token's project and path and the caller's current write access, bounds the flush (maxEditPatches 256), rebuilds the text by splicing each UTF-16 span onto the src_hash version, and hands it to the editor's own save door: ycollab/sync with base_text and park_on_conflict on a hub, the upload door with the park header on a plain folder. The result merges with what the document holds now, is idempotent when the app's own save already landed, and parks a conflict copy when somebody changed the same words. Both routes are proxied by bdrive desktop (desktopRoutes)"
     class editView {
         <>
         text/html only, inline only, PermWrite on the path
@@ -812,7 +816,8 @@ classDiagram
     commentEvent ..> CommentThread : foldComments
     CommentThread *-- CommentAnchor
     Server ..> commentView : serveBlob
-    Server ..> frameToken : handleFrame, handleRaw, authGate
+    Server ..> frameToken : handleFrame, handleRaw, authGate, handleEditFrame, handleEditFrameFlush
+    frameToken ..> ydocs : edit beacon flush through POST ycollab/sync (park_on_conflict)
     frameToken ..> Backend : hub/frame-key
     Server o-- ReadLedger
     Server o-- DataIndex : Data
diff --git a/cmd/bdrive/desktop.go b/cmd/bdrive/desktop.go
index 53d3ef21..408b09f0 100644
--- a/cmd/bdrive/desktop.go
+++ b/cmd/bdrive/desktop.go
@@ -172,6 +172,10 @@ var desktopRoutes = []struct {
 	// it has to be classified, or the desktop answers it locally.
 	{"GET /api/p/{project}/ycollab/{room...}", routeProxy, ""},
 	{"POST /api/p/{project}/ycollab/sync", routeProxy, ""},
+	// A framed HTML page's edit beacon: minted and flushed against the hub's
+	// live document for the same reason /ycollab/sync is.
+	{"POST /api/p/{project}/ycollab/frame", routeProxy, ""},
+	{"POST /api/p/{project}/ycollab/frame/{token}", routeProxy, ""},
 
 	{"POST /api/p/{project}/reads", routeLocal, "the sync client posts these straight to the hub, never through here; the app's own viewer reads go out through desktop_reads.go instead, as human traffic"},
 }
diff --git a/internal/webapp/frame.go b/internal/webapp/frame.go
index d4784857..a6f99f22 100644
--- a/internal/webapp/frame.go
+++ b/internal/webapp/frame.go
@@ -17,8 +17,10 @@ import (
 	"regexp"
 	"strings"
 	"time"
+	"unicode/utf16"
 
 	"github.com/runbear-io/beardrive/internal/remote"
+	"github.com/runbear-io/beardrive/internal/textmerge"
 )
 
 /*
@@ -58,11 +60,17 @@ const frameTokenTTL = 4 * time.Hour
 // route can name it.
 const frameKeyObject = "hub/frame-key"
 
+// frameClaims is what a frame token carries. A read token (Write false) names
+// a folder the raw route reads; an edit token (Write true) names one file the
+// edit beacon may write. Neither ever serves as the other.
 type frameClaims struct {
 	Project string `json:"p"`
-	Dir     string `json:"d"` // "" is the project root
+	Dir     string `json:"d"`           // "" is the project root (raw route)
+	Path    string `json:"f,omitempty"` // the one file an edit token writes
+	Write   bool   `json:"w,omitempty"` // an edit token
 	UserID  string `json:"i"`
 	Email   string `json:"e"`
+	Name    string `json:"n,omitempty"`
 	Expires int64  `json:"x"`
 }
 
@@ -70,6 +78,9 @@ type frameClaims struct {
 // in hub mode (/api/p//raw/...).
 var frameRouteRe = regexp.MustCompile(`^/api/(?:p/[^/]+/)?raw/([^/]+)/`)
 
+// editFrameRouteRe matches the edit beacon's flush URL in either mode.
+var editFrameRouteRe = regexp.MustCompile(`^/api/(?:p/[^/]+/)?ycollab/frame/([^/]+)$`)
+
 // loadFrameKey returns the signing key, creating it on first use. A hub is
 // several processes, and a token minted by one must verify on another, so the
 // key is shared through storage rather than drawn per process. Volume mode and
@@ -169,20 +180,25 @@ func (s *Server) verifyFrame(ctx context.Context, tok string) (frameClaims, bool
 	return c, true
 }
 
-// frameUser is authGate's door for raw-route requests, before the provider:
-// the cookie is exactly what these requests do not carry. handled is false for
-// every other path.
+// frameUser is authGate's door for raw-route requests and the edit beacon,
+// before the provider: the cookie is exactly what these requests do not
+// carry. A read token opens only the raw route and an edit token only the
+// beacon's POST. handled is false for every other path.
 func (s *Server) frameUser(w http.ResponseWriter, r *http.Request) (u User, handled, ok bool) {
+	write := false
 	m := frameRouteRe.FindStringSubmatch(r.URL.Path)
+	if m == nil && r.Method == http.MethodPost {
+		m, write = editFrameRouteRe.FindStringSubmatch(r.URL.Path), true
+	}
 	if m == nil {
 		return User{}, false, false
 	}
 	c, valid := s.verifyFrame(r.Context(), m[1])
-	if !valid {
+	if !valid || c.Write != write || (write && c.Path == "") {
 		http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized)
 		return User{}, true, false
 	}
-	return User{ID: c.UserID, Email: c.Email}, true, true
+	return User{ID: c.UserID, Email: c.Email, Name: c.Name}, true, true
 }
 
 // handleFrame mints the path-shaped URL a page renders from. Asking for it is
@@ -229,6 +245,11 @@ func (s *Server) handleRaw(v *volume, w http.ResponseWriter, r *http.Request) {
 		http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized)
 		return
 	}
+	if c.Write {
+		// An edit token writes one file; it never reads a folder.
+		http.NotFound(w, r)
+		return
+	}
 	p := r.PathValue("path")
 	if c.Project != r.PathValue("project") || !underDir(p, c.Dir) {
 		http.Error(w, "no such file: "+p, http.StatusNotFound)
@@ -245,6 +266,286 @@ func (s *Server) handleRaw(v *volume, w http.ResponseWriter, r *http.Request) {
 	s.serveBlob(v, w, r2, false)
 }
 
+/*
+The edit beacon: what a framed page that is being edited sends as it unloads.
+
+A page edited in place lives in the same opaque-origin frame, and its edits
+reach the editor by postMessage — one hop the tab can close in the middle of.
+The frame's own pagehide still runs, and a keepalive fetch it starts outlives
+the page; but it carries no cookie and can read no answer (no-cors). So the
+frame is handed, while the page is open, a URL that carries its own
+credential: an edit token naming the editor, the project and the ONE file,
+good for frameTokenTTL, opening nothing but this POST. It is minted only for
+someone who may write that file, and every flush checks that again, so a
+revoked editor's open page stops writing at once.
+
+A flush is a set of patches against the exact bytes the page was rendered
+from — the hash and the UTF-16 length the editable view stamps on it
+(htmledit.go) — each replacing one stamped element's inner range. The hub
+rebuilds the edited text from those bytes and hands it to the door the
+editor's own save takes (/ycollab/sync on a hub, the upload door on a plain
+folder): merged with whatever the document holds now, idempotent when it
+already holds the edit, and parked as a conflict copy when somebody changed
+the same words, since a page that is gone cannot be asked.
+*/
+
+// maxEditPatches bounds one flush: a page edits a handful of elements.
+const maxEditPatches = 256
+
+// handleEditFrame mints the edit beacon's URL for one file the caller may write.
+func (s *Server) handleEditFrame(v *volume, w http.ResponseWriter, r *http.Request) {
+	if !s.Upload.Enabled {
+		http.Error(w, "uploads are disabled on this server", http.StatusForbidden)
+		return
+	}
+	p, err := cleanUploadPath(r.URL.Query().Get("path"))
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
+	if !s.writablePath(w, r, p) {
+		return
+	}
+	if _, _, code, err := s.lookup(v, r); err != nil {
+		http.Error(w, err.Error(), code)
+		return
+	}
+	u := s.requestUser(r)
+	project := r.PathValue("project")
+	exp := time.Now().Add(frameTokenTTL)
+	tok, err := s.signFrame(r.Context(), frameClaims{
+		Project: project, Path: p, Write: true,
+		UserID: u.ID, Email: u.Email, Name: u.Name, Expires: exp.Unix(),
+	})
+	if err != nil {
+		storageErr(w, http.StatusBadGateway, "could not prepare the editor", err)
+		return
+	}
+	base := "/api/"
+	if project != "" {
+		base += "p/" + url.PathEscape(project) + "/"
+	}
+	writeJSON(w, map[string]any{"url": base + "ycollab/frame/" + tok, "expires": exp.UnixMilli()})
+}
+
+type editPatch struct {
+	Start int    `json:"start"`
+	End   int    `json:"end"`
+	HTML  string `json:"html"`
+}
+
+// handleEditFrameFlush applies an unloading page's unsent edits. Its caller
+// is gone before the answer arrives; the answer is for tests and logs.
+func (s *Server) handleEditFrameFlush(v *volume, w http.ResponseWriter, r *http.Request) {
+	if !s.Upload.Enabled {
+		http.Error(w, "uploads are disabled on this server", http.StatusForbidden)
+		return
+	}
+	c, ok := s.verifyFrame(r.Context(), r.PathValue("token"))
+	if !ok || !c.Write || c.Path == "" || c.Project != r.PathValue("project") {
+		http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized)
+		return
+	}
+	// Who may write, decided now: the token names the editor, never grants.
+	if !s.writablePath(w, r, c.Path) {
+		return
+	}
+	var req struct {
+		SrcHash string      `json:"src_hash"`
+		SrcLen  int         `json:"src_len"`
+		Patches []editPatch `json:"patches"`
+	}
+	if err := json.NewDecoder(io.LimitReader(r.Body, maxSeedBytes+64<<10)).Decode(&req); err != nil {
+		http.Error(w, "invalid request body", http.StatusBadRequest)
+		return
+	}
+	if len(req.Patches) == 0 || len(req.Patches) > maxEditPatches || !blobRe.MatchString(req.SrcHash) {
+		http.Error(w, "invalid edit", http.StatusBadRequest)
+		return
+	}
+	// The page is closing and may drop the socket: the write still finishes.
+	ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second)
+	defer cancel()
+
+	base, found := s.editBase(ctx, v, c.Path, req.SrcHash)
+	if !found {
+		writeJSONStatus(w, http.StatusConflict, map[string]any{"error": "the page's version of this file is gone", "path": c.Path})
+		return
+	}
+	want, err := applyEditPatches(base, req.SrcLen, req.Patches)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
+	if fi, ok := s.headFile(ctx, v, c.Path); ok && sharpShrink(fi.Size, int64(len(want))) {
+		// Nobody is left to confirm it.
+		writeJSONStatus(w, http.StatusUnprocessableEntity, map[string]any{
+			"error": "this save would empty or sharply shrink the file", "shrink": true, "path": c.Path,
+		})
+		return
+	}
+	who := s.requestUser(r)
+	var out *memWriter
+	if c.Project != "" {
+		// The editor's own save door, whole: the room's merge, the conflict
+		// copy, durability, quota and folder rules.
+		body, _ := json.Marshal(map[string]any{
+			"base": req.SrcHash, "base_text": base, "text": want, "park_on_conflict": true,
+		})
+		out = s.reenter(ctx, who, http.MethodPost,
+			"/api/p/"+url.PathEscape(c.Project)+"/ycollab/sync?path="+url.QueryEscape(c.Path), body, nil)
+	} else {
+		out = s.flushToFile(ctx, v, who, c.Path, base, want)
+	}
+	if ct := out.hdr.Get("Content-Type"); ct != "" {
+		w.Header().Set("Content-Type", ct)
+	}
+	w.WriteHeader(out.code)
+	_, _ = w.Write(out.body.Bytes())
+}
+
+// flushToFile is the edit beacon on a plain folder, which has no room: the
+// edit is merged against the file as it is now and written conditionally on
+// it, and a clash is parked beside it.
+func (s *Server) flushToFile(ctx context.Context, v *volume, who User, p, base, want string) *memWriter {
+	put := func(path, text string, hdr http.Header) *memWriter {
+		hdr.Set(parkOnConflictHeader, "1")
+		return s.reenter(ctx, who, http.MethodPut, "/api/upload/content?path="+url.QueryEscape(path), []byte(text), hdr)
+	}
+	fi, ok := s.headFile(ctx, v, p)
+	if !ok {
+		w := newMemWriter()
+		w.code = http.StatusNotFound
+		w.body.WriteString("no such file: " + p)
+		return w
+	}
+	cur, ok := s.readHead(ctx, v, p, fi)
+	if !ok {
+		w := newMemWriter()
+		w.code = http.StatusBadGateway
+		w.body.WriteString("could not read " + p)
+		return w
+	}
+	text := want
+	switch {
+	case string(cur) == want:
+		w := newMemWriter()
+		writeJSON(w, map[string]any{"ok": true, "path": p, "sha": fi.Blob, "unchanged": true})
+		return w
+	case string(cur) != base:
+		merged, ok := textmerge.Merge([]byte(base), cur, []byte(want))
+		if !ok || !validMergedText(p, merged) {
+			return put(conflictPath(p, who, time.Now()), want, http.Header{"If-None-Match": {"*"}})
+		}
+		text = string(merged)
+	}
+	return put(p, text, http.Header{"If-Match": {fi.Blob}})
+}
+
+// reenter runs one request through the API as who, the way putAs does.
+func (s *Server) reenter(ctx context.Context, who User, method, target string, body []byte, hdr http.Header) *memWriter {
+	req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body))
+	if err != nil {
+		return &memWriter{code: http.StatusInternalServerError, hdr: http.Header{}}
+	}
+	for k, vs := range hdr {
+		req.Header[k] = vs
+	}
+	w := newMemWriter()
+	s.apiMux.ServeHTTP(w, withUser(req, who))
+	return w
+}
+
+// editBase is the text of p whose content hash is sha: the file as it is,
+// or — on a journal-backed source — a version p itself once held. Never any
+// other path's: the hash is checked against p's own history before a blob
+// is read, so a caller cannot read arbitrary content by naming its hash.
+func (s *Server) editBase(ctx context.Context, v *volume, p, sha string) (string, bool) {
+	ok := func(b []byte) bool {
+		return len(b) < maxSeedBytes && textmerge.IsText(b) && sha256Hex(b) == sha
+	}
+	if fi, found := s.headFile(ctx, v, p); found {
+		if b, read := s.readHead(ctx, v, p, fi); read && ok(b) {
+			return string(b), true
+		}
+	}
+	rs, isRemote := v.source.(*RemoteSource)
+	if !isRemote {
+		return "", false
+	}
+	ops, err := rs.loadSourcedOps(ctx)
+	if err != nil {
+		return "", false
+	}
+	held := false
+	for _, so := range ops {
+		if so.Op.Path == p && so.Op.Blob == sha {
+			held = true
+			break
+		}
+	}
+	if !held {
+		return "", false
+	}
+	rc, err := rs.OpenBlob(ctx, sha)
+	if err != nil {
+		return "", false
+	}
+	defer rc.Close()
+	b, err := io.ReadAll(io.LimitReader(rc, maxSeedBytes+1))
+	if err != nil || !ok(b) {
+		return "", false
+	}
+	return string(b), true
+}
+
+// readHead reads p's current bytes, bounded like a seed.
+func (s *Server) readHead(ctx context.Context, v *volume, p string, fi FileInfo) ([]byte, bool) {
+	rc, err := v.source.Open(ctx, p, fi)
+	if err != nil {
+		return nil, false
+	}
+	defer rc.Close()
+	b, err := io.ReadAll(io.LimitReader(rc, maxSeedBytes+1))
+	return b, err == nil
+}
+
+// applyEditPatches rebuilds an edited page from the bytes it was rendered
+// from. Offsets are UTF-16 code units, as the editable view stamps them
+// (utf16Len) and as the browser's strings count. Each patch replaces one
+// element's inner range, which always sits strictly inside the document —
+// past its start tag and before its end tag — so none can replace the whole
+// file; they are in order and do not overlap, and none splits a surrogate
+// pair.
+func applyEditPatches(base string, srcLen int, patches []editPatch) (string, error) {
+	units := utf16.Encode([]rune(base))
+	if len(units) != srcLen {
+		return "", errors.New("the page's length does not match its version of the file")
+	}
+	inPair := func(i int) bool {
+		return i > 0 && i < len(units) && utf16.IsSurrogate(rune(units[i])) && units[i] >= 0xDC00
+	}
+	out := make([]uint16, 0, len(units))
+	prev := 0
+	for i, p := range patches {
+		if p.Start <= 0 || p.Start > p.End || p.End >= srcLen || p.Start < prev || (i > 0 && p.Start < patches[i-1].End) {
+			return "", errors.New("edit ranges are out of order or outside the page")
+		}
+		if inPair(p.Start) || inPair(p.End) || !textmerge.IsText([]byte(p.HTML)) {
+			return "", errors.New("an edit is not text")
+		}
+		out = append(out, units[prev:p.Start]...)
+		out = append(out, utf16.Encode([]rune(p.HTML))...)
+		prev = p.End
+	}
+	out = append(out, units[prev:]...)
+	want := string(utf16.Decode(out))
+	if len(want) >= maxSeedBytes {
+		return "", errors.New("the edited page is too large to save")
+	}
+	return want, nil
+}
+
 func underDir(p, dir string) bool {
 	if p == "" || strings.Contains("/"+p+"/", "/../") {
 		return false
diff --git a/internal/webapp/frame_test.go b/internal/webapp/frame_test.go
index 4a8a0d8a..199e89c4 100644
--- a/internal/webapp/frame_test.go
+++ b/internal/webapp/frame_test.go
@@ -3,9 +3,9 @@ package webapp
 import (
 	"bytes"
 	"context"
+	"encoding/json"
 	"errors"
 	"io"
-	"encoding/json"
 	"net/http"
 	"net/http/httptest"
 	"net/url"
@@ -293,3 +293,131 @@ func TestFrameKeyCreateIsAtomicOrRefused(t *testing.T) {
 		}
 	}
 }
+
+// beacon is what the edit frame's unload sends: a no-cors keepalive POST, no
+// cookie, a text/plain body.
+func beacon(h http.Handler, target string, body any) *httptest.ResponseRecorder {
+	data, _ := json.Marshal(body)
+	req := httptest.NewRequest("POST", target, bytes.NewReader(data))
+	req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
+	rec := httptest.NewRecorder()
+	h.ServeHTTP(rec, req)
+	return rec
+}
+
+/*
+An edit typed into a framed page whose postMessage never reached the editor —
+the tab closed first — still lands: the frame's own unload beacon carries it,
+with a token that writes that one file and nothing else.
+
+	A read token cannot write and an edit token cannot read. The beacon
+	merges into the document, is idempotent when repeated, parks a conflict
+	copy when somebody changed the same words meanwhile, and stops the
+	moment the editor may no longer write.
+*/
+func TestEditFrameFlushSavesUnackedSpanAndBlocksReadTokens(t *testing.T) {
+	h, srv, c, p := frameHub(t)
+	const path = "site/page.html"
+	const page = "

Hello world

Second line

\n" + api := "/api/p/" + p.ID + "/" + file := func() string { + t.Helper() + return doAs(t, h, "GET", api+"file?path="+url.QueryEscape(path), nil, c["alice"]).Body.String() + } + if rec := doAs(t, h, "PUT", api+"upload/content?path="+url.QueryEscape(path), []byte(page), c["bob"]); rec.Code != 200 { + t.Fatalf("seed: %d %s", rec.Code, rec.Body) + } + + // A read token opens the raw route only. + readURL := frameURL(t, h, p, path, c["bob"]) + readTok := strings.Split(strings.TrimPrefix(readURL, api+"raw/"), "/")[0] + if rec := beacon(h, api+"ycollab/frame/"+readTok, map[string]any{}); rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden { + t.Fatalf("a read token flushed an edit: %d %s", rec.Code, rec.Body) + } + + rec := doAs(t, h, "POST", api+"ycollab/frame?path="+url.QueryEscape(path), nil, c["bob"]) + if rec.Code != 200 { + t.Fatalf("mint edit token: %d %s", rec.Code, rec.Body) + } + var minted struct{ URL string } + if err := json.Unmarshal(rec.Body.Bytes(), &minted); err != nil || !strings.HasPrefix(minted.URL, api+"ycollab/frame/") { + t.Fatalf("minted %s", rec.Body) + } + editTok := strings.TrimPrefix(minted.URL, api+"ycollab/frame/") + if rec := cookieless(h, api+"raw/"+editTok+"/"+path); rec.Code != http.StatusUnauthorized && rec.Code != http.StatusNotFound { + t.Fatalf("an edit token read the page: %d %s", rec.Code, rec.Body) + } + if rec := doAs(t, h, "POST", api+"ycollab/frame?path="+url.QueryEscape(path), nil, c["dave"]); rec.Code != http.StatusForbidden { + t.Fatalf("an outsider minted an edit token: %d", rec.Code) + } + + flush := func(word string) *httptest.ResponseRecorder { + start := strings.Index(page, "Hello world") + return beacon(h, minted.URL, map[string]any{ + "src_hash": shaOf(page), "src_len": len(page), + "patches": []map[string]any{{"start": start, "end": start + len("Hello world"), "html": word}}, + }) + } + edited := strings.Replace(page, "Hello world", "Hello there", 1) + for attempt := range 2 { // the second is the same beacon again + if rec := flush("Hello there"); rec.Code != 200 { + t.Fatalf("flush (attempt %d): %d %s", attempt, rec.Code, rec.Body) + } + if got := file(); got != edited { + t.Fatalf("file after flush %d = %q, want %q", attempt, got, edited) + } + } + if cc := conflictTexts(t, srv, p.ID, path); len(cc) != 0 { + t.Fatalf("an idempotent flush parked %d copies", len(cc)) + } + + // Out-of-range and malformed patches write nothing. + for _, bad := range []map[string]any{ + {"src_hash": shaOf(page), "src_len": len(page), "patches": []map[string]any{{"start": 0, "end": len(page), "html": "x"}}}, + {"src_hash": shaOf(page), "src_len": len(page) + 1, "patches": []map[string]any{{"start": 5, "end": 6, "html": "x"}}}, + {"src_hash": shaOf("not this page"), "src_len": 13, "patches": []map[string]any{{"start": 1, "end": 2, "html": "x"}}}, + } { + if rec := beacon(h, minted.URL, bad); rec.Code == 200 { + t.Fatalf("bad flush %v accepted: %s", bad, rec.Body) + } + } + if got := file(); got != edited { + t.Fatalf("a refused flush wrote: %q", got) + } + + // Carol changes the same words; the page that never saw it still flushes + // against what it rendered. The page's edit is kept beside the file. + carols := strings.Replace(page, "Hello world", "Hello carol", 1) + if rec := doAs(t, h, "PUT", api+"upload/content?path="+url.QueryEscape(path), []byte(carols), c["carol"]); rec.Code != 200 { + t.Fatalf("carol's write: %d %s", rec.Code, rec.Body) + } + rec = flush("Hello bob") + if rec.Code != 200 { + t.Fatalf("clashing flush: %d %s", rec.Code, rec.Body) + } + var out struct { + Parked string `json:"parked"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || !strings.HasPrefix(out.Parked, path+".bdrive-conflict-") { + t.Fatalf("clashing flush answered %s: want a conflict copy", rec.Body) + } + if got := file(); got != carols { + t.Fatalf("file = %q, want carol's %q", got, carols) + } + want := strings.Replace(page, "Hello world", "Hello bob", 1) + if got := doAs(t, h, "GET", api+"file?path="+url.QueryEscape(out.Parked), nil, c["alice"]).Body.String(); got != want { + t.Fatalf("copy %s = %q, want the page's %q", out.Parked, got, want) + } + + // Bob may no longer write: the open page's beacon stops at once. + if err := srv.Projects.SetPerm(p.ID, "bob@x.io", PermRead); err != nil { + t.Fatal(err) + } + before := file() + if rec := flush("Hello again"); rec.Code != http.StatusForbidden { + t.Fatalf("flush after write was revoked: %d %s", rec.Code, rec.Body) + } + if got := file(); got != before { + t.Fatalf("a revoked flush wrote: %q", got) + } +} diff --git a/internal/webapp/frontend/e2e/inline-edit.spec.ts b/internal/webapp/frontend/e2e/inline-edit.spec.ts index 1005c22d..b6c6af86 100644 --- a/internal/webapp/frontend/e2e/inline-edit.spec.ts +++ b/internal/webapp/frontend/e2e/inline-edit.spec.ts @@ -474,6 +474,59 @@ test("two people editing different paragraphs both land", async ({ page, browser expect(after).toContain(''); }); +/* A tab closed before the edit's postMessage reached the app. The app never + hears the patch (every one is dropped on its way in, so nothing is spliced + and nothing is acknowledged), so its own exit flush has nothing to send. + The frame, sandboxed without a session, posts the edit itself on the way + out to the single-file beacon URL the app handed it — and it lands. */ +test("an edit whose postMessage is not delivered before tab close still lands", async ({ page, browser }) => { + await login(page, ADMIN); // the verifier: makes the file and reads it back + const id = await project(page); + const file = await ownFile(page, id); + + const ctx = await browser.newContext(); + try { + const editor = await ctx.newPage(); + await login(editor, ADMIN); + const issued = editor.waitForResponse( + (r) => r.url().includes("/ycollab/frame?") && r.request().method() === "POST" && r.ok(), + ); + await editor.goto(`/${id}/${file}`); + await editor.click("#edit-btn"); + const frame = editor.frameLocator("iframe.htmlview"); + await frame.locator("html[data-bd-ready]").waitFor(); + await issued; + // The URL reaches the frame as a postMessage of its own, which nothing in + // the frame makes observable; one beat for that task to run. + await editor.waitForTimeout(200); + + // Every patch is dropped before VisualEdit's listener can see it. + await editor.evaluate(() => { + window.addEventListener( + "message", + (e) => { + const d: unknown = e.data; + if (d && typeof d === "object" && "type" in d && d.type === "bd-edit:patch") e.stopImmediatePropagation(); + }, + true, + ); + }); + + await frame.locator("p.lead").click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" Saved across close."); + await editor.close({ runBeforeUnload: true }); // the tab goes at once + + // The context (its network) outlives the tab, as the browser does; only + // the tab is gone, and the edit must still land. + const after = await waitForSource(page, id, file, "Revenue grew steadily across every region. Saved across close."); + expect(after.split("

").length - 1).toBe(1); + expect(after.split("").length - 1).toBe(1); + } finally { + await ctx.close().catch(() => {}); + } +}); + /* A file that is not in English, edited through the whole real stack. The offsets the server stamps are UTF-16 code units, because that is how a diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index 1fc5ce8a..034c1bab 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import * as Y from "yjs"; import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile"; +import { postJSON } from "../api/http"; import { diffSplices, merge3PreferRight } from "../lib/merge3"; import { frameChannel, saveLocked } from "../lib/frameflush"; import { type CollabStatus } from "../lib/collab"; @@ -31,7 +32,10 @@ import { askShrink, withdrawShrink } from "./ShrinkDialog"; // request (lib/frameflush.ts), answered by `bd-edit:flushed` after every patch // the frame held. type Ready = { type: "bd-edit:ready"; hash: string; len: number; ranges: Span[] }; -type Patch = { type: "bd-edit:patch"; start: number; end: number; html: string }; +// `seq` numbers the frame's patches; each is acknowledged (`bd-edit:ack`) once +// it is in the document, and one never acknowledged goes out by the frame's +// own exit beacon (lib/editbeacon.ts). +type Patch = { type: "bd-edit:patch"; seq?: number; start: number; end: number; html: string }; type Clobbered = { type: "bd-edit:clobbered" }; type Flushed = { type: "bd-edit:flushed"; id: number }; type FromFrame = Ready | Patch | Clobbered | Flushed; @@ -173,6 +177,35 @@ export function VisualEdit({ decides whether the editor may close. */ const channel = frameChannel(); let frameReady = false; + /* The frame's way out for a patch that never reaches here — a tab closed + between the keystroke and its message (lib/editbeacon.ts): a + single-file save URL it may post to without cookies. Fetched for each + render, refreshed before it expires, handed to the frame once ready. */ + let beaconPath = ""; + let beaconTimer: ReturnType | undefined; + let beaconStopped = false; + const sendBeaconURL = () => { + if (beaconPath && frameReady) frame.current?.contentWindow?.postMessage({ type: "bd-edit:beacon", url: beaconPath }, "*"); + }; + const fetchBeacon = () => { + postJSON<{ url?: unknown; expires?: unknown }>(apiBase + "ycollab/frame?path=" + encodeURIComponent(path), {}) + .then((r) => { + if (beaconStopped || typeof r?.url !== "string") return; + beaconPath = r.url; + sendBeaconURL(); + if (typeof r.expires !== "number") return; + // A deadline (epoch ms) or a lifetime (ms): renewed a minute early. + const left = r.expires > 1e12 ? r.expires - Date.now() : r.expires; + beaconTimer = setTimeout(fetchBeacon, Math.max(30_000, left - 60_000)); + }) + .catch(() => { + // An older hub: no beacon, exactly as before. + }); + }; + fetchBeacon(); + const ackPatch = (msg: Patch) => { + if (typeof msg.seq === "number") frame.current?.contentWindow?.postMessage({ type: "bd-edit:ack", seq: msg.seq }, "*"); + }; const drainFrame = async (lock: boolean) => { const el = frame.current; const win = el?.contentWindow; @@ -430,12 +463,18 @@ export function VisualEdit({ srcHash = msg.hash; srcLen = msg.len; frameReady = true; + sendBeaconURL(); return anchorRanges(); // no-op until the document is seeded too } if (msg.type !== "bd-edit:patch") return; - if (!anchored) return anchorRanges().then(() => applyPatch(msg)); + if (!anchored) + return anchorRanges().then(() => { + applyPatch(msg); + ackPatch(msg); + }); applyPatch(msg); + ackPatch(msg); }; const applyPatch = (msg: Patch) => { const a = anchors.get(key(msg)); @@ -543,6 +582,8 @@ export function VisualEdit({ if (handle?.current === exposed) handle.current = null; frameReady = false; channel.close(); + beaconStopped = true; + clearTimeout(beaconTimer); clearTimeout(retryTimer); clearTimeout(stuckTimer); clearTimeout(stageTimer); diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts index 1d6eca3a..381bc8b5 100644 --- a/internal/webapp/frontend/src/inline-edit.ts +++ b/internal/webapp/frontend/src/inline-edit.ts @@ -10,7 +10,10 @@ `bd-edit:flushed` with that id — so the app's Done saves only after every patch before the answer has landed — and, with `lock`, stops accepting edits until `bd-edit:unlock`, so nothing typed during Done's save can be - left out of it. + left out of it. It also takes `bd-edit:ack` (each patch's `seq`, once the + app has it in the document) and `bd-edit:beacon` (a single-file save URL): + a tab closed before a patch was acknowledged posts every edit here to that + URL on the way out — cookie-free, so the sandbox still holds no session. Three things had to be true at once, and they decided the design: @@ -37,6 +40,7 @@ import { EditorView } from "@tiptap/pm/view"; import { keymap } from "@tiptap/pm/keymap"; import { baseKeymap, toggleMark } from "@tiptap/pm/commands"; import { history, undo, redo } from "@tiptap/pm/history"; +import { beaconBody, type EditedSpan } from "./lib/editbeacon"; const SRC_ATTR = "data-bd-src"; @@ -186,6 +190,14 @@ let before = ""; /* Done's save is on the wire: no edit may start until the app says how it went (`bd-edit:unlock` if the editor stays; a page torn down otherwise). */ let locked = false; +/* The exit beacon (lib/editbeacon.ts): every patch is numbered, the app + acknowledges each once it is in the document, and a page that goes with a + patch unacknowledged posts every span edited on this render to the URL the + app gave it. */ +let patchSeq = 0; +let ackedSeq = 0; +let beaconURL = ""; +const editedSpans = new Map(); // The document as markup, or null if there is no live editor. function currentHTML(): string | null { @@ -197,7 +209,9 @@ function flush() { const html = currentHTML(); if (html === null || html === before) return; before = html; - send({ type: "bd-edit:patch", start: range.start, end: range.end, html }); + const seq = ++patchSeq; + editedSpans.set(range.start + "," + range.end, { start: range.start, end: range.end, html, seq }); + send({ type: "bd-edit:patch", seq, start: range.start, end: range.end, html }); } function unmount() { @@ -395,11 +409,27 @@ send({ // the only observable difference between "rendered" and "editable". document.documentElement.setAttribute("data-bd-ready", ""); -window.addEventListener("beforeunload", unmount); +/* Leaving with an edit the app never acknowledged: post it to the hub + ourselves, once per unload (marking it acknowledged), without cookies. A + keepalive body is capped by the browser; past that it goes as an ordinary + request that may still finish. */ +function beaconUnacked() { + const body = beaconBody({ url: beaconURL, patchSeq, ackedSeq, hash, len, spans: editedSpans.values() }); + if (body === null) return; + ackedSeq = patchSeq; + const keepalive = new TextEncoder().encode(body).byteLength <= 60_000; + void fetch(beaconURL, { method: "POST", mode: "no-cors", credentials: "omit", keepalive, body }).catch(() => {}); +} + +window.addEventListener("beforeunload", () => { + unmount(); + beaconUnacked(); +}); // Flush on pagehide too; keep the open element mounted when entering bfcache. window.addEventListener("pagehide", (e: PageTransitionEvent) => { if (e.persisted) flush(); else unmount(); + beaconUnacked(); }); /* Done in the app: post what the open editor holds, then answer. The answer @@ -409,8 +439,22 @@ window.addEventListener("pagehide", (e: PageTransitionEvent) => { saved). Only the app (the parent window) may ask. */ window.addEventListener("message", (e) => { if (e.source !== window.parent) return; - const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown } | null; + const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown; url?: unknown } | null; if (!msg) return; + if (msg.type === "bd-edit:ack" && typeof msg.seq === "number") { + if (msg.seq > ackedSeq) ackedSeq = msg.seq; + return; + } + if (msg.type === "bd-edit:beacon" && typeof msg.url === "string" && msg.url.startsWith("/")) { + // The document's own URL has the hub's scheme and host even though this + // sandbox's origin is the opaque "null". + try { + beaconURL = new URL(msg.url, window.location.href).href; + } catch { + // an unusable URL: no beacon, as before + } + return; + } if (msg.type === "bd-edit:flush" && typeof msg.id === "number") { flush(); if (msg.lock === true) { diff --git a/internal/webapp/frontend/src/lib/editbeacon.ts b/internal/webapp/frontend/src/lib/editbeacon.ts new file mode 100644 index 00000000..9f8245d8 --- /dev/null +++ b/internal/webapp/frontend/src/lib/editbeacon.ts @@ -0,0 +1,36 @@ +/* The editing iframe's last word, when the app may never hear it. + + An edit reaches the app as a postMessage, and the app acknowledges each + patch once it is in the document. A tab closed between the keystroke and + that acknowledgement leaves an edit only the iframe holds — and the iframe + is sandboxed without allow-same-origin, so it has no session to save it + with. What it has instead is a single-file capability the app fetched for + it (POST ycollab/frame): on the way out it posts, cookie-free, the rendered + document's hash and every span it edited, and the hub splices them onto + that version and merges the result like any staging checkpoint (idempotent + if the app's own save also landed). + + Pure, so it is tested without a DOM; inline-edit.ts owns the state. */ + +export type EditedSpan = { start: number; end: number; html: string; seq: number }; + +/* The beacon's body, or null when nothing is owed: no capability yet, every + patch acknowledged, no rendered version to splice onto, or nothing edited. + Every span edited on this render goes, not just the unacknowledged ones: + the hub rebuilds the document from `src_hash`, so the patches must spell + all of it. */ +export function beaconBody(o: { + url: string; + patchSeq: number; + ackedSeq: number; + hash: string; + len: number; + spans: Iterable; +}): string | null { + if (!o.url || o.patchSeq <= o.ackedSeq || !o.hash || o.len < 0) return null; + const patches = [...o.spans] + .sort((a, b) => a.start - b.start) + .map(({ start, end, html }) => ({ start, end, html })); + if (!patches.length) return null; + return JSON.stringify({ src_hash: o.hash, src_len: o.len, patches }); +} diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 5a7cc896..347fc1e0 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -55,6 +55,7 @@ const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); const { parseConflict } = await import("./conflict.ts"); const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts"); const { frameChannel, saveLocked } = await import("./frameflush.ts"); +const { beaconBody } = await import("./editbeacon.ts"); /* toEqual's semantics: a property that is undefined is a property that is absent. Only plain objects and arrays are rebuilt; anything else (a @@ -2844,3 +2845,28 @@ test("frameChannel keeps arrival order behind an async handler, then handles at same(log, ["ready", "patch 1", "patch 2", "patch 3"]); // idle: synchronous channel.close(); }); + +/* The frame's exit beacon goes only when a patch is still unacknowledged, + and then carries every span edited on the render, in source order, over + the rendered version's hash — enough for the hub to rebuild the whole + document. Acknowledged, or nothing to splice onto: nothing is sent. */ +test("beaconBody: sent only while a patch is unacknowledged, carrying every edited span", () => { + const spans = [ + { start: 40, end: 52, html: "Second", seq: 2 }, + { start: 10, end: 20, html: "First", seq: 1 }, + ]; + const base = { url: "https://hub/api/p/x/ycollab/frame/tok", hash: "h", len: 100, spans }; + same(JSON.parse(beaconBody({ ...base, patchSeq: 2, ackedSeq: 1 }) ?? "null"), { + src_hash: "h", + src_len: 100, + patches: [ + { start: 10, end: 20, html: "First" }, + { start: 40, end: 52, html: "Second" }, + ], + }); + assert.equal(beaconBody({ ...base, patchSeq: 2, ackedSeq: 2 }), null); // all acknowledged + assert.equal(beaconBody({ ...base, url: "", patchSeq: 2, ackedSeq: 1 }), null); // no capability + assert.equal(beaconBody({ ...base, hash: "", patchSeq: 2, ackedSeq: 1 }), null); // no version + assert.equal(beaconBody({ ...base, len: -1, patchSeq: 2, ackedSeq: 1 }), null); + assert.equal(beaconBody({ ...base, spans: [], patchSeq: 2, ackedSeq: 1 }), null); // nothing edited +}); diff --git a/internal/webapp/server.go b/internal/webapp/server.go index 34e3d242..c2239211 100644 --- a/internal/webapp/server.go +++ b/internal/webapp/server.go @@ -1706,6 +1706,10 @@ func (s *Server) Handler() http.Handler { // A client's state merged into the live room over plain HTTP (no // socket, or a shrink to confirm). It writes, so it needs write. mux.HandleFunc("POST "+prefix+"ycollab/sync", resolve(PermWrite, s.handleYCollabSync)) + // A framed HTML page's edit beacon (frame.go): minted with the + // session, flushed by the cookieless page as it unloads. + mux.HandleFunc("POST "+prefix+"ycollab/frame", resolve(PermWrite, s.handleEditFrame)) + mux.HandleFunc("POST "+prefix+"ycollab/frame/{token}", resolve(PermWrite, s.handleEditFrameFlush)) mux.HandleFunc("POST "+prefix+"upload/init", resolve(PermWrite, s.handleUploadInit)) mux.HandleFunc("PUT "+prefix+"upload/content", resolve(PermWrite, s.handleUploadContent)) mux.HandleFunc("POST "+prefix+"upload/commit", resolve(PermWrite, s.handleUploadCommit)) diff --git a/internal/webapp/static/assets/Editor-RcQTadDR.js b/internal/webapp/static/assets/Editor-Bx08jARu.js similarity index 99% rename from internal/webapp/static/assets/Editor-RcQTadDR.js rename to internal/webapp/static/assets/Editor-Bx08jARu.js index 18b78145..c370210c 100644 --- a/internal/webapp/static/assets/Editor-RcQTadDR.js +++ b/internal/webapp/static/assets/Editor-Bx08jARu.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DRxt8NHx.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-BBwLL1qp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,c as Vh,d as CO,r as oe,e as ZO,f as XO,g as AO,h as RO,j as wn,t as wl,w as MO,a as jO}from"./index-Dib7WV0J.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-gwqfKQrv.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-BgeFGAnP.js b/internal/webapp/static/assets/VisualEdit-BgeFGAnP.js new file mode 100644 index 00000000..96e09992 --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-BgeFGAnP.js @@ -0,0 +1 @@ +import{r as u,j as E,p as Pe,w as Me,a as We}from"./index-Dib7WV0J.js";import{o as je,D as Ce,c as L,a as J,m as me,d as be}from"./sharedfile-gwqfKQrv.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Fe=50,Ne=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function qe(){let o=null;const l=new Map;let f=0,x=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),M=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){M(o.then(c));return}try{const p=c();Ne(p)&&M(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,D=!1){if(await P(),x||p())return;const h=++f;let W;const I=new Promise(j=>{l.set(h,j),W=setInterval(()=>{!x&&!p()||(l.delete(h),j())},Fe)});try{c(D?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await I}finally{clearInterval(W)}await P()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function Ae(o,l,f){let x=!1;try{return await o(),x=await l(),x}finally{x||f()}}async function De(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ue({apiBase:o,fileURL:l,path:f,initial:x,me:P,onStateChange:M,onCollab:c,onPeers:p,onConflictCopy:D,baseSha:h,onSaved:W,onWriting:I,onRendered:j,handle:_}){const b=u.useRef(null),[K,ge]=u.useState(null),[we,Q]=u.useState(!1),[Te,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D});y.current={onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D};const G=u.useRef(x),U=u.useRef(P);U.current=P;const ee=u.useRef(h);ee.current=h;const te=u.useRef(null);return u.useEffect(()=>{te.current?.rebase(h)},[h]),u.useEffect(()=>{let R=null,C=!1,s=null,g;const ve=700;Q(!1),X(!1);const Se=setTimeout(()=>{!T&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),Re=setTimeout(()=>X(!0),24e3),H=qe();let O=!1,V="",ne,re=!1;const oe=()=>{V&&O&&b.current?.contentWindow?.postMessage({type:"bd-edit:beacon",url:V},"*")},se=()=>{Pe(o+"ycollab/frame?path="+encodeURIComponent(f),{}).then(e=>{if(re||typeof e?.url!="string"||(V=e.url,oe(),typeof e.expires!="number"))return;const t=e.expires>1e12?e.expires-Date.now():e.expires;ne=setTimeout(se,Math.max(3e4,t-6e4))}).catch(()=>{})};se();const ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},ke=async e=>{const t=b.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!O||r||b.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},F=new Map,ae=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};F.set(e,(F.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(F.get(e)??1)-1;if(r>0){F.set(e,r);return}F.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ke(!0)}catch(r){throw i(),r}return i},a=te.current=je({apiBase:o,path:f,seed:G.current,baseSha:ee.current,who:U.current?.name,me:U.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>We(f,e),onShrinkWithdrawn:Me,beforeJoin:async()=>s?ae():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(T&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:J(a.collab.text,m.index),to:J(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),T=!1,t!==i&&S(r=>r+1);e.destroy()}C=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),C=!0,k()},onStalled:()=>{C||s||(s=new Ce,s.getText("body").insert(0,G.current),C=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ce=null;const le={...a,saveNow:()=>{let e=()=>{};return ce??=Ae(async()=>{e=await ae()},()=>a.saveNow(),()=>e()).finally(()=>{ce=null})}};_&&(_.current=le);const w=new Map,ue=e=>e.start+","+e.end,k=async()=>{if(T||!R||!C)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await De(t);if(i!==null?i!==de:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(ue(n),{from:J(e,n.start),to:J(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Q(!0),y.current.onRendered?.()};let de="",Y=-1,T=!1;const Ee=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){ge("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,de=e.hash,Y=e.len,O=!0,oe(),k();if(e.type==="bd-edit:patch"){if(!T)return k().then(()=>{fe(e),ie(e)});fe(e),ie(e)}},fe=e=>{const t=w.get(ue(e));if(!t)return;if(s){const d=L(t.from,s),q=L(t.to,s);if(!d||!q||d.index>q.index)return;const A=s.getText("body"),Le=q.index-d.index;if(d.index===0&&q.index===A.length&&t.spant.span*4+256){w.clear(),T=!1,S(v=>v+1);return}const B=A.toString().slice(d.index,q.index),ye=me(t.orig,B,e.html);if(t.orig=e.html,B===ye)return;s.transact(()=>{for(const v of be(B,ye))v.deleteCount>0&&A.delete(d.index+v.index,v.deleteCount),v.insertText&&A.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ve);return}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),T=!1,S(d=>d+1);return}const z=m.toString().slice(r.index,n.index),he=me(t.orig,z,e.html);t.orig=e.html,z!==he&&a.collab.applySplices(be(z,he).map(d=>({...d,index:d.index+r.index})))},pe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>Ee(t))},xe=()=>{k()};return a.collab.text.observe(xe),window.addEventListener("message",pe),()=>{_?.current===le&&(_.current=null),O=!1,H.close(),re=!0,clearTimeout(ne),clearTimeout(Se),clearTimeout(Re),clearTimeout(g),a.collab.text.unobserve(xe),setTimeout(()=>{window.removeEventListener("message",pe),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,f,$]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),Te&&!we&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ue as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js b/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js deleted file mode 100644 index e70cdd90..00000000 --- a/internal/webapp/static/assets/VisualEdit-D4m3q3oV.js +++ /dev/null @@ -1 +0,0 @@ -import{r as u,j as E,w as Te,a as Se}from"./index-DRxt8NHx.js";import{o as Re,D as ke,c as L,a as O,m as de,d as fe}from"./sharedfile-BBwLL1qp.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Ee=50,Le=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function Pe(){let o=null;const l=new Map;let x=0,h=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),j=c=>{const f=c.catch(()=>{}).finally(()=>{o===f&&(o=null)});o=f};return{enqueue(c){if(o){j(o.then(c));return}try{const f=c();Le(f)&&j(Promise.resolve(f))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,f,I=!1){if(await P(),h||f())return;const p=++x;let W;const _=new Promise(M=>{l.set(p,M),W=setInterval(()=>{!h&&!f()||(l.delete(p),M())},Ee)});try{c(I?{type:"bd-edit:flush",id:p,lock:!0}:{type:"bd-edit:flush",id:p}),await _}finally{clearInterval(W)}await P()},close(){h=!0;for(const c of l.values())c();l.clear()}}}async function je(o,l,x){let h=!1;try{return await o(),h=await l(),h}finally{h||x()}}async function We(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(x=>x.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ie({apiBase:o,fileURL:l,path:x,initial:h,me:P,onStateChange:j,onCollab:c,onPeers:f,onConflictCopy:I,baseSha:p,onSaved:W,onWriting:_,onRendered:M,handle:q}){const T=u.useRef(null),[Q,xe]=u.useState(null),[he,U]=u.useState(!1),[pe,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:j,onCollab:c,onPeers:f,onSaved:W,onWriting:_,onRendered:M,onConflictCopy:I});y.current={onStateChange:j,onCollab:c,onPeers:f,onSaved:W,onWriting:_,onRendered:M,onConflictCopy:I};const G=u.useRef(h),J=u.useRef(P);J.current=P;const B=u.useRef(p);B.current=p;const ee=u.useRef(null);return u.useEffect(()=>{ee.current?.rebase(p)},[p]),u.useEffect(()=>{let R=null,F=!1,s=null,g;const ye=700;U(!1),X(!1);const me=setTimeout(()=>{!b&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),ge=setTimeout(()=>X(!0),24e3),H=Pe();let V=!1;const we=async e=>{const t=T.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!V||r||T.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},C=new Map,te=async()=>{const e=T.current?.contentWindow;if(!e)return()=>{};C.set(e,(C.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(C.get(e)??1)-1;if(r>0){C.set(e,r);return}C.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await we(!0)}catch(r){throw i(),r}return i},a=ee.current=Re({apiBase:o,path:x,seed:G.current,baseSha:B.current,who:J.current?.name,me:J.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>Se(x,e),onShrinkWithdrawn:Te,beforeJoin:async()=>s?te():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(b&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:O(a.collab.text,m.index),to:O(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),b=!1,t!==i&&S(r=>r+1);e.destroy()}F=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),F=!0,k()},onStalled:()=>{F||s||(s=new ke,s.getText("body").insert(0,G.current),F=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ne=null;const re={...a,saveNow:()=>{let e=()=>{};return ne??=je(async()=>{e=await te()},()=>a.saveNow(),()=>e()).finally(()=>{ne=null})}};q&&(q.current=re);const w=new Map,oe=e=>e.start+","+e.end,k=async()=>{if(b||!R||!F)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await We(t);if(i!==null?i!==se:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(oe(n),{from:O(e,n.start),to:O(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});b=!0,U(!0),y.current.onRendered?.()};let se="",Y=-1,b=!1;const be=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){xe("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,se=e.hash,Y=e.len,V=!0,k();if(e.type==="bd-edit:patch"){if(!b)return k().then(()=>ie(e));ie(e)}},ie=e=>{const t=w.get(oe(e));if(!t)return;if(s){const d=L(t.from,s),A=L(t.to,s);if(!d||!A||d.index>A.index)return;const D=s.getText("body"),ve=A.index-d.index;if(d.index===0&&A.index===D.length&&t.spant.span*4+256){w.clear(),b=!1,S(v=>v+1);return}const K=D.toString().slice(d.index,A.index),ue=de(t.orig,K,e.html);if(t.orig=e.html,K===ue)return;s.transact(()=>{for(const v of fe(K,ue))v.deleteCount>0&&D.delete(d.index+v.index,v.deleteCount),v.insertText&&D.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ye);return}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),b=!1,S(d=>d+1);return}const z=m.toString().slice(r.index,n.index),le=de(t.orig,z,e.html);t.orig=e.html,z!==le&&a.collab.applySplices(fe(z,le).map(d=>({...d,index:d.index+r.index})))},ae=e=>{if(!T.current||e.source!==T.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>be(t))},ce=()=>{k()};return a.collab.text.observe(ce),window.addEventListener("message",ae),()=>{q?.current===re&&(q.current=null),V=!1,H.close(),clearTimeout(me),clearTimeout(ge),clearTimeout(g),a.collab.text.unobserve(ce),setTimeout(()=>{window.removeEventListener("message",ae),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,x,$]),E.jsxs(E.Fragment,{children:[Q&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:Q}),pe&&!he&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:T,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:x},$)]})}export{Ie as VisualEdit}; diff --git a/internal/webapp/static/assets/index-DRxt8NHx.js b/internal/webapp/static/assets/index-Dib7WV0J.js similarity index 99% rename from internal/webapp/static/assets/index-DRxt8NHx.js rename to internal/webapp/static/assets/index-Dib7WV0J.js index 1e3725ae..1d05b3b0 100644 --- a/internal/webapp/static/assets/index-DRxt8NHx.js +++ b/internal/webapp/static/assets/index-Dib7WV0J.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-RcQTadDR.js","assets/sharedfile-BBwLL1qp.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-D4m3q3oV.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Bx08jARu.js","assets/sharedfile-gwqfKQrv.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-BgeFGAnP.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-RcQTadDR.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-D4m3q3oV.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Bx08jARu.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-BgeFGAnP.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w}; +`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,SV as c,qB as d,GB as e,kf as f,Mo as g,BB as h,BM as i,o as j,PB as k,YB as l,KB as m,xV as n,ZB as o,Sn as p,b as r,uy as s,Ne as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-BBwLL1qp.js b/internal/webapp/static/assets/sharedfile-gwqfKQrv.js similarity index 99% rename from internal/webapp/static/assets/sharedfile-BBwLL1qp.js rename to internal/webapp/static/assets/sharedfile-gwqfKQrv.js index 668d9ae9..3e1e9ed4 100644 --- a/internal/webapp/static/assets/sharedfile-BBwLL1qp.js +++ b/internal/webapp/static/assets/sharedfile-gwqfKQrv.js @@ -1,4 +1,4 @@ -import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-DRxt8NHx.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +import{H as et,i as En,k as Jt,l as Qo,m as xr,n as de,f as Lr,g as Or}from"./index-Dib7WV0J.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=` `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})() BearDrive - + diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js index f7cb2f72..ccbf93c5 100644 --- a/internal/webapp/static/inline-edit.js +++ b/internal/webapp/static/inline-edit.js @@ -1,21 +1,21 @@ -(function(){"use strict";var Nr=Object.defineProperty,al=(n,e)=>{let t={};for(var r in n)Nr(t,r,{get:n[r],enumerable:!0});return Nr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Er(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Ir(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=vr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Rr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Rr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Rr(s.content,e-i-1,t-i-1)))}function vr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=vr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function cl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Pr(n,e,t,0)}function Pr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Pe(n.nodeAfter,r),s++));for(let l=s;li&&Cn(n,e,i+1),o=r.depth>i&&Cn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Br(s,o),Pe(Be(s,zr(n,e,t,r,i+1)),l)):(s&&Pe(Be(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Pe(Be(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Cn(n,e,t+1);Pe(Be(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function fl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Fr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Lr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};ze.prototype.text=void 0;class jt extends ze{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Lr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Lr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Fe{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new pl(e,t);if(r.next==null)return Fe.empty;let i=Vr(r);r.next&&r.err("Unexpected trailing text");let s=Sl(xl(i));return Ml(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}Fe.empty=new Fe(!0);class pl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Vr(n){let e=[];do e.push(ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ml(n){let e=[];do e.push(gl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function gl(n){let e=kl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=yl(n,e);else break;return e}function $r(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function yl(n,e){let t=$r(n),r=t;return n.eat(",")&&(n.next!="}"?r=$r(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function bl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function kl(n){if(n.eat("(")){let e=Vr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=bl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function xl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Fe(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Hr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ze(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new ze(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new ze(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new rl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Cl(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class wl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Cl(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Kr(e,i.attrs),this.excluded=null;let s=Jr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Hr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Ur{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=_r.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Fe.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Gr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Gr(this,o.split(" "))}this.nodeFromJSON=i=>ze.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _r){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Gr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Tl(n){return n.tag!=null}function Ol(n){return n.style!=null}class de{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Tl(i))this.tags.push(i);else if(Ol(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Zr(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Zr(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ei(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ei(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new de(e,de.schemaRules(e)))}}const Yr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Nl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Xr={ol:!0,ul:!0},gt=1,wn=2,yt=4;function Qr(n,e,t){return e!=null?(e?gt:0)|(e==="full"?wn:0):n&&n.whitespace=="pre"?gt|wn:t&~yt}class Ht{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Yr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Zr{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Qr(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new Ht(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Ht(null,null,E.none,!0,null,o):s=new Ht(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&wn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ti(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Ht(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function El(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Xr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Dl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ei(n){let e={};for(let t in n)e[t]=n[t];return e}function ti(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(qt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Le(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ni(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ni(e.marks)}}function ni(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function qt(n){return n.document||window.document}const ri=new WeakMap;function Al(n){let e=ri.get(n);return e===void 0&&ri.set(n,e=Il(n)),e}function Il(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const ii=65535,si=Math.pow(2,16);function Rl(n,e){return n+e*si}function oi(n){return n&ii}function vl(n){return(n-(n&ii))/si}const li=1,ai=2,_t=4,ci=8;class Tn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ci)>0}get deletedBefore(){return(this.delInfo&(li|_t))>0}get deletedAfter(){return(this.delInfo&(ai|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=oi(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Rl(l/3,e-a),m=e==a?ai:e==u?li:_t;return(t<0?e!=a:e!=u)&&(m|=ci),new Tn(h,m,p)}i+=f-c}return r?e+i:new Tn(e+i,0,null)}touches(e,t){let r=0,i=oi(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xe(t.pos,r.pos,this.mark)}merge(e){return e instanceof xe&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xe(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new xe(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",xe);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Nn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new xe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Se extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function En(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Pl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Bl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function Dn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function zl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function et(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Wl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&jl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&hi(n,o,l,s),Dn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&di(n,o,l,s),!1}})}function di(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function hi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function jl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Jl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function he(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Hl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function $e(n,e){let t=n.resolve(e),r=t.index();return pi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&pi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Kl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);hi(n,f.node(),f.before(),l)}o.inlineContent&&Dn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);di(n,f.node(),f.before(),n.steps.length)}return n}function _l(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return mi(i,s,r)?new R(e,t,r):new Gl(i,s,r).fit()}function mi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Gl{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=gi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return bi(e,-1)<=t?!1:(this.unplaced.size>1&&bi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=gi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(yi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=An(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function gi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,yi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function An(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Yl(t,s.content,o)?l:null}function Yl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=Xl(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function ki(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Zl(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=_l(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ea(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=xi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function xi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class tt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new tt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new tt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new tt(t.pos,t.attr,t.value)}}W.jsonID("attr",tt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let nt=class extends Error{};nt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},nt.prototype=Object.create(Error.prototype),nt.prototype.constructor=nt,nt.prototype.name="TransformError";class Si{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new nt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Ql(this,e,t,r),this}replaceRangeWith(e,t,r){return Zl(this,e,t,r),this}deleteRange(e,t){return ea(this,e,t),this}lift(e,t){return Fl(this,e,t),this}join(e,t=1){return Kl(this,e,t),this}wrap(e,t){return $l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Wl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Jl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new tt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Se(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new Ve(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Ve(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Hl(this,e,t,r),this}addMark(e,t,r){return Pl(this,e,t,r),this}removeMark(e,t,r){return Bl(this,e,t,r),this}clearIncompatible(e,t,r){return Dn(this,e,t,r),this}}const In=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ta(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?rt(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):rt(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return rt(e,e,0,0,1)||new U(e)}static atEnd(e){return rt(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=In[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in In)throw new RangeError("Duplicate use of selection JSON ID "+e);return In[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ta{constructor(e,t){this.$from=e,this.$to=t}}let Mi=!1;function Ci(n){!Mi&&!n.parent.inlineContent&&(Mi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ci(e),Ci(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=rt(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function wi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ti=1,Xt=2,Oi=4;class ra extends Si{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Oi,this}get scrolledIntoView(){return(this.updated&Oi)>0}}function Ni(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ni(t.init,r),this.apply=Ni(t.apply,r)}}const ia=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class vn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ia.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class it{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new vn(e.schema,e.plugins),s=new it(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=ze.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ei(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ei(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ei(e.props,this,this.props),this.key=e.key?e.key.key:Di("plugin")}getState(e){return e[this.key]}}const Pn=Object.create(null);function Di(n){return n in Pn?n+"$"+ ++Pn[n]:(Pn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Di(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ai=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ii(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Ri=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Bn(r);if(!i){let o=r.blockRange(),l=o&&et(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(ji(n,i,e,-1))return!0;if(r.parent.content.size==0&&(st(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},sa=(n,e,t)=>{let r=Ii(n,t);if(!r)return!1;let i=Bn(r);return i?vi(n,i,e):!1},oa=(n,e,t)=>{let r=Bi(n,t);if(!r)return!1;let i=zn(r);return i?vi(n,i,e):!1};function vi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function st(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Pi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Bn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Bn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Bi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Bi(n,t);if(!r)return!1;let i=zn(r);if(!i)return!1;let s=i.nodeAfter;if(ji(n,i,e,1))return!0;if(r.parent.content.size==0&&(st(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!$e(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},aa=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!$e(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ca=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&et(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Li=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function Fn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Fn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},$i=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Fn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(he(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&et(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function fa(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!he(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Fn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=he(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=he(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ua=fa(),da=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ha=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function pa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||$e(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function ji(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&pa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&$e(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&et(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&st(s,"start",!0)&&st(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ji(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Hi=Ji(-1),qi=Ji(1);function ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&fi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ki(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function _i(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ga(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ma(e,t,n,s):Ca(e,t,s):!0:!1}}function Ma(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function wa(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},ot=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let $n=null;const me=function(n,e,t){let r=$n||($n=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ta=function(){$n=null},We=function(n,e,t,r){return t&&(Yi(n,e,t,r,-1)||Yi(n,e,t,r,1))},Oa=/^(img|br|input|textarea|hr)$/i;function Yi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Oa.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Na(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ea(n,e){for(;;){if(n.nodeType==3&&e2),ee=lt||(ce?/Mac/.test(ce.platform):!1),es=ce?/Win/.test(ce.platform):!1,ge=/Android \d/.test(Me),wt=!!Xi&&"webkitFontSmoothing"in Xi.documentElement.style,Ra=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function va(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ye(n,e){return typeof n=="number"?n:n[e]}function Pa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function ts(n,e,t){if(!qn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=ot(o);continue}let l=o,a=l==s.body,c=a?va(s):Pa(l),f=0,u=0;if(e.topc.bottom-ye(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+ye(i,"top")-c.top:e.bottom-c.bottom+ye(i,"bottom")),e.leftc.right-ye(r,"right")&&(f=e.right-c.right+ye(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:ot(o)}}function Ba(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ns(n.dom)}}function ns(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=ot(r));return e}function za({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;rs(t,r==0?0:r-e)}function rs(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?La(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:is(t,i)}function La(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Va(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Wa(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function ss(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Wa(n,r,i,e))}l==null&&(l=$a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function qn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(we(me(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Kn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?me(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(we(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Kn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function as(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ha(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return as(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=ls(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=me(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const qa=/[\u0590-\u08ac]/;function Ka(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:as(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let cs=null,fs=null,us=!1;function _a(n,e,t){return cs==e&&fs==t?us:(cs=e,fs=t,us=t=="up"||t=="down"?Ha(n,e,t):Ka(n,e,t))}const te=0,ds=1,Je=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ms){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof hs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Je:ds,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Je:se}r=o}this.dirty=Je}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Je:ds;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Ua extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Te extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Le.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Te(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Un(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Le.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=bs(f,r,t),c?a=new Ga(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Oe(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Xa(this,o&&o.node,e);ec(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Je)&&(o&&this.protectLocalComposition(e,o),gs(this.contentDOM,this.children,e),lt&&tc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=nc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Ua(this,s,t,i);e.input.compositionNodes.push(o),this.children=Un(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ys(this.dom,this.nodeDOM,_n(this.outerDeco,this.node,t),_n(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ps(n,e,t,r,i){bs(r,e,n);let s=new Oe(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Oe{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ms extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ga extends Oe{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function gs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Te.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Te)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Za(n,e){return n.type.side-e.type.side}function ec(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function tc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function nc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Un(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Gn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Da(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!xs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function ic(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&Ce<=11&&(t.disabled=!0,t.disabled=!1)}function ws(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ts(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ts(n)}function Ts(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Xn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Os(n){return n.editable&&!n.hasFocus()?!1:Ns(n)}function Ns(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function sc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return We(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Qn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ne(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Es(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ne(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Qn(n.state,e);return i&&i instanceof x?Ne(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ne(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ne(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ne(n,new S(e>0?r.$to:r.$from));{let i=Qn(n.state,e);return i?Ne(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ct(n,e){return e<0?oc(n):lc(n)}function oc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Ds(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Zn(n,t,r):i&&Zn(n,i,s)}function lc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&be(n)},50)}function As(n,e){let t=n.state.doc.resolve(e);if(!(V||es)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Is(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Qn(n.state,e);if(o&&o instanceof x)return Ne(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ne(n,l):!1}return!1}function Rs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function vs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function fc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;vs(n,r,"true"),setTimeout(()=>vs(n,r,"false"),20)}return!1}function uc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function dc(n,e){let t=e.keyCode,r=uc(e);if(t==8||ee&&t==72&&r=="c")return Rs(n,-1)||ct(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Rs(n,1)||ct(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?As(n,n.state.selection.from)=="ltr"?-1:1:-1;return Es(n,i,r)||ct(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?As(n,n.state.selection.from)=="ltr"?1:-1:1;return Es(n,i,r)||ct(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Is(n,-1,r)||ct(n,-1);if(t==40||ee&&t==78&&r=="c")return fc(n)||Is(n,1,r)||ct(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function er(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Le.fromSchema(n.state.schema),l=$s(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Vs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` +(function(){"use strict";var Ar=Object.defineProperty,ml=(n,e)=>{let t={};for(var r in n)Ar(t,r,{get:n[r],enumerable:!0});return Ar(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ir(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Pr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=zr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Br(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Br(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Br(s.content,e-i-1,t-i-1)))}function zr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=zr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function gl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Fr(n,e,t,0)}function Fr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&wn(n,e,i+1),o=r.depth>i&&wn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Lr(s,o),Be(ze(s,Vr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=wn(n,e,t+1);Be(ze(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function yl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=$r.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Wr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Wr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Wr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new Sl(e,t);if(r.next==null)return Le.empty;let i=jr(r);r.next&&r.err("Unexpected trailing text");let s=El(Nl(i));return Dl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Le.empty=new Le(!0);class Sl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function jr(n){let e=[];do e.push(Ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Ml(n){let e=[];do e.push(Cl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Cl(n){let e=Ol(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=wl(n,e);else break;return e}function Jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function wl(n,e){let t=Jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Tl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Ol(n){if(n.eat("(")){let e=jr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Tl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Nl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:_r(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new fl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Al(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Il{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Al(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Gr(e,i.attrs),this.excluded=null;let s=Kr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,_r(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Xr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Yr.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Qr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Qr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Yr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Qr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Rl(n){return n.tag!=null}function vl(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Rl(i))this.tags.push(i);else if(vl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ni(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ni(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ri(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ri(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Zr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Pl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},ei={ol:!0,ul:!0},gt=1,Tn=2,yt=4;function ti(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Tn:0):n&&n.whitespace=="pre"?gt|Tn:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Zr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ni{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ti(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Tn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ii(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Bl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&ei.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function zl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ri(n){let e={};for(let t in n)e[t]=n[t];return e}function ii(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=si(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return si(e.marks)}}function si(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const oi=new WeakMap;function Fl(n){let e=oi.get(n);return e===void 0&&oi.set(n,e=Ll(n)),e}function Ll(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const li=65535,ai=Math.pow(2,16);function Vl(n,e){return n+e*ai}function ci(n){return n&li}function $l(n){return(n-(n&li))/ai}const fi=1,ui=2,_t=4,di=8;class On{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&di)>0}get deletedBefore(){return(this.delInfo&(fi|_t))>0}get deletedAfter(){return(this.delInfo&(ui|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ci(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Vl(l/3,e-a),m=e==a?ui:e==u?fi:_t;return(t<0?e!=a:e!=u)&&(m|=di),new On(h,m,p)}i+=f-c}return r?e+i:new On(e+i,0,null)}touches(e,t){let r=0,i=ci(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(En(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Dn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Wl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function jl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function An(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Jl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Ul(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Gl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&gi(n,o,l,s),An(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&mi(n,o,l,s),!1}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function gi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function Gl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Yl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Xl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return yi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&yi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Zl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);gi(n,f.node(),f.before(),l)}o.inlineContent&&An(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);mi(n,f.node(),f.before(),n.steps.length)}return n}function ea(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return bi(i,s,r)?new R(e,t,r):new na(i,s,r).fit()}function bi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class na{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=ki(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return Si(e,-1)<=t?!1:(this.unplaced.size>1&&Si(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=ki(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(xi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=In(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function ki(n,e){for(let t=0;t1&&(r=r.replaceChild(0,xi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function In(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!ra(t,s.content,o)?l:null}function ra(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=ia(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Mi(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function oa(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=ea(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function la(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Ci(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Ci(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class wi{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return sa(this,e,t,r),this}replaceRangeWith(e,t,r){return oa(this,e,t,r),this}deleteRange(e,t){return la(this,e,t),this}lift(e,t){return ql(this,e,t),this}join(e,t=1){return Zl(this,e,t),this}wrap(e,t){return _l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Ul(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Yl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Xl(this,e,t,r),this}addMark(e,t,r){return Wl(this,e,t,r),this}removeMark(e,t,r){return jl(this,e,t,r),this}clearIncompatible(e,t,r){return An(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new aa(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class aa{constructor(e,t){this.$from=e,this.$to=t}}let Ti=!1;function Oi(n){!Ti&&!n.parent.inlineContent&&(Ti=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Oi(e),Oi(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ni(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ei=1,Xt=2,Di=4;class fa extends wi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Di,this}get scrolledIntoView(){return(this.updated&Di)>0}}function Ai(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ai(t.init,r),this.apply=Ai(t.apply,r)}}const ua=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Pn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ua.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Pn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ii(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ii(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ii(e.props,this,this.props),this.key=e.key?e.key.key:Ri("plugin")}getState(e){return e[this.key]}}const Bn=Object.create(null);function Ri(n){return n in Bn?n+"$"+ ++Bn[n]:(Bn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ri(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const vi=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Pi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Bi=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=zn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Hi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},da=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=zn(r);return i?zi(n,i,e):!1},ha=(n,e,t)=>{let r=Li(n,t);if(!r)return!1;let i=Fn(r);return i?zi(n,i,e):!1};function zi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Fi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=zn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function zn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Li(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Li(n,t);if(!r)return!1;let i=Fn(r);if(!i)return!1;let s=i.nodeAfter;if(Hi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ma=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ga=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Wi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Ln(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Ln(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Ln(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ya(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Ln(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ba=ya(),ka=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},xa=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function Sa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Hi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&Sa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ki(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const _i=Ki(-1),Ui=Ki(1);function Ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&hi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Gi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Yi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!Ca(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Da(e,t,n,s):Aa(e,t,s):!0:!1}}function Da(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ia(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Wn=null;const ge=function(n,e,t){let r=Wn||(Wn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ra=function(){Wn=null},je=function(n,e,t,r){return t&&(Zi(n,e,t,r,-1)||Zi(n,e,t,r,1))},va=/^(img|br|input|textarea|hr)$/i;function Zi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||va.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Pa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ba(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),rs=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!es&&"webkitFontSmoothing"in es.documentElement.style,Va=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function $a(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Wa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function is(n,e,t){if(!Kn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?$a(s):Wa(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function ja(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ss(n.dom)}}function ss(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Ja({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ls(t,r==0?0:r-e)}function ls(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Ha(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:as(t,i)}function Ha(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Ka(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ua(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function cs(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ua(n,r,i,e))}l==null&&(l=_a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Kn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return _n(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function _n(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function us(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Xa(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return us(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=fs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Qa=/[\u0590-\u08ac]/;function Za(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:us(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let ds=null,hs=null,ps=!1;function ec(n,e,t){return ds==e&&hs==t?ps:(ds=e,hs=t,ps=t=="up"||t=="down"?Xa(n,e,t):Za(n,e,t))}const te=0,ms=1,qe=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof bs){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof gs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?qe:ms,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?qe:se}r=o}this.dirty=qe}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?qe:ms;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class tc extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Gn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=Ss(f,r,t),c?a=new nc(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new ic(this,o&&o.node,e);lc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==qe)&&(o&&this.protectLocalComposition(e,o),ks(this.contentDOM,this.children,e),at&&ac(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=cc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new tc(this,s,t,i);e.input.compositionNodes.push(o),this.children=Gn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=xs(this.dom,this.nodeDOM,Un(this.outerDeco,this.node,t),Un(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ys(n,e,t,r,i){Ss(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class bs extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class nc extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function ks(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function oc(n,e){return n.type.side-e.type.side}function lc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ac(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function cc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Gn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Yn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&za(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Cs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function uc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Ns(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Es(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Es(n)}function Es(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Qn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Ds(n){return n.editable&&!n.hasFocus()?!1:As(n)}function As(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function dc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Zn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Is(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Zn(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=Zn(n.state,e);return i?Ee(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?hc(n):pc(n)}function hc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Rs(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?er(n,t,r):i&&er(n,i,s)}function pc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function vs(n,e){let t=n.state.doc.resolve(e);if(!(V||rs)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ps(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Zn(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Bs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function zs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function yc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;zs(n,r,"true"),setTimeout(()=>zs(n,r,"false"),20)}return!1}function bc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function kc(n,e){let t=e.keyCode,r=bc(e);if(t==8||ee&&t==72&&r=="c")return Bs(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Bs(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?vs(n,n.state.selection.from)=="ltr"?-1:1:-1;return Is(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?vs(n,n.state.selection.from)=="ltr"?1:-1:1;return Is(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Ps(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return yc(n)||Ps(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function tr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=Js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=js[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` -`);return{dom:a,text:d,slice:e}}function Ps(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Le.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=gc(t),wt&&yc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||de.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!hc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=bc(Ls(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(pc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const hc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function pc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&zs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Fs(o[o.length-1],s.length));let f=Bs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Bs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function zs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ls(n,e,t){return et})}return Dt.createHTML(n)}function gc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=$s(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Vs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},kc={touchstart:!0,touchmove:!0};class xc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Sc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Cc(n,r)&&!rr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},kc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),nr(n)}function ke(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Mc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function nr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>rr(n,r))})}function rr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Cc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function wc(n,e){!rr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Hs(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ge&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),lt&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||dc(n,t)?t.preventDefault():ke(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Hs(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Tc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function ir(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Oc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Nc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ec(n,e,t,r,i){return ir(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Nc(n,t):Oc(n,t))}function Dc(n,e,t,r){return ir(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Ac(n,e,t,r){return ir(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ic(n,t,r)}function Ic(n,e,t){if(t.button!=0)return!1;let r=Ws(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new vc(n,r)),!0):!1}function Ws(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function sr(n){return nn(n)}const js=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=sr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Tc(t,n.input.lastClick)&&!t[js]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Rc(n,o,t,!!r):(s=="doubleClick"?Dc:Ac)(n,o.pos,o.inside,t)?t.preventDefault():ke(n,"pointer"))};class Js{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Rc extends Js{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[js],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),ke(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||be(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?ke(this.view,"pointer"):Ec(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):ke(this.view,"pointer")}move(e){this.updateAllowDefault(e),ke(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class vc extends Js{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),ke(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Ws(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),sr(n),ke(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),ke(n,"pointer")},q.contextmenu=n=>sr(n);function Hs(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Pc=ge?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&es&&Bc(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}qs(n,Pc)};function Bc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,qs(n,20))};function qs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Ks(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function zc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Na(e.focusNode,e.focusOffset),r=Ea(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ge&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Ks(n),e||n.docView&&n.docView.dirty){let t=Gn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Fc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&Ce<15||lt&&Ra<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=er(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Fc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Lc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Vc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Ps(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Lc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function _s(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ge)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,_s(r),r.getData("text/html"),i,t)?t.preventDefault():Vc(n,t)};class Us{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const $c=ee?"altKey":"ctrlKey";function Gs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[$c]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=er(n,l);(!t.dataTransfer.files.length||!V||Zi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Us(f,Gs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Wc(n,e,n.dragging)}finally{n.dragging=null}};function Wc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Ps(n,_s(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Gs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Ul(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Xn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&be(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ge&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||qe,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ee{constructor(e,t){this.attrs=e,this.spec=t||qe}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||qe)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Xs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ee){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,qe));return De.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Jc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Xs(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Ys(s?Qs(n):n,-t).sort(Ke);for(let l=0;l0;)e++;n.splice(e,0,t)}function ar(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),De.from(e)}const Hc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qc=G&&Ce<=11;class Kc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class _c{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Kc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Hc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Os(this.view)){if(this.suppressingSelectionUpdates)return be(this.view);if(G&&Ce<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&We(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=ot(s))t.add(s);for(let s=e.anchorNode;s;s=ot(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Os(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Yc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Uc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Xc(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||be(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||de.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:Zc(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const Zc=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},ef=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function tf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Gn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ge&&n.input.lastKeyCode===13&&Date.now()-100Qe(n,je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Qc(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ge)&&i.some(M=>M.nodeType==1&&!ef.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=ro(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&Ce<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((lt&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&rf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,je(8,"Backspace")))){ge&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ge&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=ro(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeletebe(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=nf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function ro(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Xn(n,e.resolve(t.anchor),e.resolve(t.head))}function nf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||cr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function sf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class io{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new xc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(co),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=lo(this),oo(this),this.nodeViews=ao(this),this.docView=ps(this.state.doc,so(this),ar(this),this.dom,this),this.domObserver=new _c(this,(r,i,s,o)=>tf(this,r,i,s,o)),this.domObserver.start(),Sc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&nr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(co),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Ks(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=ao(this);lf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&nr(this),this.editable=lo(this),oo(this);let a=ar(this),c=so(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Ba(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&of(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=zc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ps(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sc(this)&&p.delaySelUpdate())?be(this,h):(ws(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&za(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&ts(this,t.getBoundingClientRect(),e)}else ts(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ja(this,e)}coordsAtPos(e,t=1){return ls(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return _a(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return er(this,e)}destroy(){this.docView&&(Mc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ar(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ta())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return wc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Aa(this.dom.ownerDocument)==this.dom&&Gc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}io.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function so(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function oo(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function lo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function of(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function ao(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function lf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function co(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ae={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},af=typeof navigator<"u"&&/Mac/.test(navigator.platform),cf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ae[48+$]=Ae[96+$]=String($);for(var $=1;$<=24;$++)Ae[$+111]="F"+$;for(var $=65;$<=90;$++)Ae[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var fr in Ae)on.hasOwnProperty(fr)||(on[fr]=Ae[fr]);function ff(n){var e=af&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||cf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ae)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const uf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),df=typeof navigator<"u"&&/Win/.test(navigator.platform);function hf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=il.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:uo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const yf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),bf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),kf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=et(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},xf=n=>e=>n(e),Sf=()=>({state:n,dispatch:e})=>$i(n,e),Mf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Cf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const wf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Tf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Of=n=>n.content?/^text(\*|\+)/.test(n.content):!1,ho=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:ho(n,t,"left"),to:ho(e,t,"right")}),Ef=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Nf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Df=()=>({commands:n})=>n.keyboardShortcut("Enter"),Af=()=>({state:n,dispatch:e})=>Vi(n,e);function If(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:If(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function po(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function mo(n,e,t={}){return!!po(n,e,t)}function dr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!po([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&mo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ie(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=dr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},vf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||yo())&&r.dom.focus(),Bf()&&!an()&&!yo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!go(t.state.selection))return o(),!0;const l=Pf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Ff=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Lf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),bo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&bo(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return bo(t)}function ko(n){return typeof n?.nodesBetween=="function"}function ut(n,e,t){if(ko(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ut("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Ur({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?de.fromSchema(a).parseSlice(cn(n),t.parseOptions):de.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=de.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return ut("",e,t)}function xo(n){return!("type"in n)}function So(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Vf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ut(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=xo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):ko(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&So(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function Mo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=Mo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ut(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&So(e,e.steps.length-1,-1)),!0):!1},Wf=()=>({state:n,dispatch:e})=>la(n,e),jf=()=>({state:n,dispatch:e})=>aa(n,e),Jf=()=>({state:n,dispatch:e})=>Ri(n,e),Hf=()=>({state:n,dispatch:e})=>zi(n,e),qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Kf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},_f=()=>({state:n,dispatch:e})=>sa(n,e),Uf=()=>({state:n,dispatch:e})=>oa(n,e);function Co(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Gf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Gf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function hr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const Xf=(n,e={})=>({state:t,dispatch:r})=>hr(t,H(n,t.schema),e)?ca(t,r):!1,Qf=()=>({state:n,dispatch:e})=>Wi(n,e),Zf=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Sa(r)(e,t)},eu=()=>({state:n,dispatch:e})=>Li(n,e);function wo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function To(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const tu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,To(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(To(d.attrs,e))))})})}),a},nu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ru=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},iu=()=>({state:n,dispatch:e})=>Pi(n,e),su=()=>({state:n,dispatch:e})=>Fi(n,e),ou=()=>({state:n,dispatch:e})=>da(n,e),lu=()=>({state:n,dispatch:e})=>qi(n,e),au=()=>({state:n,dispatch:e})=>Hi(n,e);function cu(n,e,t={},r={}){return ut(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const fu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=cu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=xo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function uu(n,e){const t=Ie(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function du(n,e){const t=new Si(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function hu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function pr(n){return e=>hu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Oo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Oo(t())]:e}).flat(10)}function pu(n){return typeof n=="function"}function D(n,e=void 0,...t){return pu(n)?e?n.bind(e)(...t):n(...t):n}function mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function gu(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function yu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function No(n){const e=[],t=yu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...No(r[i]),...No(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Eo(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function bu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Do(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):bu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ao(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&mu(t)?!1:t!=null))}function Io(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function ku(n,e){var t;const r=gu(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Do(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Eo(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ao({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Io))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Do(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Eo(m,f)})),[c.name,d]}));return new Ur({topNode:o,nodes:l,marks:a})}function xu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Su(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Cu(n,e){return ku(Mu(n),e)}function wu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` +`);return{dom:a,text:d,slice:e}}function Fs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=Cc(t),wt&&wc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!xc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Tc(Ws(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(Sc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const xc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function Sc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Vs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=$s(o[o.length-1],s.length));let f=Ls(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Ls(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Vs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ws(n,e,t){return et})}return Dt.createHTML(n)}function Cc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&js[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=Mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const H={},K={},Oc={touchstart:!0,touchmove:!0};class Nc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Ec(n){for(let e in H){let t=H[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Ac(n,r)&&!ir(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},Oc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),rr(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Dc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function rr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>ir(n,r))})}function ir(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Ac(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Ic(n,e){!ir(n,e)&&H[e.type]&&(n.editable||!(e.type in K))&&H[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!_s(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||kc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(_s(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Rc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function sr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function vc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Pc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Bc(n,e,t,r,i){return sr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Pc(n,t):vc(n,t))}function zc(n,e,t,r){return sr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Fc(n,e,t,r){return sr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Lc(n,t,r)}function Lc(n,e,t){if(t.button!=0)return!1;let r=qs(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new $c(n,r)),!0):!1}function qs(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function or(n){return nn(n)}const Hs=ee?"metaKey":"ctrlKey";H.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=or(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Rc(t,n.input.lastClick)&&!t[Hs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Vc(n,o,t,!!r):(s=="doubleClick"?zc:Fc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class Ks{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Vc extends Ks{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Hs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):Bc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class $c extends Ks{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&qs(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),or(n),xe(n,"pointer")},H.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},H.contextmenu=n=>or(n);function _s(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Wc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&rs&&jc(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Us(n,Wc)};function jc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Us(n,20))};function Us(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Gs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Jc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Pa(e.focusNode,e.focusOffset),r=Ba(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Gs(n),e||n.docView&&n.docView.dirty){let t=Yn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function qc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&we<15||at&&Va<604;H.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=tr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):qc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Hc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Kc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Fs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Hc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Ys(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,Ys(r),r.getData("text/html"),i,t)?t.preventDefault():Kc(n,t)};class Xs{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const _c=ee?"altKey":"ctrlKey";function Qs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[_c]}H.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=tr(n,l);(!t.dataTransfer.files.length||!V||ns>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Xs(f,Qs(n,t),o)},H.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Uc(n,e,n.dragging)}finally{n.dragging=null}};function Uc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Fs(n,Ys(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Qs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?ta(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Qn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}H.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},H.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},H.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)H[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=eo(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Yc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=eo(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Zs(s?to(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function cr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const Xc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Qc=G&&we<=11;class Zc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class ef{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Zc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Xc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Ds(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Ds(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||rf(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),tf(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,sf(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:lf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const lf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},af=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function cf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Yn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=of(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!af.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=oo(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&uf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=oo(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=ff(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function oo(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Qn(n,e.resolve(t.anchor),e.resolve(t.head))}function ff(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||fr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function df(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class lo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Nc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(ho),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=fo(this),co(this),this.nodeViews=uo(this),this.docView=ys(this.state.doc,ao(this),cr(this),this.dom,this),this.domObserver=new ef(this,(r,i,s,o)=>cf(this,r,i,s,o)),this.domObserver.start(),Ec(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&rr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(ho),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Gs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=uo(this);pf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&rr(this),this.editable=fo(this),co(this);let a=cr(this),c=ao(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&ja(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&hf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Jc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ys(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&dc(this)&&p.delaySelUpdate())?ke(this,h):(Ns(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ja(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&is(this,t.getBoundingClientRect(),e)}else is(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Ga(this,e)}coordsAtPos(e,t=1){return fs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return ec(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return tr(this,e)}destroy(){this.docView&&(Dc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],cr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ra())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Ic(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Fa(this.dom.ownerDocument)==this.dom&&nf(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}lo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function ao(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function co(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function fo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function hf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function uo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function pf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function ho(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mf=typeof navigator<"u"&&/Mac/.test(navigator.platform),gf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var ur in Ie)on.hasOwnProperty(ur)||(on[ur]=Ie[ur]);function yf(n){var e=mf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||gf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const bf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),kf=typeof navigator<"u"&&/Win/.test(navigator.platform);function xf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=ul.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:mo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const wf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Tf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),Of=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Nf=n=>e=>n(e),Ef=()=>({state:n,dispatch:e})=>Ji(n,e),Df=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Af=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function q(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const If=n=>({tr:e,state:t,dispatch:r})=>{const i=q(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Rf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},vf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,go=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:go(n,t,"left"),to:go(e,t,"right")}),Bf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Pf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},zf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Ff=()=>({state:n,dispatch:e})=>ji(n,e);function Lf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Lf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function yo(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function bo(n,e,t={}){return!!yo(n,e,t)}function hr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!yo([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&bo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Re(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=hr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},$f=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||xo())&&r.dom.focus(),jf()&&!an()&&!xo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!ko(t.state.selection))return o(),!0;const l=Wf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},qf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Hf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),So=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&So(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return So(t)}function Mo(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(Mo(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Xr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(cn(n),t.parseOptions):he.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return dt("",e,t)}function Co(n){return!("type"in n)}function wo(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Kf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Co(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):Mo(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&wo(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function To(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=To(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&wo(e,e.steps.length-1,-1)),!0):!1},Uf=()=>({state:n,dispatch:e})=>pa(n,e),Gf=()=>({state:n,dispatch:e})=>ma(n,e),Yf=()=>({state:n,dispatch:e})=>Bi(n,e),Xf=()=>({state:n,dispatch:e})=>Vi(n,e),Qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Zf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},eu=()=>({state:n,dispatch:e})=>da(n,e),tu=()=>({state:n,dispatch:e})=>ha(n,e);function Oo(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function nu(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=nu(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function pr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?q(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const iu=(n,e={})=>({state:t,dispatch:r})=>pr(t,q(n,t.schema),e)?ga(t,r):!1,su=()=>({state:n,dispatch:e})=>qi(n,e),ou=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Ea(r)(e,t)},lu=()=>({state:n,dispatch:e})=>Wi(n,e);function No(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Eo(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const au=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=No(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,Eo(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(Eo(d.attrs,e))))})})}),a},cu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),fu=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},uu=()=>({state:n,dispatch:e})=>Fi(n,e),du=()=>({state:n,dispatch:e})=>$i(n,e),hu=()=>({state:n,dispatch:e})=>ka(n,e),pu=()=>({state:n,dispatch:e})=>Ui(n,e),mu=()=>({state:n,dispatch:e})=>_i(n,e);function gu(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const yu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=gu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Co(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function bu(n,e){const t=Re(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function ku(n,e){const t=new wi(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function xu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function mr(n){return e=>xu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Do(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Do(t())]:e}).flat(10)}function Su(n){return typeof n=="function"}function D(n,e=void 0,...t){return Su(n)?e?n.bind(e)(...t):n(...t):n}function Mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function Cu(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function wu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Ao(n){const e=[],t=wu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Ao(r[i]),...Ao(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Io(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function Tu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Ro(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Tu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function vo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&Mu(t)?!1:t!=null))}function Po(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Ou(n,e){var t;const r=Cu(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Po))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Ro(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Io(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Po))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Ro(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Io(m,f)})),[c.name,d]}));return new Xr({topNode:o,nodes:l,marks:a})}function Nu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Eu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Au(n,e){return Ou(Du(n),e)}function Iu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Tu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Ou(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Nu(n){const e=Ou(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Eu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Nu(r)}function Ro(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=dr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Du(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ie(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function mr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function vo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(vo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Au(n,e,t){const{selection:r}=e;let i=null;if(go(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Iu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ie(n,r.schema);if(i)if(o){const c=uu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Au(r,t,a)},Ru=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),vu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ki(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ki(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=_e(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Bu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},zu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=_e(i,o,l),c=_e(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},Fu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)};function Po(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Lu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!he(o,l.pos)?!1:(r&&(n&&Po(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:Mo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=he(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&he(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Po(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Vu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!he(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Bo(n){return!n||n==="1"?null:n}function zo(n,e){return Bo(n)===Bo(e)}const gr=(n,e)=>{const t=pr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,t.pos))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},yr=(n,e)=>{const t=pr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&$e(n.doc,r))||!zo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function $u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Wu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=pr(Ze=>mr(Ze.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&mr(N.type.name,u)?{node:N,pos:0}:null,Qe=_??v,Vd=!!_&&w.depth>=1&&w.depth-_.depth<=1,nl=!!v;if((Vd||nl)&&Qe){if(Qe.node.type===h)return ne&&nl?a().command(({tr:Ze,dispatch:xn})=>{const Sn=$u(Ze);return Sn?(Ze.setSelection(Sn),xn&&xn(Ze),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(mr(Qe.node.type.name,u)&&h.validContent(Qe.node.content))return a().command(()=>(s.setNodeMarkup(Qe.pos,h),!0)).command(()=>gr(s,h)).command(()=>yr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>gr(s,h)).command(()=>yr(s,h)).run():a().command(()=>{const Ze=f().wrapInList(h,r),xn=A.filter(Sn=>d.includes(Sn.type.name));return s.ensureMarks(xn),Ze?!0:c.clearNodes()}).wrapInList(h,r).command(()=>gr(s,h)).command(()=>yr(s,h)).run()},ju=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ie(n,r.schema);return Du(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ju=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=hr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Hu=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return hr(t,i,e)?r.lift(i):r.wrapIn(i,e)},qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Ku=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},_u=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ie(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=dr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Uu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Gu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=wo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Ie(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Yu=new ie("__tiptap_decorations__"),Xu=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Yu,{type:"force",name:n}),!0),Qu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ma(i,e)(t,r)},Zu=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)};var ed=al({blur:()=>yf,clearContent:()=>bf,clearNodes:()=>kf,command:()=>xf,createParagraphNear:()=>Sf,cut:()=>Mf,deleteCurrentNode:()=>Cf,deleteNode:()=>wf,deleteRange:()=>Tf,deleteSelection:()=>Ef,enter:()=>Df,exitCode:()=>Af,extendMarkRange:()=>Rf,first:()=>vf,focus:()=>zf,forEach:()=>Ff,insertContent:()=>Lf,insertContentAt:()=>Vf,insertDefaultBlock:()=>$f,joinBackward:()=>Jf,joinDown:()=>jf,joinForward:()=>Hf,joinItemBackward:()=>qf,joinItemForward:()=>Kf,joinTextblockBackward:()=>_f,joinTextblockForward:()=>Uf,joinUp:()=>Wf,keyboardShortcut:()=>Yf,lift:()=>Xf,liftEmptyBlock:()=>Qf,liftListItem:()=>Zf,newlineInCode:()=>eu,resetAttributes:()=>tu,scrollIntoView:()=>nu,selectAll:()=>ru,selectNodeBackward:()=>iu,selectNodeForward:()=>su,selectParentNode:()=>ou,selectTextblockEnd:()=>lu,selectTextblockStart:()=>au,setContent:()=>fu,setMark:()=>Iu,setMeta:()=>Ru,setNode:()=>vu,setNodeSelection:()=>Pu,setTextDirection:()=>Bu,setTextSelection:()=>zu,sinkListItem:()=>Fu,splitBlock:()=>Lu,splitListItem:()=>Vu,toggleList:()=>Wu,toggleMark:()=>ju,toggleNode:()=>Ju,toggleWrap:()=>Hu,undoInputRule:()=>qu,unsetAllMarks:()=>Ku,unsetMark:()=>_u,unsetTextDirection:()=>Uu,updateAttributes:()=>Gu,updateDecorations:()=>Xu,wrapIn:()=>Qu,wrapInList:()=>Zu});typeof process<"u"&&process.env.NODE_ENV;function td(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return td(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Fo(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=Fo(n[r],e[r]):t[r]=e[r]}),t}var nd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},br=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Fo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class sl extends br{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new sl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},rd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ol extends br{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ol(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Tu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>wu(r,{from:a.pos,to:c.pos},l)).join(o??` +`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Ru(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function vu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Pu(n){const e=vu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Bu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Pu(r)}function Bo(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=hr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function zu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Re(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function gr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function zo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(zo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Fu(n,e,t){const{selection:r}=e;let i=null;if(ko(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Lu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Re(n,r.schema);if(i)if(o){const c=bu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Fu(r,t,a)},Vu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),$u=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=q(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Gi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Gi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Wu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},ju=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Ju=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},qu=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Ia(r)(e,t)};function Fo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Hu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&Fo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:To(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Fo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Ku=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=q(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Lo(n){return!n||n==="1"?null:n}function Vo(n,e){return Lo(n)===Lo(e)}const yr=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Vo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},br=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Vo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function _u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Uu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=q(n,o.schema),p=q(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=mr(et=>gr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&gr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??v,Hd=!!_&&w.depth>=1&&w.depth-_.depth<=1,cl=!!v;if((Hd||cl)&&Ze){if(Ze.node.type===h)return ne&&cl?a().command(({tr:et,dispatch:Sn})=>{const Mn=_u(et);return Mn?(et.setSelection(Mn),Sn&&Sn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(gr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>yr(s,h)).command(()=>br(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Sn=A.filter(Mn=>d.includes(Mn.type.name));return s.ensureMarks(Sn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run()},Gu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Re(n,r.schema);return zu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Yu=(n,e,t={})=>({state:r,commands:i})=>{const s=q(n,r.schema),o=q(e,r.schema),l=pr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Xu=(n,e={})=>({state:t,commands:r})=>{const i=q(n,t.schema);return pr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Zu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},ed=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Re(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=hr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},td=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},nd=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=No(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},rd=new ie("__tiptap_decorations__"),id=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(rd,{type:"force",name:n}),!0),sd=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ma(i,e)(t,r)},od=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ta(i,e)(t,r)};var ld=ml({blur:()=>wf,clearContent:()=>Tf,clearNodes:()=>Of,command:()=>Nf,createParagraphNear:()=>Ef,cut:()=>Df,deleteCurrentNode:()=>Af,deleteNode:()=>If,deleteRange:()=>Rf,deleteSelection:()=>Bf,enter:()=>zf,exitCode:()=>Ff,extendMarkRange:()=>Vf,first:()=>$f,focus:()=>Jf,forEach:()=>qf,insertContent:()=>Hf,insertContentAt:()=>Kf,insertDefaultBlock:()=>_f,joinBackward:()=>Yf,joinDown:()=>Gf,joinForward:()=>Xf,joinItemBackward:()=>Qf,joinItemForward:()=>Zf,joinTextblockBackward:()=>eu,joinTextblockForward:()=>tu,joinUp:()=>Uf,keyboardShortcut:()=>ru,lift:()=>iu,liftEmptyBlock:()=>su,liftListItem:()=>ou,newlineInCode:()=>lu,resetAttributes:()=>au,scrollIntoView:()=>cu,selectAll:()=>fu,selectNodeBackward:()=>uu,selectNodeForward:()=>du,selectParentNode:()=>hu,selectTextblockEnd:()=>pu,selectTextblockStart:()=>mu,setContent:()=>yu,setMark:()=>Lu,setMeta:()=>Vu,setNode:()=>$u,setNodeSelection:()=>Wu,setTextDirection:()=>ju,setTextSelection:()=>Ju,sinkListItem:()=>qu,splitBlock:()=>Hu,splitListItem:()=>Ku,toggleList:()=>Uu,toggleMark:()=>Gu,toggleNode:()=>Yu,toggleWrap:()=>Xu,undoInputRule:()=>Qu,unsetAllMarks:()=>Zu,unsetMark:()=>ed,unsetTextDirection:()=>td,updateAttributes:()=>nd,updateDecorations:()=>id,wrapIn:()=>sd,wrapInList:()=>od});typeof process<"u"&&process.env.NODE_ENV;function ad(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return ad(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function $o(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=$o(n[r],e[r]):t[r]=e[r]}),t}var cd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},kr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>$o(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class dl extends kr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new dl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},fd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class hl extends kr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new hl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Ru(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Iu(r,{from:a.pos,to:c.pos},l)).join(o??` -`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ed}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=du(n.before,[n,...e]);Eu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const id=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:id,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||Co()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!vo(t.doc))return;const f=t.tr,u=uo({state:t,transaction:f}),{commands:d}=new gf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new nd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Ro(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Lo=class ll extends br{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ll(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new rd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Ro(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var sd=Lo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ld}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=ku(n.before,[n,...e]);Bu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const ud=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:ud,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||Oo()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!zo(t.doc))return;const f=t.tr,u=mo({state:t,transaction:f}),{commands:d}=new Cf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new cd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Bo(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Wo=class pl extends kr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new pl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new fd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Bo(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var dd=Wo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""}),od=Lo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Vo=new WeakSet,$o=new WeakSet;function Ue(n){const e=n;return Vo.add(e),e}function kr(n){return Array.isArray(n)&&Vo.has(n)}function Wo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&$o.has(e)&&!kr(e)?Wo(e):[e])}function ld(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!kr(i)&&!$o.has(i)?Ue(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(kr(t))return Ue([n,r,t]);if(t.length===0)return Ue([n,r]);const i=Wo(t);return i.length===0?Ue([n,r]):Ue([n,r,...i])}return t!=null?Ue([n,r,t]):Ue([n,r])}const jo=(n,e)=>ld(n,e),ad=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,fd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,ud=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var dd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return jo("strong",{...un(this.options.HTMLAttributes,n),children:jo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ad,type:this.type}),Bt({find:fd,type:this.type})]},addPasteRules(){return[zt({find:cd,type:this.type}),zt({find:ud,type:this.type})]}});const hd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,pd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,gd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var yd=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},kd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var xd=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Jo(e):z.empty};var Jo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Jo([]);var Sd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Md=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fwd&&(l=Cd(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dMd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Cd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const wd=20;function Td(n,e,t,r){let i=t.getMeta(Ge),s;if(i)return i.historyState;t.getMeta(Ed)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ge))return o.getMeta(Ge).redo?new Re(n.done.addTransform(t,void 0,r,gn(e)),n.undone,Ho(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Od(t,n.prevRanges)),c=o?xr(n.prevRanges,t.mapping):Ho(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),xr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),xr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Od(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ho(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function xr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ge.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Nd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const _o=Ko(!1,!0),Mr=Ko(!0,!0),Ye="data-bd-src",Ad=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Cu([sd.extend({content:"inline*"}),od,dd,yd,xd,Ad]),Id=de.fromSchema(yn),Rd=Le.fromSchema(yn),vd={preserveWhitespace:"full"};function Uo(n){return Id.parse(n,vd)}function Go(n){const e=document.createElement("div");return e.appendChild(Rd.serializeFragment(n.content)),e.innerHTML}function Pd(n){try{return Go(Uo(n))===n.innerHTML}catch{return!1}}function Yo(n){const e=n.getAttribute(Ye);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),Cr=new WeakMap;function Xo(n){let e=Cr.get(n);return e===void 0&&(e=Pd(n),Cr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,ve=null,dt=null,wr="",Xe=!1;function Qo(){return Y?Go(Y.state.doc):null}function kn(){if(!ve||!dt)return;const n=Qo();n===null||n===wr||(wr=n,bn({type:"bd-edit:patch",start:dt.start,end:dt.end,html:n}))}function Ft(){if(!Y)return;kn();const n=ve,e=Qo();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Cr.delete(n),n.removeAttribute("data-bd-edit")),ve=null,dt=null}function Bd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function zd(n,e,t){if(ve===n)return;Ft();const r=Yo(n);if(!r)return;ve=n,dt=r,wr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=it.create({doc:Uo(n),plugins:[Dd(),fo({"Mod-b":_i(yn.marks.bold),"Mod-i":_i(yn.marks.italic),"Mod-z":_o,"Mod-y":Mr,"Shift-Mod-z":Mr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),fo(ya)]});Y=new io({mount:n},{state:i,editable:()=>!Xe,dispatchTransaction(s){Xe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&kn())}}),Y.focus(),e!==void 0&&t!==void 0&&Bd(Y,e,t)}function Zo(n){const e=n?.closest?.(`[${Ye}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Xe)return;const e=Zo(n.target);if(!e){Ft();return}Xo(e)&&zd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=Zo(n.target);e&&Xo(e)},!0),new MutationObserver(()=>{ve&&!ve.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,ve=null,dt=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const el=document.createElement("style");el.textContent=` - [${Ye}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } - [${Ye}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } - [${Ye}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } - [${Ye}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } -`,document.head.appendChild(el);const tl=document.currentScript??document.querySelector("script[data-src-hash]"),Fd=tl?.dataset.srcHash??"",Ld=Number(tl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:Fd,len:Ld,ranges:[...document.querySelectorAll(`[${Ye}]`)].map(n=>Yo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready",""),window.addEventListener("beforeunload",Ft),window.addEventListener("pagehide",n=>{n.persisted?kn():Ft()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:flush"&&typeof e.id=="number"){kn(),e.lock===!0&&(Xe=!0,Y?.setProps({editable:()=>!Xe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Xe=!1,Y?.setProps({editable:()=>!Xe}))}})})(); +`):""}),hd=Wo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const jo=new WeakSet,Jo=new WeakSet;function Ge(n){const e=n;return jo.add(e),e}function xr(n){return Array.isArray(n)&&jo.has(n)}function qo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Jo.has(e)&&!xr(e)?qo(e):[e])}function pd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!xr(i)&&!Jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(xr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=qo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const Ho=(n,e)=>pd(n,e),md=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,gd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,yd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,bd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var kd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Ho("strong",{...un(this.options.HTMLAttributes,n),children:Ho("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:md,type:this.type}),Bt({find:yd,type:this.type})]},addPasteRules(){return[zt({find:gd,type:this.type}),zt({find:bd,type:this.type})]}});const xd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Sd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Cd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var wd=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:xd,type:this.type}),Bt({find:Md,type:this.type})]},addPasteRules(){return[zt({find:Sd,type:this.type}),zt({find:Cd,type:this.type})]}});const Td=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},Od=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Nd=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Td,type:this.type})]},addPasteRules(){return[zt({find:Od,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Ko(e):z.empty};var Ko=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Ko([]);var Ed=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Dd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fId&&(l=Ad(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dDd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Ad(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class ve{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Id=20;function Rd(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(Bd)&&(n=new ve(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new ve(n.done.addTransform(t,void 0,r,gn(e)),n.undone,_o(t.mapping.maps),n.prevTime,n.prevComposition):new ve(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!vd(t,n.prevRanges)),c=o?Sr(n.prevRanges,t.mapping):_o(t.mapping.maps);return new ve(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ve(n.done.rebased(t,s),n.undone.rebased(t,s),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ve(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function vd(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function _o(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Sr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Pd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Yo=Go(!1,!0),Cr=Go(!0,!0);function Fd(n){if(!n.url||n.patchSeq<=n.ackedSeq||!n.hash||n.len<0)return null;const e=[...n.spans].sort((t,r)=>t.start-r.start).map(({start:t,end:r,html:i})=>({start:t,end:r,html:i}));return e.length?JSON.stringify({src_hash:n.hash,src_len:n.len,patches:e}):null}const Xe="data-bd-src",Ld=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Au([dd.extend({content:"inline*"}),hd,kd,wd,Nd,Ld]),Vd=he.fromSchema(yn),$d=Ve.fromSchema(yn),Wd={preserveWhitespace:"full"};function Xo(n){return Vd.parse(n,Wd)}function Qo(n){const e=document.createElement("div");return e.appendChild($d.serializeFragment(n.content)),e.innerHTML}function jd(n){try{return Qo(Xo(n))===n.innerHTML}catch{return!1}}function Zo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),wr=new WeakMap;function el(n){let e=wr.get(n);return e===void 0&&(e=jd(n),wr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Tr="",Qe=!1,Or=0,kn=0,Nr="";const tl=new Map;function nl(){return Y?Qo(Y.state.doc):null}function xn(){if(!Pe||!de)return;const n=nl();if(n===null||n===Tr)return;Tr=n;const e=++Or;tl.set(de.start+","+de.end,{start:de.start,end:de.end,html:n,seq:e}),bn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Ft(){if(!Y)return;xn();const n=Pe,e=nl();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),wr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Jd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function qd(n,e,t){if(Pe===n)return;Ft();const r=Zo(n);if(!r)return;Pe=n,de=r,Tr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Xo(n),plugins:[zd(),po({"Mod-b":Yi(yn.marks.bold),"Mod-i":Yi(yn.marks.italic),"Mod-z":Yo,"Mod-y":Cr,"Shift-Mod-z":Cr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),po(wa)]});Y=new lo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&xn())}}),Y.focus(),e!==void 0&&t!==void 0&&Jd(Y,e,t)}function rl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=rl(n.target);if(!e){Ft();return}el(e)&&qd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=rl(n.target);e&&el(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const il=document.createElement("style");il.textContent=` + [${Xe}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } + [${Xe}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } + [${Xe}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } + [${Xe}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } +`,document.head.appendChild(il);const sl=document.currentScript??document.querySelector("script[data-src-hash]"),ol=sl?.dataset.srcHash??"",ll=Number(sl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:ol,len:ll,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Zo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function al(){const n=Fd({url:Nr,patchSeq:Or,ackedSeq:kn,hash:ol,len:ll,spans:tl.values()});if(n===null)return;kn=Or;const e=new TextEncoder().encode(n).byteLength<=6e4;fetch(Nr,{method:"POST",mode:"no-cors",credentials:"omit",keepalive:e,body:n}).catch(()=>{})}window.addEventListener("beforeunload",()=>{Ft(),al()}),window.addEventListener("pagehide",n=>{n.persisted?xn():Ft(),al()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){e.seq>kn&&(kn=e.seq);return}if(e.type==="bd-edit:beacon"&&typeof e.url=="string"&&e.url.startsWith("/")){try{Nr=new URL(e.url,window.location.href).href}catch{}return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){xn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); From 84f31d6442f3a3342354bf8e39956a0a217b4141 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 00:39:51 +0900 Subject: [PATCH 17/34] fix(desktop,webapp): proxy capability beacon without originGuard and ack only applied patches --- CHANGELOG.md | 2 +- cmd/bdrive/desktop.go | 52 +++++++++++---- cmd/bdrive/desktop_routes_test.go | 63 +++++++++++++++++++ .../frontend/src/components/VisualEdit.tsx | 26 ++++---- ...{Editor-Bx08jARu.js => Editor-yrlJG67f.js} | 2 +- ...dit-BgeFGAnP.js => VisualEdit-CnYT3nlY.js} | 2 +- .../{index-Dib7WV0J.js => index-IQjI59Ja.js} | 4 +- ...ile-gwqfKQrv.js => sharedfile-CQlHsuJ4.js} | 2 +- internal/webapp/static/index.html | 2 +- 9 files changed, 121 insertions(+), 34 deletions(-) rename internal/webapp/static/assets/{Editor-Bx08jARu.js => Editor-yrlJG67f.js} (99%) rename internal/webapp/static/assets/{VisualEdit-BgeFGAnP.js => VisualEdit-CnYT3nlY.js} (68%) rename internal/webapp/static/assets/{index-Dib7WV0J.js => index-IQjI59Ja.js} (99%) rename internal/webapp/static/assets/{sharedfile-gwqfKQrv.js => sharedfile-CQlHsuJ4.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02960b3d..c2dd73ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict. - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. -- **`VisualEdit` saves edits the app never received when the tab closes.** The editing iframe stays sandboxed without `allow-same-origin`, so it has no session of its own. The app acknowledges each numbered patch (`bd-edit:ack`) and hands the iframe a single-file token URL from `POST /api/p//ycollab/frame`. When the iframe unloads with an unacknowledged patch, it posts its edited spans with the source hash, cookie-free (`no-cors`, `keepalive` up to 60,000 bytes), to `POST /api/p//ycollab/frame/`. The hub splices them onto that version and merges the result through `ycollab/sync`; a repeat of an edit the app already saved changes nothing, and a same-word clash parks a conflict copy. `bdrive desktop` proxies both routes. +- **`VisualEdit` sends an exit beacon for unacknowledged iframe edits when the tab closes.** The editing iframe stays sandboxed without `allow-same-origin`, so it has no session of its own. The app acknowledges each numbered patch (`bd-edit:ack`) and hands the iframe a single-file token URL from `POST /api/p//ycollab/frame`. Once that URL has arrived, an iframe that unloads with an unacknowledged patch posts its edited spans with the source hash, cookie-free (`no-cors`, `keepalive` up to 60,000 bytes), to `POST /api/p//ycollab/frame/`. The hub splices them onto that version and merges the result through `ycollab/sync`; a repeat of an edit the app already saved changes nothing, a same-word clash parks a conflict copy, and an unconfirmed sharp shrink is refused (`422`). Delivery is still subject to the browser's teardown limits. `bdrive desktop` proxies both routes. ## v0.18.9 — 2026-11-11 diff --git a/cmd/bdrive/desktop.go b/cmd/bdrive/desktop.go index 408b09f0..6cc0e661 100644 --- a/cmd/bdrive/desktop.go +++ b/cmd/bdrive/desktop.go @@ -77,6 +77,10 @@ const ( routeLocal routeMode = iota // routeProxy forwards to the project's own hub with the device token. routeProxy + // routeProxyCapability forwards to the project's own hub without the + // device token and without originGuard: the URL carries a hub-signed + // capability token, and the sandboxed iframe that posts it has Origin: null. + routeProxyCapability ) // desktopRoutes classifies every per-project route the hub serves, and the @@ -175,7 +179,7 @@ var desktopRoutes = []struct { // A framed HTML page's edit beacon: minted and flushed against the hub's // live document for the same reason /ycollab/sync is. {"POST /api/p/{project}/ycollab/frame", routeProxy, ""}, - {"POST /api/p/{project}/ycollab/frame/{token}", routeProxy, ""}, + {"POST /api/p/{project}/ycollab/frame/{token}", routeProxyCapability, ""}, {"POST /api/p/{project}/reads", routeLocal, "the sync client posts these straight to the hub, never through here; the app's own viewer reads go out through desktop_reads.go instead, as human traffic"}, } @@ -210,14 +214,16 @@ func desktopHandler() http.Handler { // Every per-project hub route is classified in desktopRoutes below, and the // proxies are registered FROM it — see the table for why that matters. for _, rt := range desktopRoutes { - if rt.mode != routeProxy { - continue // falls through to srv, answered from this machine - } - h := http.HandlerFunc(proxyProject) - if !strings.HasPrefix(rt.pattern, "GET ") { - h = originGuard(h) // every proxied write, exactly as before + switch rt.mode { + case routeProxy: + h := http.HandlerFunc(proxyProject) + if !strings.HasPrefix(rt.pattern, "GET ") { + h = originGuard(h) // every proxied write, exactly as before + } + mux.HandleFunc(rt.pattern, h) + case routeProxyCapability: + mux.HandleFunc(rt.pattern, proxyCapabilityProject) } - mux.HandleFunc(rt.pattern, h) } // Project creation and its template seeding are hub writes (2026-08-20 // owner decision): create goes to the signed-in hub, uploads go to the @@ -809,6 +815,19 @@ func proxyProject(w http.ResponseWriter, r *http.Request) { proxyDefaultHub(w, r) } +func proxyCapabilityProject(w http.ResponseWriter, r *http.Request) { + if m, ok := desktopMounts()[r.PathValue("project")]; ok { + proxyHubWithAuth(w, r, m.server, false) + return + } + settings, _ := config.LoadSettings() + if settings.Server == "" { + http.Error(w, "not signed in to a hub", http.StatusBadGateway) + return + } + proxyHubWithAuth(w, r, settings.Server, false) +} + // proxyDefaultHub forwards a token-scoped request (share revoke/expiry — // nothing in the path names a project) to the signed-in hub. // ponytail: a mount syncing through a DIFFERENT hub than the signed-in one @@ -846,10 +865,17 @@ func proxyDefaultHub(w http.ResponseWriter, r *http.Request) { } func proxyHub(w http.ResponseWriter, r *http.Request, server string) { - settings, _ := config.LoadSettings() - token := os.Getenv("BDRIVE_TOKEN") - if token == "" { - token = settings.Token + proxyHubWithAuth(w, r, server, true) +} + +func proxyHubWithAuth(w http.ResponseWriter, r *http.Request, server string, attachToken bool) { + var token string + if attachToken { + settings, _ := config.LoadSettings() + token = os.Getenv("BDRIVE_TOKEN") + if token == "" { + token = settings.Token + } } u := server + r.URL.Path if r.URL.RawQuery != "" { @@ -866,7 +892,7 @@ func proxyHub(w http.ResponseWriter, r *http.Request, server string) { if ct := r.Header.Get("Content-Type"); ct != "" { req.Header.Set("Content-Type", ct) } - if token != "" && tokenGoesTo(server) { + if attachToken && token != "" && tokenGoesTo(server) { req.Header.Set("Authorization", "Bearer "+token) } // A long-lived stream cannot use initClient: its 10s whole-request timeout diff --git a/cmd/bdrive/desktop_routes_test.go b/cmd/bdrive/desktop_routes_test.go index 728329dc..517b917a 100644 --- a/cmd/bdrive/desktop_routes_test.go +++ b/cmd/bdrive/desktop_routes_test.go @@ -1,10 +1,14 @@ package main import ( + "io" + "net/http" + "net/http/httptest" "sort" "strings" "testing" + "github.com/runbear-io/beardrive/internal/config" "github.com/runbear-io/beardrive/internal/webapp" ) @@ -64,3 +68,62 @@ func TestDesktopRoutesClassified(t *testing.T) { t.Errorf("desktopRoutes lists %q, which the hub no longer serves — renamed or removed?", pat) } } + +func TestDesktopCapabilityBeaconAcceptsOpaqueOriginWithoutAmbientToken(t *testing.T) { + t.Setenv("BDRIVE_HOME", t.TempDir()) + t.Setenv("BDRIVE_TOKEN", "") + + var gotAuth, gotPath, gotBody string + hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + gotPath = r.URL.Path + b, _ := io.ReadAll(r.Body) + gotBody = string(b) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"ok":true}`)) + })) + defer hub.Close() + + if err := config.SaveSettings(config.Settings{ + Server: hub.URL, + Token: "ambient-device-secret", + Email: "alice@example.com", + }); err != nil { + t.Fatal(err) + } + + desk := httptest.NewServer(desktopHandler()) + defer desk.Close() + + // Minting an edit token still requires same-origin: Origin: null is refused. + mintReq, _ := http.NewRequest("POST", desk.URL+"/api/p/p-1/ycollab/frame", strings.NewReader(`{"path":"a.html"}`)) + mintReq.Header.Set("Origin", "null") + mintResp, err := http.DefaultClient.Do(mintReq) + if err != nil { + t.Fatal(err) + } + mintResp.Body.Close() + if mintResp.StatusCode != http.StatusForbidden { + t.Fatalf("mint with Origin: null = %d, want 403", mintResp.StatusCode) + } + + // Flushing with the capability token in the URL accepts Origin: null from + // the sandboxed iframe and never attaches the saved device token. + flushReq, _ := http.NewRequest("POST", desk.URL+"/api/p/p-1/ycollab/frame/tok.sig", strings.NewReader(`{"patches":[]}`)) + flushReq.Header.Set("Origin", "null") + flushReq.Header.Set("Content-Type", "text/plain;charset=UTF-8") + flushResp, err := http.DefaultClient.Do(flushReq) + if err != nil { + t.Fatal(err) + } + flushResp.Body.Close() + if flushResp.StatusCode != http.StatusOK { + t.Fatalf("flush with Origin: null = %d, want 200", flushResp.StatusCode) + } + if gotPath != "/api/p/p-1/ycollab/frame/tok.sig" || gotBody != `{"patches":[]}` { + t.Fatalf("proxied path=%q body=%q", gotPath, gotBody) + } + if gotAuth != "" { + t.Fatalf("capability beacon attached ambient Authorization=%q, want empty", gotAuth) + } +} diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index 034c1bab..e09724bc 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -470,19 +470,17 @@ export function VisualEdit({ if (msg.type !== "bd-edit:patch") return; if (!anchored) return anchorRanges().then(() => { - applyPatch(msg); - ackPatch(msg); + if (applyPatch(msg)) ackPatch(msg); }); - applyPatch(msg); - ackPatch(msg); + if (applyPatch(msg)) ackPatch(msg); }; - const applyPatch = (msg: Patch) => { + const applyPatch = (msg: Patch): boolean => { const a = anchors.get(key(msg)); - if (!a) return; // a range from a render this side has already replaced + if (!a) return false; // a range from a render this side has already replaced if (stageDoc) { const sFrom = Y.createAbsolutePositionFromRelativePosition(a.from, stageDoc); const sTo = Y.createAbsolutePositionFromRelativePosition(a.to, stageDoc); - if (!sFrom || !sTo || sFrom.index > sTo.index) return; + if (!sFrom || !sTo || sFrom.index > sTo.index) return false; const sText = stageDoc.getText("body"); const sSpan = sTo.index - sFrom.index; const sWhole = sFrom.index === 0 && sTo.index === sText.length; @@ -490,12 +488,12 @@ export function VisualEdit({ anchors.clear(); anchored = false; setGen((g) => g + 1); - return; + return false; } const sLive = sText.toString().slice(sFrom.index, sTo.index); const sWant = merge3PreferRight(a.orig, sLive, msg.html); a.orig = msg.html; - if (sLive === sWant) return; + if (sLive === sWant) return true; stageDoc.transact(() => { for (const s of diffSplices(sLive, sWant)) { if (s.deleteCount > 0) sText.delete(sFrom.index + s.index, s.deleteCount); @@ -505,13 +503,12 @@ export function VisualEdit({ cb.current.onStateChange?.("dirty"); clearTimeout(stageTimer); stageTimer = setTimeout(() => void file.saveNow(), STAGE_IDLE_MS); - return; + return true; } const doc = file.collab.doc; const from = Y.createAbsolutePositionFromRelativePosition(a.from, doc); const to = Y.createAbsolutePositionFromRelativePosition(a.to, doc); - if (!from || !to || from.index > to.index) return; - + if (!from || !to || from.index > to.index) return false; const text = file.collab.text; /* Last line of defence: a patch may not swallow the document. @@ -539,7 +536,7 @@ export function VisualEdit({ anchors.clear(); anchored = false; setGen((g) => g + 1); - return; + return false; } const live = text.toString().slice(from.index, to.index); @@ -552,13 +549,14 @@ export function VisualEdit({ other words of the same element survives the collision. */ const want = merge3PreferRight(a.orig, live, msg.html); a.orig = msg.html; - if (live === want) return; + if (live === want) return true; // Splices run last-first in `live` coordinates, so shifting by the // span's start keeps every one valid. One transaction, so peers see one // change rather than a moment of missing content. file.collab.applySplices( diffSplices(live, want).map((s) => ({ ...s, index: s.index + from.index })), ); + return true; }; const onMessage = (e: MessageEvent) => { // The iframe is sandboxed WITHOUT allow-same-origin, so its origin is diff --git a/internal/webapp/static/assets/Editor-Bx08jARu.js b/internal/webapp/static/assets/Editor-yrlJG67f.js similarity index 99% rename from internal/webapp/static/assets/Editor-Bx08jARu.js rename to internal/webapp/static/assets/Editor-yrlJG67f.js index c370210c..dad69fcf 100644 --- a/internal/webapp/static/assets/Editor-Bx08jARu.js +++ b/internal/webapp/static/assets/Editor-yrlJG67f.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,c as Vh,d as CO,r as oe,e as ZO,f as XO,g as AO,h as RO,j as wn,t as wl,w as MO,a as jO}from"./index-Dib7WV0J.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-gwqfKQrv.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,c as Vh,d as CO,r as oe,e as ZO,f as XO,g as AO,h as RO,j as wn,t as wl,w as MO,a as jO}from"./index-IQjI59Ja.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CQlHsuJ4.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-BgeFGAnP.js b/internal/webapp/static/assets/VisualEdit-CnYT3nlY.js similarity index 68% rename from internal/webapp/static/assets/VisualEdit-BgeFGAnP.js rename to internal/webapp/static/assets/VisualEdit-CnYT3nlY.js index 96e09992..3c9dad1d 100644 --- a/internal/webapp/static/assets/VisualEdit-BgeFGAnP.js +++ b/internal/webapp/static/assets/VisualEdit-CnYT3nlY.js @@ -1 +1 @@ -import{r as u,j as E,p as Pe,w as Me,a as We}from"./index-Dib7WV0J.js";import{o as je,D as Ce,c as L,a as J,m as me,d as be}from"./sharedfile-gwqfKQrv.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Fe=50,Ne=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function qe(){let o=null;const l=new Map;let f=0,x=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),M=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){M(o.then(c));return}try{const p=c();Ne(p)&&M(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,D=!1){if(await P(),x||p())return;const h=++f;let W;const I=new Promise(j=>{l.set(h,j),W=setInterval(()=>{!x&&!p()||(l.delete(h),j())},Fe)});try{c(D?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await I}finally{clearInterval(W)}await P()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function Ae(o,l,f){let x=!1;try{return await o(),x=await l(),x}finally{x||f()}}async function De(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ue({apiBase:o,fileURL:l,path:f,initial:x,me:P,onStateChange:M,onCollab:c,onPeers:p,onConflictCopy:D,baseSha:h,onSaved:W,onWriting:I,onRendered:j,handle:_}){const b=u.useRef(null),[K,ge]=u.useState(null),[we,Q]=u.useState(!1),[Te,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D});y.current={onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D};const G=u.useRef(x),U=u.useRef(P);U.current=P;const ee=u.useRef(h);ee.current=h;const te=u.useRef(null);return u.useEffect(()=>{te.current?.rebase(h)},[h]),u.useEffect(()=>{let R=null,C=!1,s=null,g;const ve=700;Q(!1),X(!1);const Se=setTimeout(()=>{!T&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),Re=setTimeout(()=>X(!0),24e3),H=qe();let O=!1,V="",ne,re=!1;const oe=()=>{V&&O&&b.current?.contentWindow?.postMessage({type:"bd-edit:beacon",url:V},"*")},se=()=>{Pe(o+"ycollab/frame?path="+encodeURIComponent(f),{}).then(e=>{if(re||typeof e?.url!="string"||(V=e.url,oe(),typeof e.expires!="number"))return;const t=e.expires>1e12?e.expires-Date.now():e.expires;ne=setTimeout(se,Math.max(3e4,t-6e4))}).catch(()=>{})};se();const ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},ke=async e=>{const t=b.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!O||r||b.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},F=new Map,ae=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};F.set(e,(F.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(F.get(e)??1)-1;if(r>0){F.set(e,r);return}F.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ke(!0)}catch(r){throw i(),r}return i},a=te.current=je({apiBase:o,path:f,seed:G.current,baseSha:ee.current,who:U.current?.name,me:U.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>We(f,e),onShrinkWithdrawn:Me,beforeJoin:async()=>s?ae():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(T&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:J(a.collab.text,m.index),to:J(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),T=!1,t!==i&&S(r=>r+1);e.destroy()}C=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),C=!0,k()},onStalled:()=>{C||s||(s=new Ce,s.getText("body").insert(0,G.current),C=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ce=null;const le={...a,saveNow:()=>{let e=()=>{};return ce??=Ae(async()=>{e=await ae()},()=>a.saveNow(),()=>e()).finally(()=>{ce=null})}};_&&(_.current=le);const w=new Map,ue=e=>e.start+","+e.end,k=async()=>{if(T||!R||!C)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await De(t);if(i!==null?i!==de:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(ue(n),{from:J(e,n.start),to:J(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Q(!0),y.current.onRendered?.()};let de="",Y=-1,T=!1;const Ee=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){ge("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,de=e.hash,Y=e.len,O=!0,oe(),k();if(e.type==="bd-edit:patch"){if(!T)return k().then(()=>{fe(e),ie(e)});fe(e),ie(e)}},fe=e=>{const t=w.get(ue(e));if(!t)return;if(s){const d=L(t.from,s),q=L(t.to,s);if(!d||!q||d.index>q.index)return;const A=s.getText("body"),Le=q.index-d.index;if(d.index===0&&q.index===A.length&&t.spant.span*4+256){w.clear(),T=!1,S(v=>v+1);return}const B=A.toString().slice(d.index,q.index),ye=me(t.orig,B,e.html);if(t.orig=e.html,B===ye)return;s.transact(()=>{for(const v of be(B,ye))v.deleteCount>0&&A.delete(d.index+v.index,v.deleteCount),v.insertText&&A.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ve);return}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256){console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),T=!1,S(d=>d+1);return}const z=m.toString().slice(r.index,n.index),he=me(t.orig,z,e.html);t.orig=e.html,z!==he&&a.collab.applySplices(be(z,he).map(d=>({...d,index:d.index+r.index})))},pe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>Ee(t))},xe=()=>{k()};return a.collab.text.observe(xe),window.addEventListener("message",pe),()=>{_?.current===le&&(_.current=null),O=!1,H.close(),re=!0,clearTimeout(ne),clearTimeout(Se),clearTimeout(Re),clearTimeout(g),a.collab.text.unobserve(xe),setTimeout(()=>{window.removeEventListener("message",pe),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,f,$]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),Te&&!we&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ue as VisualEdit}; +import{r as u,j as E,p as Pe,w as Me,a as We}from"./index-IQjI59Ja.js";import{o as je,D as Ce,c as L,a as J,m as me,d as be}from"./sharedfile-CQlHsuJ4.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Fe=50,Ne=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function qe(){let o=null;const l=new Map;let f=0,x=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),M=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){M(o.then(c));return}try{const p=c();Ne(p)&&M(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,D=!1){if(await P(),x||p())return;const h=++f;let W;const I=new Promise(j=>{l.set(h,j),W=setInterval(()=>{!x&&!p()||(l.delete(h),j())},Fe)});try{c(D?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await I}finally{clearInterval(W)}await P()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function Ae(o,l,f){let x=!1;try{return await o(),x=await l(),x}finally{x||f()}}async function De(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ue({apiBase:o,fileURL:l,path:f,initial:x,me:P,onStateChange:M,onCollab:c,onPeers:p,onConflictCopy:D,baseSha:h,onSaved:W,onWriting:I,onRendered:j,handle:_}){const b=u.useRef(null),[K,ge]=u.useState(null),[we,Q]=u.useState(!1),[Te,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D});y.current={onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D};const G=u.useRef(x),U=u.useRef(P);U.current=P;const ee=u.useRef(h);ee.current=h;const te=u.useRef(null);return u.useEffect(()=>{te.current?.rebase(h)},[h]),u.useEffect(()=>{let R=null,C=!1,s=null,g;const ve=700;Q(!1),X(!1);const Se=setTimeout(()=>{!T&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),Re=setTimeout(()=>X(!0),24e3),H=qe();let O=!1,V="",ne,re=!1;const oe=()=>{V&&O&&b.current?.contentWindow?.postMessage({type:"bd-edit:beacon",url:V},"*")},se=()=>{Pe(o+"ycollab/frame?path="+encodeURIComponent(f),{}).then(e=>{if(re||typeof e?.url!="string"||(V=e.url,oe(),typeof e.expires!="number"))return;const t=e.expires>1e12?e.expires-Date.now():e.expires;ne=setTimeout(se,Math.max(3e4,t-6e4))}).catch(()=>{})};se();const ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},ke=async e=>{const t=b.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!O||r||b.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},F=new Map,ae=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};F.set(e,(F.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(F.get(e)??1)-1;if(r>0){F.set(e,r);return}F.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ke(!0)}catch(r){throw i(),r}return i},a=te.current=je({apiBase:o,path:f,seed:G.current,baseSha:ee.current,who:U.current?.name,me:U.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>We(f,e),onShrinkWithdrawn:Me,beforeJoin:async()=>s?ae():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(T&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:J(a.collab.text,m.index),to:J(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),T=!1,t!==i&&S(r=>r+1);e.destroy()}C=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),C=!0,k()},onStalled:()=>{C||s||(s=new Ce,s.getText("body").insert(0,G.current),C=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ce=null;const le={...a,saveNow:()=>{let e=()=>{};return ce??=Ae(async()=>{e=await ae()},()=>a.saveNow(),()=>e()).finally(()=>{ce=null})}};_&&(_.current=le);const w=new Map,ue=e=>e.start+","+e.end,k=async()=>{if(T||!R||!C)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await De(t);if(i!==null?i!==de:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(ue(n),{from:J(e,n.start),to:J(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Q(!0),y.current.onRendered?.()};let de="",Y=-1,T=!1;const Ee=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){ge("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,de=e.hash,Y=e.len,O=!0,oe(),k();if(e.type==="bd-edit:patch"){if(!T)return k().then(()=>{fe(e)&&ie(e)});fe(e)&&ie(e)}},fe=e=>{const t=w.get(ue(e));if(!t)return!1;if(s){const d=L(t.from,s),q=L(t.to,s);if(!d||!q||d.index>q.index)return!1;const A=s.getText("body"),Le=q.index-d.index;if(d.index===0&&q.index===A.length&&t.spant.span*4+256)return w.clear(),T=!1,S(v=>v+1),!1;const B=A.toString().slice(d.index,q.index),ye=me(t.orig,B,e.html);return t.orig=e.html,B===ye||(s.transact(()=>{for(const v of be(B,ye))v.deleteCount>0&&A.delete(d.index+v.index,v.deleteCount),v.insertText&&A.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ve)),!0}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return!1;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),T=!1,S(d=>d+1),!1;const z=m.toString().slice(r.index,n.index),he=me(t.orig,z,e.html);return t.orig=e.html,z===he||a.collab.applySplices(be(z,he).map(d=>({...d,index:d.index+r.index}))),!0},pe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>Ee(t))},xe=()=>{k()};return a.collab.text.observe(xe),window.addEventListener("message",pe),()=>{_?.current===le&&(_.current=null),O=!1,H.close(),re=!0,clearTimeout(ne),clearTimeout(Se),clearTimeout(Re),clearTimeout(g),a.collab.text.unobserve(xe),setTimeout(()=>{window.removeEventListener("message",pe),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,f,$]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),Te&&!we&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ue as VisualEdit}; diff --git a/internal/webapp/static/assets/index-Dib7WV0J.js b/internal/webapp/static/assets/index-IQjI59Ja.js similarity index 99% rename from internal/webapp/static/assets/index-Dib7WV0J.js rename to internal/webapp/static/assets/index-IQjI59Ja.js index 1d05b3b0..852d4a1d 100644 --- a/internal/webapp/static/assets/index-Dib7WV0J.js +++ b/internal/webapp/static/assets/index-IQjI59Ja.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Bx08jARu.js","assets/sharedfile-gwqfKQrv.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-BgeFGAnP.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-yrlJG67f.js","assets/sharedfile-CQlHsuJ4.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CnYT3nlY.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Bx08jARu.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-BgeFGAnP.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-yrlJG67f.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CnYT3nlY.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,SV as c,qB as d,GB as e,kf as f,Mo as g,BB as h,BM as i,o as j,PB as k,YB as l,KB as m,xV as n,ZB as o,Sn as p,b as r,uy as s,Ne as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-gwqfKQrv.js b/internal/webapp/static/assets/sharedfile-CQlHsuJ4.js similarity index 99% rename from internal/webapp/static/assets/sharedfile-gwqfKQrv.js rename to internal/webapp/static/assets/sharedfile-CQlHsuJ4.js index 3e1e9ed4..1cceabac 100644 --- a/internal/webapp/static/assets/sharedfile-gwqfKQrv.js +++ b/internal/webapp/static/assets/sharedfile-CQlHsuJ4.js @@ -1,4 +1,4 @@ -import{H as et,i as En,k as Jt,l as Qo,m as xr,n as de,f as Lr,g as Or}from"./index-Dib7WV0J.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +import{H as et,i as En,k as Jt,l as Qo,m as xr,n as de,f as Lr,g as Or}from"./index-IQjI59Ja.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=` `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})() BearDrive - + From e2bcc8b3d204b23e95112ceadb4823a5dbe23834 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 00:44:19 +0900 Subject: [PATCH 18/34] fix(webapp): track per-span exact-seq acknowledgements for VisualEdit exit beacon --- internal/webapp/frontend/src/inline-edit.ts | 17 +++++--- .../webapp/frontend/src/lib/editbeacon.ts | 35 +++++++++++----- .../src/lib/sharedfile_restore.test.ts | 40 ++++++++++++++----- internal/webapp/static/inline-edit.js | 26 ++++++------ 4 files changed, 78 insertions(+), 40 deletions(-) diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts index 381bc8b5..2158a2ce 100644 --- a/internal/webapp/frontend/src/inline-edit.ts +++ b/internal/webapp/frontend/src/inline-edit.ts @@ -40,7 +40,7 @@ import { EditorView } from "@tiptap/pm/view"; import { keymap } from "@tiptap/pm/keymap"; import { baseKeymap, toggleMark } from "@tiptap/pm/commands"; import { history, undo, redo } from "@tiptap/pm/history"; -import { beaconBody, type EditedSpan } from "./lib/editbeacon"; +import { ackEditedSpan, beaconBody, type EditedSpan } from "./lib/editbeacon"; const SRC_ATTR = "data-bd-src"; @@ -195,7 +195,6 @@ let locked = false; patch unacknowledged posts every span edited on this render to the URL the app gave it. */ let patchSeq = 0; -let ackedSeq = 0; let beaconURL = ""; const editedSpans = new Map(); @@ -210,7 +209,13 @@ function flush() { if (html === null || html === before) return; before = html; const seq = ++patchSeq; - editedSpans.set(range.start + "," + range.end, { start: range.start, end: range.end, html, seq }); + editedSpans.set(range.start + "," + range.end, { + start: range.start, + end: range.end, + html, + seq, + acked: false, + }); send({ type: "bd-edit:patch", seq, start: range.start, end: range.end, html }); } @@ -414,9 +419,9 @@ document.documentElement.setAttribute("data-bd-ready", ""); keepalive body is capped by the browser; past that it goes as an ordinary request that may still finish. */ function beaconUnacked() { - const body = beaconBody({ url: beaconURL, patchSeq, ackedSeq, hash, len, spans: editedSpans.values() }); + const body = beaconBody({ url: beaconURL, hash, len, spans: editedSpans.values() }); if (body === null) return; - ackedSeq = patchSeq; + for (const s of editedSpans.values()) s.acked = true; const keepalive = new TextEncoder().encode(body).byteLength <= 60_000; void fetch(beaconURL, { method: "POST", mode: "no-cors", credentials: "omit", keepalive, body }).catch(() => {}); } @@ -442,7 +447,7 @@ window.addEventListener("message", (e) => { const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown; url?: unknown } | null; if (!msg) return; if (msg.type === "bd-edit:ack" && typeof msg.seq === "number") { - if (msg.seq > ackedSeq) ackedSeq = msg.seq; + ackEditedSpan(editedSpans.values(), msg.seq); return; } if (msg.type === "bd-edit:beacon" && typeof msg.url === "string" && msg.url.startsWith("/")) { diff --git a/internal/webapp/frontend/src/lib/editbeacon.ts b/internal/webapp/frontend/src/lib/editbeacon.ts index 9f8245d8..7d29982e 100644 --- a/internal/webapp/frontend/src/lib/editbeacon.ts +++ b/internal/webapp/frontend/src/lib/editbeacon.ts @@ -12,25 +12,40 @@ Pure, so it is tested without a DOM; inline-edit.ts owns the state. */ -export type EditedSpan = { start: number; end: number; html: string; seq: number }; +export type EditedSpan = { + start: number; + end: number; + html: string; + seq: number; + acked?: boolean; +}; + +/* Marks the span whose latest edit is `seq` acknowledged. A later edit to a + different span (higher `seq`) never acknowledges an earlier rejected span, + and an older ack arriving after a newer edit to the same span leaves the + newer edit unacknowledged until its own `seq` is confirmed. */ +export function ackEditedSpan(spans: Iterable, seq: number): void { + for (const s of spans) { + if (s.seq === seq) s.acked = true; + } +} /* The beacon's body, or null when nothing is owed: no capability yet, every - patch acknowledged, no rendered version to splice onto, or nothing edited. - Every span edited on this render goes, not just the unacknowledged ones: - the hub rebuilds the document from `src_hash`, so the patches must spell - all of it. */ + edited span acknowledged, no rendered version to splice onto, or nothing + edited. Every span edited on this render goes once any span is unacked: + the hub rebuilds the document from `src_hash`, so the patches spell the + full render state. */ export function beaconBody(o: { url: string; - patchSeq: number; - ackedSeq: number; hash: string; len: number; spans: Iterable; }): string | null { - if (!o.url || o.patchSeq <= o.ackedSeq || !o.hash || o.len < 0) return null; - const patches = [...o.spans] + if (!o.url || !o.hash || o.len < 0) return null; + const all = [...o.spans]; + if (!all.some((s) => !s.acked)) return null; + const patches = all .sort((a, b) => a.start - b.start) .map(({ start, end, html }) => ({ start, end, html })); - if (!patches.length) return null; return JSON.stringify({ src_hash: o.hash, src_len: o.len, patches }); } diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index 347fc1e0..c028b351 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -13,6 +13,7 @@ import { createRequire, registerHooks } from "node:module"; import { existsSync, readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import type { SharedFile, ShrinkAsk } from "./sharedfile.ts"; +import type { EditedSpan } from "./editbeacon.ts"; /* The modules under test are app code: extensionless imports, and TypeScript node cannot strip on its own (collab.ts's parameter properties). So every @@ -55,7 +56,7 @@ const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); const { parseConflict } = await import("./conflict.ts"); const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts"); const { frameChannel, saveLocked } = await import("./frameflush.ts"); -const { beaconBody } = await import("./editbeacon.ts"); +const { ackEditedSpan, beaconBody } = await import("./editbeacon.ts"); /* toEqual's semantics: a property that is undefined is a property that is absent. Only plain objects and arrays are rebuilt; anything else (a @@ -2850,13 +2851,17 @@ test("frameChannel keeps arrival order behind an async handler, then handles at and then carries every span edited on the render, in source order, over the rendered version's hash — enough for the hub to rebuild the whole document. Acknowledged, or nothing to splice onto: nothing is sent. */ -test("beaconBody: sent only while a patch is unacknowledged, carrying every edited span", () => { - const spans = [ - { start: 40, end: 52, html: "Second", seq: 2 }, - { start: 10, end: 20, html: "First", seq: 1 }, +test("beaconBody: per-span ack keeps an unapplied earlier span owed even after a later span is acked", () => { + const spans: EditedSpan[] = [ + { start: 40, end: 52, html: "Second", seq: 2, acked: false }, + { start: 10, end: 20, html: "First", seq: 1, acked: false }, ]; const base = { url: "https://hub/api/p/x/ycollab/frame/tok", hash: "h", len: 100, spans }; - same(JSON.parse(beaconBody({ ...base, patchSeq: 2, ackedSeq: 1 }) ?? "null"), { + + // Patch 1 was not applied (no ack 1), while patch 2 on another span succeeded (ack 2): + // patch 1 is still unacknowledged, so unload still sends the beacon! + ackEditedSpan(spans, 2); + same(JSON.parse(beaconBody(base) ?? "null"), { src_hash: "h", src_len: 100, patches: [ @@ -2864,9 +2869,22 @@ test("beaconBody: sent only while a patch is unacknowledged, carrying every edit { start: 40, end: 52, html: "Second" }, ], }); - assert.equal(beaconBody({ ...base, patchSeq: 2, ackedSeq: 2 }), null); // all acknowledged - assert.equal(beaconBody({ ...base, url: "", patchSeq: 2, ackedSeq: 1 }), null); // no capability - assert.equal(beaconBody({ ...base, hash: "", patchSeq: 2, ackedSeq: 1 }), null); // no version - assert.equal(beaconBody({ ...base, len: -1, patchSeq: 2, ackedSeq: 1 }), null); - assert.equal(beaconBody({ ...base, spans: [], patchSeq: 2, ackedSeq: 1 }), null); // nothing edited + + // Once patch 1 is also acknowledged, nothing is owed. + ackEditedSpan(spans, 1); + assert.equal(beaconBody(base), null); + + // Re-editing span 1 (seq 3) resets acked=false; a stale ack(1) does not clear seq 3. + spans[1] = { start: 10, end: 20, html: "First again", seq: 3, acked: false }; + ackEditedSpan(spans, 1); + assert.notEqual(beaconBody(base), null); + ackEditedSpan(spans, 3); + assert.equal(beaconBody(base), null); + + // Missing capability, hash, length, or spans -> null even when unacked. + spans[1].acked = false; + assert.equal(beaconBody({ ...base, url: "" }), null); + assert.equal(beaconBody({ ...base, hash: "" }), null); + assert.equal(beaconBody({ ...base, len: -1 }), null); + assert.equal(beaconBody({ ...base, spans: [] }), null); }); diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js index ccbf93c5..b604eef3 100644 --- a/internal/webapp/static/inline-edit.js +++ b/internal/webapp/static/inline-edit.js @@ -1,21 +1,21 @@ -(function(){"use strict";var Ar=Object.defineProperty,ml=(n,e)=>{let t={};for(var r in n)Ar(t,r,{get:n[r],enumerable:!0});return Ar(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ir(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Pr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=zr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Br(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Br(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Br(s.content,e-i-1,t-i-1)))}function zr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=zr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function gl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return Fr(n,e,t,0)}function Fr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&wn(n,e,i+1),o=r.depth>i&&wn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Lr(s,o),Be(ze(s,Vr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=wn(n,e,t+1);Be(ze(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function yl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=$r.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Wr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Wr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Wr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new Sl(e,t);if(r.next==null)return Le.empty;let i=jr(r);r.next&&r.err("Unexpected trailing text");let s=El(Nl(i));return Dl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}Le.empty=new Le(!0);class Sl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function jr(n){let e=[];do e.push(Ml(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Ml(n){let e=[];do e.push(Cl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Cl(n){let e=Ol(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=wl(n,e);else break;return e}function Jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function wl(n,e){let t=Jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Tl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Ol(n){if(n.eat("(")){let e=jr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Tl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Nl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:_r(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new fl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Al(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Il{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Al(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Gr(e,i.attrs),this.excluded=null;let s=Kr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,_r(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Xr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Yr.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Qr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Qr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Yr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Qr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Rl(n){return n.tag!=null}function vl(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Rl(i))this.tags.push(i);else if(vl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ni(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ni(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ri(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ri(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Zr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Pl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},ei={ol:!0,ul:!0},gt=1,Tn=2,yt=4;function ti(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Tn:0):n&&n.whitespace=="pre"?gt|Tn:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Zr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ni{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ti(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Tn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ii(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Bl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&ei.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function zl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ri(n){let e={};for(let t in n)e[t]=n[t];return e}function ii(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=si(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return si(e.marks)}}function si(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const oi=new WeakMap;function Fl(n){let e=oi.get(n);return e===void 0&&oi.set(n,e=Ll(n)),e}function Ll(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const li=65535,ai=Math.pow(2,16);function Vl(n,e){return n+e*ai}function ci(n){return n&li}function $l(n){return(n-(n&li))/ai}const fi=1,ui=2,_t=4,di=8;class On{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&di)>0}get deletedBefore(){return(this.delInfo&(fi|_t))>0}get deletedAfter(){return(this.delInfo&(ui|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ci(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Vl(l/3,e-a),m=e==a?ui:e==u?fi:_t;return(t<0?e!=a:e!=u)&&(m|=di),new On(h,m,p)}i+=f-c}return r?e+i:new On(e+i,0,null)}touches(e,t){let r=0,i=ci(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(En(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Dn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Wl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function jl(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function An(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Jl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Ul(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Gl(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&gi(n,o,l,s),An(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&mi(n,o,l,s),!1}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function gi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function Gl(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Yl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Xl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return yi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Ql(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&yi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Zl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);gi(n,f.node(),f.before(),l)}o.inlineContent&&An(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);mi(n,f.node(),f.before(),n.steps.length)}return n}function ea(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return bi(i,s,r)?new R(e,t,r):new na(i,s,r).fit()}function bi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class na{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=ki(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return Si(e,-1)<=t?!1:(this.unplaced.size>1&&Si(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=ki(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(xi(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=In(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function ki(n,e){for(let t=0;t1&&(r=r.replaceChild(0,xi(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function In(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!ra(t,s.content,o)?l:null}function ra(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=ia(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Mi(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function oa(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=ea(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function la(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Ci(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Ci(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class wi{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return sa(this,e,t,r),this}replaceRangeWith(e,t,r){return oa(this,e,t,r),this}deleteRange(e,t){return la(this,e,t),this}lift(e,t){return ql(this,e,t),this}join(e,t=1){return Zl(this,e,t),this}wrap(e,t){return _l(this,e,t),this}setBlockType(e,t=e,r,i=null){return Ul(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Yl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Xl(this,e,t,r),this}addMark(e,t,r){return Wl(this,e,t,r),this}removeMark(e,t,r){return jl(this,e,t,r),this}clearIncompatible(e,t,r){return An(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new aa(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class aa{constructor(e,t){this.$from=e,this.$to=t}}let Ti=!1;function Oi(n){!Ti&&!n.parent.inlineContent&&(Ti=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Oi(e),Oi(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ni(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ei=1,Xt=2,Di=4;class fa extends wi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Di,this}get scrolledIntoView(){return(this.updated&Di)>0}}function Ai(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Ai(t.init,r),this.apply=Ai(t.apply,r)}}const ua=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Pn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ua.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Pn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ii(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ii(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ii(e.props,this,this.props),this.key=e.key?e.key.key:Ri("plugin")}getState(e){return e[this.key]}}const Bn=Object.create(null);function Ri(n){return n in Bn?n+"$"+ ++Bn[n]:(Bn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ri(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const vi=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Pi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Bi=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=zn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Hi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},da=(n,e,t)=>{let r=Pi(n,t);if(!r)return!1;let i=zn(r);return i?zi(n,i,e):!1},ha=(n,e,t)=>{let r=Li(n,t);if(!r)return!1;let i=Fn(r);return i?zi(n,i,e):!1};function zi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const Fi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=zn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function zn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Li(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Li(n,t);if(!r)return!1;let i=Fn(r);if(!i)return!1;let s=i.nodeAfter;if(Hi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ma=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ga=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Wi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function Ln(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Ln(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Ln(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ya(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Ln(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ba=ya(),ka=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},xa=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function Sa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Hi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&Sa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Ki(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const _i=Ki(-1),Ui=Ki(1);function Ma(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&hi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Gi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Yi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!Ca(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Da(e,t,n,s):Aa(e,t,s):!0:!1}}function Da(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ia(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Wn=null;const ge=function(n,e,t){let r=Wn||(Wn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ra=function(){Wn=null},je=function(n,e,t,r){return t&&(Zi(n,e,t,r,-1)||Zi(n,e,t,r,1))},va=/^(img|br|input|textarea|hr)$/i;function Zi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||va.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Pa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ba(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),rs=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!es&&"webkitFontSmoothing"in es.documentElement.style,Va=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function $a(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Wa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function is(n,e,t){if(!Kn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?$a(s):Wa(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function ja(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:ss(n.dom)}}function ss(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Ja({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ls(t,r==0?0:r-e)}function ls(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Ha(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:as(t,i)}function Ha(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Ka(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ua(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function cs(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ua(n,r,i,e))}l==null&&(l=_a(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Kn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return _n(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function _n(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function us(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Xa(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return us(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=fs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Qa=/[\u0590-\u08ac]/;function Za(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Qa.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:us(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let ds=null,hs=null,ps=!1;function ec(n,e,t){return ds==e&&hs==t?ps:(ds=e,hs=t,ps=t=="up"||t=="down"?Xa(n,e,t):Za(n,e,t))}const te=0,ms=1,qe=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof bs){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof gs&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?qe:ms,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?qe:se}r=o}this.dirty=qe}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?qe:ms;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class tc extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Gn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=Ss(f,r,t),c?a=new nc(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new ic(this,o&&o.node,e);lc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==qe)&&(o&&this.protectLocalComposition(e,o),ks(this.contentDOM,this.children,e),at&&ac(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=cc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new tc(this,s,t,i);e.input.compositionNodes.push(o),this.children=Gn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=xs(this.dom,this.nodeDOM,Un(this.outerDeco,this.node,t),Un(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ys(n,e,t,r,i){Ss(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class bs extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class nc extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function ks(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function oc(n,e){return n.type.side-e.type.side}function lc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ac(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function cc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Gn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Yn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&za(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Cs(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function uc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Ns(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Es(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Es(n)}function Es(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Qn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Ds(n){return n.editable&&!n.hasFocus()?!1:As(n)}function As(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function dc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Zn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Is(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Zn(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=Zn(n.state,e);return i?Ee(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?hc(n):pc(n)}function hc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Rs(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?er(n,t,r):i&&er(n,i,s)}function pc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function vs(n,e){let t=n.state.doc.resolve(e);if(!(V||rs)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ps(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Zn(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Bs(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function zs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function yc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;zs(n,r,"true"),setTimeout(()=>zs(n,r,"false"),20)}return!1}function bc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function kc(n,e){let t=e.keyCode,r=bc(e);if(t==8||ee&&t==72&&r=="c")return Bs(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Bs(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?vs(n,n.state.selection.from)=="ltr"?-1:1:-1;return Is(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?vs(n,n.state.selection.from)=="ltr"?1:-1:1;return Is(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Ps(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return yc(n)||Ps(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function tr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=Js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=js[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` +(function(){"use strict";var Dr=Object.defineProperty,hl=(n,e)=>{let t={};for(var r in n)Dr(t,r,{get:n[r],enumerable:!0});return Dr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ar(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function vr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Br(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Pr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Pr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Pr(s.content,e-i-1,t-i-1)))}function Br(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Br(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function pl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return zr(n,e,t,0)}function zr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&wn(n,e,i+1),o=r.depth>i&&wn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Fr(s,o),Be(ze(s,Lr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=wn(n,e,t+1);Be(ze(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function ml(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Vr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),$r(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):$r(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function $r(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new kl(e,t);if(r.next==null)return Le.empty;let i=Wr(r);r.next&&r.err("Unexpected trailing text");let s=Ol(Tl(i));return Nl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Le.empty=new Le(!0);class kl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Wr(n){let e=[];do e.push(xl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function xl(n){let e=[];do e.push(Sl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Sl(n){let e=wl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=Ml(n,e);else break;return e}function jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Ml(n,e){let t=jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Cl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function wl(n){if(n.eat("(")){let e=Wr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Cl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Tl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Kr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new al(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function El(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Dl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?El(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Ur(e,i.attrs),this.excluded=null;let s=Hr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Kr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Yr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Gr.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Xr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Xr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Gr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Xr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Al(n){return n.tag!=null}function Il(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Al(i))this.tags.push(i);else if(Il(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ti(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ti(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ni(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ni(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Qr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Rl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Zr={ol:!0,ul:!0},gt=1,Tn=2,yt=4;function ei(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Tn:0):n&&n.whitespace=="pre"?gt|Tn:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Qr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ti{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ei(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Tn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ri(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function vl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Zr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Pl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ni(n){let e={};for(let t in n)e[t]=n[t];return e}function ri(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ii(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ii(e.marks)}}function ii(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const si=new WeakMap;function Bl(n){let e=si.get(n);return e===void 0&&si.set(n,e=zl(n)),e}function zl(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const oi=65535,li=Math.pow(2,16);function Fl(n,e){return n+e*li}function ai(n){return n&oi}function Ll(n){return(n-(n&oi))/li}const ci=1,fi=2,_t=4,ui=8;class On{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ui)>0}get deletedBefore(){return(this.delInfo&(ci|_t))>0}get deletedAfter(){return(this.delInfo&(fi|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ai(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Fl(l/3,e-a),m=e==a?fi:e==u?ci:_t;return(t<0?e!=a:e!=u)&&(m|=ui),new On(h,m,p)}i+=f-c}return r?e+i:new On(e+i,0,null)}touches(e,t){let r=0,i=ai(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(En(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Dn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Vl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function $l(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function An(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Wl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Kl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&_l(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&mi(n,o,l,s),An(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&pi(n,o,l,s),!1}})}function pi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function _l(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Ul(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Gl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return gi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Yl(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&gi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Xl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);mi(n,f.node(),f.before(),l)}o.inlineContent&&An(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);pi(n,f.node(),f.before(),n.steps.length)}return n}function Ql(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return yi(i,s,r)?new R(e,t,r):new ea(i,s,r).fit()}function yi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class ea{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=bi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return xi(e,-1)<=t?!1:(this.unplaced.size>1&&xi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=bi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(ki(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=In(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function bi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,ki(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function In(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!ta(t,s.content,o)?l:null}function ta(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=na(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Si(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function ia(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Ql(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function sa(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Mi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Mi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class Ci{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return ra(this,e,t,r),this}replaceRangeWith(e,t,r){return ia(this,e,t,r),this}deleteRange(e,t){return sa(this,e,t),this}lift(e,t){return jl(this,e,t),this}join(e,t=1){return Xl(this,e,t),this}wrap(e,t){return Hl(this,e,t),this}setBlockType(e,t=e,r,i=null){return Kl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Ul(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Gl(this,e,t,r),this}addMark(e,t,r){return Vl(this,e,t,r),this}removeMark(e,t,r){return $l(this,e,t,r),this}clearIncompatible(e,t,r){return An(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new oa(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class oa{constructor(e,t){this.$from=e,this.$to=t}}let wi=!1;function Ti(n){!wi&&!n.parent.inlineContent&&(wi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ti(e),Ti(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Oi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ni=1,Xt=2,Ei=4;class aa extends Ci{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ei,this}get scrolledIntoView(){return(this.updated&Ei)>0}}function Di(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Di(t.init,r),this.apply=Di(t.apply,r)}}const ca=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Pn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ca.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Pn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ai(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ai(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ai(e.props,this,this.props),this.key=e.key?e.key.key:Ii("plugin")}getState(e){return e[this.key]}}const Bn=Object.create(null);function Ii(n){return n in Bn?n+"$"+ ++Bn[n]:(Bn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ii(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ri=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function vi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Pi=(n,e,t)=>{let r=vi(n,t);if(!r)return!1;let i=zn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(qi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},fa=(n,e,t)=>{let r=vi(n,t);if(!r)return!1;let i=zn(r);return i?Bi(n,i,e):!1},ua=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Fn(r);return i?Bi(n,i,e):!1};function Bi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const zi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=zn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function zn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Fi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Fi(n,t);if(!r)return!1;let i=Fn(r);if(!i)return!1;let s=i.nodeAfter;if(qi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ha=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},pa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},$i=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Ln(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Ln(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Ln(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ma(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Ln(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ga=ma(),ya=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ba=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ka(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function qi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ka(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Hi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ki=Hi(-1),_i=Hi(1);function xa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&di(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ui(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Gi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!Sa(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Na(e,t,n,s):Ea(e,t,s):!0:!1}}function Na(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Da(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Wn=null;const ge=function(n,e,t){let r=Wn||(Wn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Aa=function(){Wn=null},je=function(n,e,t,r){return t&&(Qi(n,e,t,r,-1)||Qi(n,e,t,r,1))},Ia=/^(img|br|input|textarea|hr)$/i;function Qi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Ia.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Ra(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function va(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),ns=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!Zi&&"webkitFontSmoothing"in Zi.documentElement.style,Fa=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function La(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Va(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function rs(n,e,t){if(!Kn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?La(s):Va(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function $a(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:is(n.dom)}}function is(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Wa({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ss(t,r==0?0:r-e)}function ss(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Ja(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:ls(t,i)}function Ja(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function qa(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ka(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function as(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ka(n,r,i,e))}l==null&&(l=Ha(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Kn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return _n(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function _n(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function fs(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ga(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return fs(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=cs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ya=/[\u0590-\u08ac]/;function Xa(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ya.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:fs(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let us=null,ds=null,hs=!1;function Qa(n,e,t){return us==e&&ds==t?hs:(us=e,ds=t,hs=t=="up"||t=="down"?Ga(n,e,t):Xa(n,e,t))}const te=0,ps=1,qe=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ys){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ms&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?qe:ps,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?qe:se}r=o}this.dirty=qe}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?qe:ps;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Za extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Gn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=xs(f,r,t),c?a=new ec(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new nc(this,o&&o.node,e);sc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==qe)&&(o&&this.protectLocalComposition(e,o),bs(this.contentDOM,this.children,e),at&&oc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=lc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Za(this,s,t,i);e.input.compositionNodes.push(o),this.children=Gn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ks(this.dom,this.nodeDOM,Un(this.outerDeco,this.node,t),Un(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function gs(n,e,t,r,i){xs(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ys extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ec extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function bs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function ic(n,e){return n.type.side-e.type.side}function sc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function oc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function lc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Gn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Yn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Pa(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Ms(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function cc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Os(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ns(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ns(n)}function Ns(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Qn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Es(n){return n.editable&&!n.hasFocus()?!1:Ds(n)}function Ds(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function fc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Zn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function As(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Zn(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=Zn(n.state,e);return i?Ee(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?uc(n):dc(n)}function uc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Is(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?er(n,t,r):i&&er(n,i,s)}function dc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function Rs(n,e){let t=n.state.doc.resolve(e);if(!(V||ns)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function vs(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Zn(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Ps(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Bs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function mc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Bs(n,r,"true"),setTimeout(()=>Bs(n,r,"false"),20)}return!1}function gc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function yc(n,e){let t=e.keyCode,r=gc(e);if(t==8||ee&&t==72&&r=="c")return Ps(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Ps(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?Rs(n,n.state.selection.from)=="ltr"?-1:1:-1;return As(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?Rs(n,n.state.selection.from)=="ltr"?1:-1:1;return As(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return vs(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return mc(n)||vs(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function tr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ws[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` -`);return{dom:a,text:d,slice:e}}function Fs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=Cc(t),wt&&wc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!xc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Tc(Ws(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(Sc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const xc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function Sc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Vs(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=$s(o[o.length-1],s.length));let f=Ls(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Ls(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Vs(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Ws(n,e,t){return et})}return Dt.createHTML(n)}function Cc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&js[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=Mc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const H={},K={},Oc={touchstart:!0,touchmove:!0};class Nc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Ec(n){for(let e in H){let t=H[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Ac(n,r)&&!ir(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},Oc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),rr(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Dc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function rr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>ir(n,r))})}function ir(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Ac(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Ic(n,e){!ir(n,e)&&H[e.type]&&(n.editable||!(e.type in K))&&H[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!_s(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||kc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(_s(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Rc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function sr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function vc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Pc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Bc(n,e,t,r,i){return sr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Pc(n,t):vc(n,t))}function zc(n,e,t,r){return sr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Fc(n,e,t,r){return sr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Lc(n,t,r)}function Lc(n,e,t){if(t.button!=0)return!1;let r=qs(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new $c(n,r)),!0):!1}function qs(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function or(n){return nn(n)}const Hs=ee?"metaKey":"ctrlKey";H.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=or(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Rc(t,n.input.lastClick)&&!t[Hs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Vc(n,o,t,!!r):(s=="doubleClick"?zc:Fc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class Ks{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Vc extends Ks{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Hs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):Bc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class $c extends Ks{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&qs(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),or(n),xe(n,"pointer")},H.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},H.contextmenu=n=>or(n);function _s(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Wc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&rs&&jc(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Us(n,Wc)};function jc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Us(n,20))};function Us(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Gs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Jc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Pa(e.focusNode,e.focusOffset),r=Ba(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Gs(n),e||n.docView&&n.docView.dirty){let t=Yn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function qc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&we<15||at&&Va<604;H.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=tr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):qc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Hc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Kc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=Fs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Hc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Ys(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,Ys(r),r.getData("text/html"),i,t)?t.preventDefault():Kc(n,t)};class Xs{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const _c=ee?"altKey":"ctrlKey";function Qs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[_c]}H.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=tr(n,l);(!t.dataTransfer.files.length||!V||ns>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Xs(f,Qs(n,t),o)},H.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Uc(n,e,n.dragging)}finally{n.dragging=null}};function Uc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Fs(n,Ys(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Qs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?ta(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Qn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}H.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},H.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},H.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)H[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=eo(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Yc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=eo(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Zs(s?to(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function cr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const Xc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Qc=G&&we<=11;class Zc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class ef{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Zc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Qc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Xc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Ds(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Ds(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||rf(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),tf(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,sf(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:lf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const lf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},af=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function cf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Yn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=of(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!af.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=oo(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&uf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=oo(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=ff(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function oo(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Qn(n,e.resolve(t.anchor),e.resolve(t.head))}function ff(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||fr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function df(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class lo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Nc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(ho),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=fo(this),co(this),this.nodeViews=uo(this),this.docView=ys(this.state.doc,ao(this),cr(this),this.dom,this),this.domObserver=new ef(this,(r,i,s,o)=>cf(this,r,i,s,o)),this.domObserver.start(),Ec(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&rr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(ho),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Gs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=uo(this);pf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&rr(this),this.editable=fo(this),co(this);let a=cr(this),c=ao(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&ja(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&hf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Jc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=ys(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&dc(this)&&p.delaySelUpdate())?ke(this,h):(Ns(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ja(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&is(this,t.getBoundingClientRect(),e)}else is(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Ga(this,e)}coordsAtPos(e,t=1){return fs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return ec(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return tr(this,e)}destroy(){this.docView&&(Dc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],cr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ra())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Ic(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Fa(this.dom.ownerDocument)==this.dom&&nf(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}lo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function ao(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function co(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function fo(n){return!n.someProp("editable",e=>e(n.state)===!1)}function hf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function uo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function pf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function ho(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mf=typeof navigator<"u"&&/Mac/.test(navigator.platform),gf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var ur in Ie)on.hasOwnProperty(ur)||(on[ur]=Ie[ur]);function yf(n){var e=mf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||gf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const bf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),kf=typeof navigator<"u"&&/Win/.test(navigator.platform);function xf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=ul.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:mo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const wf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Tf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),Of=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Nf=n=>e=>n(e),Ef=()=>({state:n,dispatch:e})=>Ji(n,e),Df=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Af=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function q(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const If=n=>({tr:e,state:t,dispatch:r})=>{const i=q(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Rf=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},vf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,go=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:go(n,t,"left"),to:go(e,t,"right")}),Bf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Pf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},zf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Ff=()=>({state:n,dispatch:e})=>ji(n,e);function Lf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Lf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function yo(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function bo(n,e,t={}){return!!yo(n,e,t)}function hr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!yo([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&bo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Re(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=hr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},$f=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||xo())&&r.dom.focus(),jf()&&!an()&&!xo()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!ko(t.state.selection))return o(),!0;const l=Wf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},qf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Hf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),So=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&So(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return So(t)}function Mo(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(Mo(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Xr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(cn(n),t.parseOptions):he.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return dt("",e,t)}function Co(n){return!("type"in n)}function wo(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Kf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Co(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):Mo(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&wo(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function To(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=To(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&wo(e,e.steps.length-1,-1)),!0):!1},Uf=()=>({state:n,dispatch:e})=>pa(n,e),Gf=()=>({state:n,dispatch:e})=>ma(n,e),Yf=()=>({state:n,dispatch:e})=>Bi(n,e),Xf=()=>({state:n,dispatch:e})=>Vi(n,e),Qf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Zf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},eu=()=>({state:n,dispatch:e})=>da(n,e),tu=()=>({state:n,dispatch:e})=>ha(n,e);function Oo(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function nu(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=nu(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function pr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?q(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const iu=(n,e={})=>({state:t,dispatch:r})=>pr(t,q(n,t.schema),e)?ga(t,r):!1,su=()=>({state:n,dispatch:e})=>qi(n,e),ou=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Ea(r)(e,t)},lu=()=>({state:n,dispatch:e})=>Wi(n,e);function No(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Eo(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const au=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=No(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,Eo(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(Eo(d.attrs,e))))})})}),a},cu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),fu=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},uu=()=>({state:n,dispatch:e})=>Fi(n,e),du=()=>({state:n,dispatch:e})=>$i(n,e),hu=()=>({state:n,dispatch:e})=>ka(n,e),pu=()=>({state:n,dispatch:e})=>Ui(n,e),mu=()=>({state:n,dispatch:e})=>_i(n,e);function gu(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const yu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=gu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Co(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function bu(n,e){const t=Re(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function ku(n,e){const t=new wi(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function xu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function mr(n){return e=>xu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Do(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Do(t())]:e}).flat(10)}function Su(n){return typeof n=="function"}function D(n,e=void 0,...t){return Su(n)?e?n.bind(e)(...t):n(...t):n}function Mu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function Cu(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function wu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Ao(n){const e=[],t=wu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Ao(r[i]),...Ao(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Io(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function Tu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Ro(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Tu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function vo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&Mu(t)?!1:t!=null))}function Po(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Ou(n,e){var t;const r=Cu(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Po))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Ro(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Io(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Po))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Ro(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Io(m,f)})),[c.name,d]}));return new Xr({topNode:o,nodes:l,marks:a})}function Nu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Eu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Au(n,e){return Ou(Du(n),e)}function Iu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` +`);return{dom:a,text:d,slice:e}}function zs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=Sc(t),wt&&Mc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!bc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Cc($s(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(kc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const bc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function kc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Ls(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Vs(o[o.length-1],s.length));let f=Fs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Fs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Ls(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function $s(n,e,t){return et})}return Dt.createHTML(n)}function Sc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ws[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=xc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const H={},K={},wc={touchstart:!0,touchmove:!0};class Tc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Oc(n){for(let e in H){let t=H[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Ec(n,r)&&!ir(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},wc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),rr(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Nc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function rr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>ir(n,r))})}function ir(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Ec(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Dc(n,e){!ir(n,e)&&H[e.type]&&(n.editable||!(e.type in K))&&H[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Ks(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||yc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Ks(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Ac(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function sr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Ic(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Rc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function vc(n,e,t,r,i){return sr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Rc(n,t):Ic(n,t))}function Pc(n,e,t,r){return sr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Bc(n,e,t,r){return sr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||zc(n,t,r)}function zc(n,e,t){if(t.button!=0)return!1;let r=Js(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new Lc(n,r)),!0):!1}function Js(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function or(n){return nn(n)}const qs=ee?"metaKey":"ctrlKey";H.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=or(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Ac(t,n.input.lastClick)&&!t[qs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Fc(n,o,t,!!r):(s=="doubleClick"?Pc:Bc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class Hs{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Fc extends Hs{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[qs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):vc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Lc extends Hs{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Js(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),or(n),xe(n,"pointer")},H.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},H.contextmenu=n=>or(n);function Ks(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Vc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&ns&&$c(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}_s(n,Vc)};function $c(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,_s(n,20))};function _s(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Us(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Wc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Ra(e.focusNode,e.focusOffset),r=va(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Us(n),e||n.docView&&n.docView.dirty){let t=Yn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function jc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&we<15||at&&Fa<604;H.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=tr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):jc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Jc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function qc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=zs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Jc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Gs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,Gs(r),r.getData("text/html"),i,t)?t.preventDefault():qc(n,t)};class Ys{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Hc=ee?"altKey":"ctrlKey";function Xs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Hc]}H.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=tr(n,l);(!t.dataTransfer.files.length||!V||ts>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Ys(f,Xs(n,t),o)},H.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Kc(n,e,n.dragging)}finally{n.dragging=null}};function Kc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=zs(n,Gs(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Xs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Zl(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Qn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}H.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},H.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},H.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)H[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Zs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Uc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Zs(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Qs(s?eo(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function cr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const Gc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Yc=G&&we<=11;class Xc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Qc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Xc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Yc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Gc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Es(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Es(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||tf(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Zc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,nf(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:sf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const sf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},of=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function lf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Yn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=rf(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!of.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=so(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&cf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=so(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=af(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function so(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Qn(n,e.resolve(t.anchor),e.resolve(t.head))}function af(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||fr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function ff(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class oo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Tc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(uo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=co(this),ao(this),this.nodeViews=fo(this),this.docView=gs(this.state.doc,lo(this),cr(this),this.dom,this),this.domObserver=new Qc(this,(r,i,s,o)=>lf(this,r,i,s,o)),this.domObserver.start(),Oc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&rr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(uo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Us(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=fo(this);df(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&rr(this),this.editable=co(this),ao(this);let a=cr(this),c=lo(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&$a(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&uf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Wc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=gs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&fc(this)&&p.delaySelUpdate())?ke(this,h):(Os(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Wa(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&rs(this,t.getBoundingClientRect(),e)}else rs(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return _a(this,e)}coordsAtPos(e,t=1){return cs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Qa(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return tr(this,e)}destroy(){this.docView&&(Nc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],cr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Aa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Dc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Ba(this.dom.ownerDocument)==this.dom&&ef(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}oo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function lo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function ao(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function co(n){return!n.someProp("editable",e=>e(n.state)===!1)}function uf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function fo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function df(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function uo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},hf=typeof navigator<"u"&&/Mac/.test(navigator.platform),pf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var ur in Ie)on.hasOwnProperty(ur)||(on[ur]=Ie[ur]);function mf(n){var e=hf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||pf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const gf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),yf=typeof navigator<"u"&&/Win/.test(navigator.platform);function bf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=cl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:po({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const Mf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Cf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),wf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Tf=n=>e=>n(e),Of=()=>({state:n,dispatch:e})=>ji(n,e),Nf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Ef=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function q(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Df=n=>({tr:e,state:t,dispatch:r})=>{const i=q(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Af=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},If=n=>n.content?/^text(\*|\+)/.test(n.content):!1,mo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:mo(n,t,"left"),to:mo(e,t,"right")}),vf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Rf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Pf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Bf=()=>({state:n,dispatch:e})=>Wi(n,e);function zf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:zf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function go(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function yo(n,e,t={}){return!!go(n,e,t)}function hr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!go([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&yo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Re(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=hr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},Lf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||ko())&&r.dom.focus(),$f()&&!an()&&!ko()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!bo(t.state.selection))return o(),!0;const l=Vf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},jf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Jf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),xo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&xo(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return xo(t)}function So(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(So(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Yr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(cn(n),t.parseOptions):he.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return dt("",e,t)}function Mo(n){return!("type"in n)}function Co(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const qf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Mo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):So(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&Co(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function wo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=wo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&Co(e,e.steps.length-1,-1)),!0):!1},Kf=()=>({state:n,dispatch:e})=>da(n,e),_f=()=>({state:n,dispatch:e})=>ha(n,e),Uf=()=>({state:n,dispatch:e})=>Pi(n,e),Gf=()=>({state:n,dispatch:e})=>Li(n,e),Yf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Xf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Qf=()=>({state:n,dispatch:e})=>fa(n,e),Zf=()=>({state:n,dispatch:e})=>ua(n,e);function To(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function eu(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=eu(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function pr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?q(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const nu=(n,e={})=>({state:t,dispatch:r})=>pr(t,q(n,t.schema),e)?pa(t,r):!1,ru=()=>({state:n,dispatch:e})=>Ji(n,e),iu=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Oa(r)(e,t)},su=()=>({state:n,dispatch:e})=>$i(n,e);function Oo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function No(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const ou=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,No(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(No(d.attrs,e))))})})}),a},lu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),au=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},cu=()=>({state:n,dispatch:e})=>zi(n,e),fu=()=>({state:n,dispatch:e})=>Vi(n,e),uu=()=>({state:n,dispatch:e})=>ya(n,e),du=()=>({state:n,dispatch:e})=>_i(n,e),hu=()=>({state:n,dispatch:e})=>Ki(n,e);function pu(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const mu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=pu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Mo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function gu(n,e){const t=Re(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function yu(n,e){const t=new Ci(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function bu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function mr(n){return e=>bu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Eo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Eo(t())]:e}).flat(10)}function ku(n){return typeof n=="function"}function D(n,e=void 0,...t){return ku(n)?e?n.bind(e)(...t):n(...t):n}function xu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function Su(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function Mu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Do(n){const e=[],t=Mu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Do(r[i]),...Do(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Ao(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function Cu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Io(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Cu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ro(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&xu(t)?!1:t!=null))}function vo(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function wu(n,e){var t;const r=Su(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ro({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(vo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Io(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Ao(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ro({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(vo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Io(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Ao(m,f)})),[c.name,d]}));return new Yr({topNode:o,nodes:l,marks:a})}function Tu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Ou(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Eu(n,e){return wu(Nu(n),e)}function Du(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Ru(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function vu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Pu(n){const e=vu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Bu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Pu(r)}function Bo(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=hr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function zu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Re(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function gr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function zo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(zo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Fu(n,e,t){const{selection:r}=e;let i=null;if(ko(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Lu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Re(n,r.schema);if(i)if(o){const c=bu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Fu(r,t,a)},Vu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),$u=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=q(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Gi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Gi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Wu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},ju=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Ju=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},qu=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Ia(r)(e,t)};function Fo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Hu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&Fo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:To(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&Fo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Ku=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=q(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Lo(n){return!n||n==="1"?null:n}function Vo(n,e){return Lo(n)===Lo(e)}const yr=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Vo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},br=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Vo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function _u(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Uu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=q(n,o.schema),p=q(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=mr(et=>gr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&gr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??v,Hd=!!_&&w.depth>=1&&w.depth-_.depth<=1,cl=!!v;if((Hd||cl)&&Ze){if(Ze.node.type===h)return ne&&cl?a().command(({tr:et,dispatch:Sn})=>{const Mn=_u(et);return Mn?(et.setSelection(Mn),Sn&&Sn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(gr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>yr(s,h)).command(()=>br(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Sn=A.filter(Mn=>d.includes(Mn.type.name));return s.ensureMarks(Sn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run()},Gu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Re(n,r.schema);return zu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Yu=(n,e,t={})=>({state:r,commands:i})=>{const s=q(n,r.schema),o=q(e,r.schema),l=pr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Xu=(n,e={})=>({state:t,commands:r})=>{const i=q(n,t.schema);return pr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Qu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Zu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},ed=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Re(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=hr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},td=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},nd=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=No(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},rd=new ie("__tiptap_decorations__"),id=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(rd,{type:"force",name:n}),!0),sd=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ma(i,e)(t,r)},od=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ta(i,e)(t,r)};var ld=ml({blur:()=>wf,clearContent:()=>Tf,clearNodes:()=>Of,command:()=>Nf,createParagraphNear:()=>Ef,cut:()=>Df,deleteCurrentNode:()=>Af,deleteNode:()=>If,deleteRange:()=>Rf,deleteSelection:()=>Bf,enter:()=>zf,exitCode:()=>Ff,extendMarkRange:()=>Vf,first:()=>$f,focus:()=>Jf,forEach:()=>qf,insertContent:()=>Hf,insertContentAt:()=>Kf,insertDefaultBlock:()=>_f,joinBackward:()=>Yf,joinDown:()=>Gf,joinForward:()=>Xf,joinItemBackward:()=>Qf,joinItemForward:()=>Zf,joinTextblockBackward:()=>eu,joinTextblockForward:()=>tu,joinUp:()=>Uf,keyboardShortcut:()=>ru,lift:()=>iu,liftEmptyBlock:()=>su,liftListItem:()=>ou,newlineInCode:()=>lu,resetAttributes:()=>au,scrollIntoView:()=>cu,selectAll:()=>fu,selectNodeBackward:()=>uu,selectNodeForward:()=>du,selectParentNode:()=>hu,selectTextblockEnd:()=>pu,selectTextblockStart:()=>mu,setContent:()=>yu,setMark:()=>Lu,setMeta:()=>Vu,setNode:()=>$u,setNodeSelection:()=>Wu,setTextDirection:()=>ju,setTextSelection:()=>Ju,sinkListItem:()=>qu,splitBlock:()=>Hu,splitListItem:()=>Ku,toggleList:()=>Uu,toggleMark:()=>Gu,toggleNode:()=>Yu,toggleWrap:()=>Xu,undoInputRule:()=>Qu,unsetAllMarks:()=>Zu,unsetMark:()=>ed,unsetTextDirection:()=>td,updateAttributes:()=>nd,updateDecorations:()=>id,wrapIn:()=>sd,wrapInList:()=>od});typeof process<"u"&&process.env.NODE_ENV;function ad(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return ad(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function $o(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=$o(n[r],e[r]):t[r]=e[r]}),t}var cd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},kr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>$o(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class dl extends kr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new dl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},fd=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class hl extends kr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new hl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Ru(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Iu(r,{from:a.pos,to:c.pos},l)).join(o??` +`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Au(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Iu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Ru(n){const e=Iu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function vu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Ru(r)}function Po(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=hr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Pu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Re(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function gr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Bo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Bo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Bu(n,e,t){const{selection:r}=e;let i=null;if(bo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const zu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Re(n,r.schema);if(i)if(o){const c=gu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Bu(r,t,a)},Fu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Lu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=q(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ui(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ui(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},$u=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Wu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},ju=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Da(r)(e,t)};function zo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Ju=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&zo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:wo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&zo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},qu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=q(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Fo(n){return!n||n==="1"?null:n}function Lo(n,e){return Fo(n)===Fo(e)}const yr=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},br=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Hu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Ku=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=q(n,o.schema),p=q(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=mr(et=>gr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&gr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??v,Hd=!!_&&w.depth>=1&&w.depth-_.depth<=1,ll=!!v;if((Hd||ll)&&Ze){if(Ze.node.type===h)return ne&&ll?a().command(({tr:et,dispatch:Sn})=>{const Mn=Hu(et);return Mn?(et.setSelection(Mn),Sn&&Sn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(gr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>yr(s,h)).command(()=>br(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Sn=A.filter(Mn=>d.includes(Mn.type.name));return s.ensureMarks(Sn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run()},_u=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Re(n,r.schema);return Pu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Uu=(n,e,t={})=>({state:r,commands:i})=>{const s=q(n,r.schema),o=q(e,r.schema),l=pr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Gu=(n,e={})=>({state:t,commands:r})=>{const i=q(n,t.schema);return pr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Yu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Xu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Qu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Re(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=hr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Zu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},ed=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},td=new ie("__tiptap_decorations__"),nd=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(td,{type:"force",name:n}),!0),rd=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return xa(i,e)(t,r)},id=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ca(i,e)(t,r)};var sd=hl({blur:()=>Mf,clearContent:()=>Cf,clearNodes:()=>wf,command:()=>Tf,createParagraphNear:()=>Of,cut:()=>Nf,deleteCurrentNode:()=>Ef,deleteNode:()=>Df,deleteRange:()=>Af,deleteSelection:()=>vf,enter:()=>Pf,exitCode:()=>Bf,extendMarkRange:()=>Ff,first:()=>Lf,focus:()=>Wf,forEach:()=>jf,insertContent:()=>Jf,insertContentAt:()=>qf,insertDefaultBlock:()=>Hf,joinBackward:()=>Uf,joinDown:()=>_f,joinForward:()=>Gf,joinItemBackward:()=>Yf,joinItemForward:()=>Xf,joinTextblockBackward:()=>Qf,joinTextblockForward:()=>Zf,joinUp:()=>Kf,keyboardShortcut:()=>tu,lift:()=>nu,liftEmptyBlock:()=>ru,liftListItem:()=>iu,newlineInCode:()=>su,resetAttributes:()=>ou,scrollIntoView:()=>lu,selectAll:()=>au,selectNodeBackward:()=>cu,selectNodeForward:()=>fu,selectParentNode:()=>uu,selectTextblockEnd:()=>du,selectTextblockStart:()=>hu,setContent:()=>mu,setMark:()=>zu,setMeta:()=>Fu,setNode:()=>Lu,setNodeSelection:()=>Vu,setTextDirection:()=>$u,setTextSelection:()=>Wu,sinkListItem:()=>ju,splitBlock:()=>Ju,splitListItem:()=>qu,toggleList:()=>Ku,toggleMark:()=>_u,toggleNode:()=>Uu,toggleWrap:()=>Gu,undoInputRule:()=>Yu,unsetAllMarks:()=>Xu,unsetMark:()=>Qu,unsetTextDirection:()=>Zu,updateAttributes:()=>ed,updateDecorations:()=>nd,wrapIn:()=>rd,wrapInList:()=>id});typeof process<"u"&&process.env.NODE_ENV;function od(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return od(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Vo(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=Vo(n[r],e[r]):t[r]=e[r]}),t}var ld=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},kr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Vo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class fl extends kr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new fl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},ad=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ul extends kr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ul(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Au(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Du(r,{from:a.pos,to:c.pos},l)).join(o??` -`)}}})]}}),fe.create({name:"commands",addCommands(){return{...ld}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=ku(n.before,[n,...e]);Bu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const ud=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:ud,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||Oo()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!zo(t.doc))return;const f=t.tr,u=mo({state:t,transaction:f}),{commands:d}=new Cf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new cd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Bo(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Wo=class pl extends kr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new pl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new fd({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Bo(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var dd=Wo.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`)}}})]}}),fe.create({name:"commands",addCommands(){return{...sd}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=yu(n.before,[n,...e]);vu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const cd=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:cd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||To()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Bo(t.doc))return;const f=t.tr,u=po({state:t,transaction:f}),{commands:d}=new Sf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new ld({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Po(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var $o=class dl extends kr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new dl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new ad({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Po(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var fd=$o.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""}),hd=Wo.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const jo=new WeakSet,Jo=new WeakSet;function Ge(n){const e=n;return jo.add(e),e}function xr(n){return Array.isArray(n)&&jo.has(n)}function qo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Jo.has(e)&&!xr(e)?qo(e):[e])}function pd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!xr(i)&&!Jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(xr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=qo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const Ho=(n,e)=>pd(n,e),md=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,gd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,yd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,bd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var kd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Ho("strong",{...un(this.options.HTMLAttributes,n),children:Ho("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:md,type:this.type}),Bt({find:yd,type:this.type})]},addPasteRules(){return[zt({find:gd,type:this.type}),zt({find:bd,type:this.type})]}});const xd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Sd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Md=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Cd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var wd=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:xd,type:this.type}),Bt({find:Md,type:this.type})]},addPasteRules(){return[zt({find:Sd,type:this.type}),zt({find:Cd,type:this.type})]}});const Td=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},Od=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Nd=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Td,type:this.type})]},addPasteRules(){return[zt({find:Od,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Ko(e):z.empty};var Ko=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Ko([]);var Ed=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Dd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fId&&(l=Ad(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dDd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Ad(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class ve{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Id=20;function Rd(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(Bd)&&(n=new ve(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new ve(n.done.addTransform(t,void 0,r,gn(e)),n.undone,_o(t.mapping.maps),n.prevTime,n.prevComposition):new ve(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!vd(t,n.prevRanges)),c=o?Sr(n.prevRanges,t.mapping):_o(t.mapping.maps);return new ve(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ve(n.done.rebased(t,s),n.undone.rebased(t,s),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ve(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function vd(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function _o(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Sr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Pd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Yo=Go(!1,!0),Cr=Go(!0,!0);function Fd(n){if(!n.url||n.patchSeq<=n.ackedSeq||!n.hash||n.len<0)return null;const e=[...n.spans].sort((t,r)=>t.start-r.start).map(({start:t,end:r,html:i})=>({start:t,end:r,html:i}));return e.length?JSON.stringify({src_hash:n.hash,src_len:n.len,patches:e}):null}const Xe="data-bd-src",Ld=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Au([dd.extend({content:"inline*"}),hd,kd,wd,Nd,Ld]),Vd=he.fromSchema(yn),$d=Ve.fromSchema(yn),Wd={preserveWhitespace:"full"};function Xo(n){return Vd.parse(n,Wd)}function Qo(n){const e=document.createElement("div");return e.appendChild($d.serializeFragment(n.content)),e.innerHTML}function jd(n){try{return Qo(Xo(n))===n.innerHTML}catch{return!1}}function Zo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),wr=new WeakMap;function el(n){let e=wr.get(n);return e===void 0&&(e=jd(n),wr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Tr="",Qe=!1,Or=0,kn=0,Nr="";const tl=new Map;function nl(){return Y?Qo(Y.state.doc):null}function xn(){if(!Pe||!de)return;const n=nl();if(n===null||n===Tr)return;Tr=n;const e=++Or;tl.set(de.start+","+de.end,{start:de.start,end:de.end,html:n,seq:e}),bn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Ft(){if(!Y)return;xn();const n=Pe,e=nl();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),wr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Jd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function qd(n,e,t){if(Pe===n)return;Ft();const r=Zo(n);if(!r)return;Pe=n,de=r,Tr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Xo(n),plugins:[zd(),po({"Mod-b":Yi(yn.marks.bold),"Mod-i":Yi(yn.marks.italic),"Mod-z":Yo,"Mod-y":Cr,"Shift-Mod-z":Cr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),po(wa)]});Y=new lo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&xn())}}),Y.focus(),e!==void 0&&t!==void 0&&Jd(Y,e,t)}function rl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=rl(n.target);if(!e){Ft();return}el(e)&&qd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=rl(n.target);e&&el(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const il=document.createElement("style");il.textContent=` +`):""}),ud=$o.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Wo=new WeakSet,jo=new WeakSet;function Ge(n){const e=n;return Wo.add(e),e}function xr(n){return Array.isArray(n)&&Wo.has(n)}function Jo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&jo.has(e)&&!xr(e)?Jo(e):[e])}function dd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!xr(i)&&!jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(xr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=Jo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const qo=(n,e)=>dd(n,e),hd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,pd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,md=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,gd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var yd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return qo("strong",{...un(this.options.HTMLAttributes,n),children:qo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,kd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,xd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Sd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var Md=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:bd,type:this.type}),Bt({find:xd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type}),zt({find:Sd,type:this.type})]}});const Cd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},wd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Td=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Cd,type:this.type})]},addPasteRules(){return[zt({find:wd,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Ho(e):z.empty};var Ho=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Ho([]);var Od=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Nd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fDd&&(l=Ed(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dNd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Ed(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class ve{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Dd=20;function Ad(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(vd)&&(n=new ve(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new ve(n.done.addTransform(t,void 0,r,gn(e)),n.undone,Ko(t.mapping.maps),n.prevTime,n.prevComposition):new ve(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Id(t,n.prevRanges)),c=o?Sr(n.prevRanges,t.mapping):Ko(t.mapping.maps);return new ve(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ve(n.done.rebased(t,s),n.undone.rebased(t,s),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ve(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Id(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ko(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Sr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Rd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Go=Uo(!1,!0),Cr=Uo(!0,!0);function Bd(n,e){for(const t of n)t.seq===e&&(t.acked=!0)}function zd(n){if(!n.url||!n.hash||n.len<0)return null;const e=[...n.spans];if(!e.some(r=>!r.acked))return null;const t=e.sort((r,i)=>r.start-i.start).map(({start:r,end:i,html:s})=>({start:r,end:i,html:s}));return JSON.stringify({src_hash:n.hash,src_len:n.len,patches:t})}const Xe="data-bd-src",Fd=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Eu([fd.extend({content:"inline*"}),ud,yd,Md,Td,Fd]),Ld=he.fromSchema(yn),Vd=Ve.fromSchema(yn),$d={preserveWhitespace:"full"};function Yo(n){return Ld.parse(n,$d)}function Xo(n){const e=document.createElement("div");return e.appendChild(Vd.serializeFragment(n.content)),e.innerHTML}function Wd(n){try{return Xo(Yo(n))===n.innerHTML}catch{return!1}}function Qo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),wr=new WeakMap;function Zo(n){let e=wr.get(n);return e===void 0&&(e=Wd(n),wr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Tr="",Qe=!1,jd=0,Or="";const kn=new Map;function el(){return Y?Xo(Y.state.doc):null}function xn(){if(!Pe||!de)return;const n=el();if(n===null||n===Tr)return;Tr=n;const e=++jd;kn.set(de.start+","+de.end,{start:de.start,end:de.end,html:n,seq:e,acked:!1}),bn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Ft(){if(!Y)return;xn();const n=Pe,e=el();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),wr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Jd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function qd(n,e,t){if(Pe===n)return;Ft();const r=Qo(n);if(!r)return;Pe=n,de=r,Tr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Yo(n),plugins:[Pd(),ho({"Mod-b":Gi(yn.marks.bold),"Mod-i":Gi(yn.marks.italic),"Mod-z":Go,"Mod-y":Cr,"Shift-Mod-z":Cr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),ho(Ma)]});Y=new oo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&xn())}}),Y.focus(),e!==void 0&&t!==void 0&&Jd(Y,e,t)}function tl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=tl(n.target);if(!e){Ft();return}Zo(e)&&qd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=tl(n.target);e&&Zo(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const nl=document.createElement("style");nl.textContent=` [${Xe}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } [${Xe}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } [${Xe}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } [${Xe}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } -`,document.head.appendChild(il);const sl=document.currentScript??document.querySelector("script[data-src-hash]"),ol=sl?.dataset.srcHash??"",ll=Number(sl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:ol,len:ll,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Zo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function al(){const n=Fd({url:Nr,patchSeq:Or,ackedSeq:kn,hash:ol,len:ll,spans:tl.values()});if(n===null)return;kn=Or;const e=new TextEncoder().encode(n).byteLength<=6e4;fetch(Nr,{method:"POST",mode:"no-cors",credentials:"omit",keepalive:e,body:n}).catch(()=>{})}window.addEventListener("beforeunload",()=>{Ft(),al()}),window.addEventListener("pagehide",n=>{n.persisted?xn():Ft(),al()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){e.seq>kn&&(kn=e.seq);return}if(e.type==="bd-edit:beacon"&&typeof e.url=="string"&&e.url.startsWith("/")){try{Nr=new URL(e.url,window.location.href).href}catch{}return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){xn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); +`,document.head.appendChild(nl);const rl=document.currentScript??document.querySelector("script[data-src-hash]"),il=rl?.dataset.srcHash??"",sl=Number(rl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:il,len:sl,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Qo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function ol(){const n=zd({url:Or,hash:il,len:sl,spans:kn.values()});if(n===null)return;for(const t of kn.values())t.acked=!0;const e=new TextEncoder().encode(n).byteLength<=6e4;fetch(Or,{method:"POST",mode:"no-cors",credentials:"omit",keepalive:e,body:n}).catch(()=>{})}window.addEventListener("beforeunload",()=>{Ft(),ol()}),window.addEventListener("pagehide",n=>{n.persisted?xn():Ft(),ol()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){Bd(kn.values(),e.seq);return}if(e.type==="bd-edit:beacon"&&typeof e.url=="string"&&e.url.startsWith("/")){try{Or=new URL(e.url,window.location.href).href}catch{}return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){xn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); From 03fa86f2fbfbf04eb5d6698f514e77520b0323f3 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 02:15:01 +0900 Subject: [PATCH 19/34] fix(webapp): run VisualEdit exit save in same-origin worker without iframe tokens --- CHANGELOG.md | 2 +- architecture/webapp-frontend.md | 7 +- architecture/webapp-server.md | 15 +- cmd/bdrive/desktop.go | 54 +-- cmd/bdrive/desktop_routes_test.go | 63 ---- internal/webapp/frame.go | 313 +----------------- internal/webapp/frame_test.go | 130 +------- .../webapp/frontend/e2e/inline-edit.spec.ts | 155 +++++++-- .../frontend/src/components/VisualEdit.tsx | 128 ++++--- internal/webapp/frontend/src/inline-edit.ts | 60 ++-- .../webapp/frontend/src/lib/editbeacon.ts | 223 +++++++++++-- .../frontend/src/lib/editexit.worker.ts | 94 ++++++ .../webapp/frontend/src/lib/sharedfile.ts | 6 + .../src/lib/sharedfile_restore.test.ts | 138 ++++++-- internal/webapp/server.go | 4 - ...{Editor-yrlJG67f.js => Editor-CsLWwTRs.js} | 2 +- .../static/assets/VisualEdit-CGKGr6GV.js | 1 + .../static/assets/VisualEdit-CnYT3nlY.js | 1 - .../static/assets/editexit.worker-CfTN8vfX.js | 11 + .../{index-IQjI59Ja.js => index-DyFnf9EY.js} | 6 +- ...ile-CQlHsuJ4.js => sharedfile-CtVUr4nt.js} | 4 +- internal/webapp/static/index.html | 2 +- internal/webapp/static/inline-edit.js | 24 +- 23 files changed, 714 insertions(+), 729 deletions(-) create mode 100644 internal/webapp/frontend/src/lib/editexit.worker.ts rename internal/webapp/static/assets/{Editor-yrlJG67f.js => Editor-CsLWwTRs.js} (99%) create mode 100644 internal/webapp/static/assets/VisualEdit-CGKGr6GV.js delete mode 100644 internal/webapp/static/assets/VisualEdit-CnYT3nlY.js create mode 100644 internal/webapp/static/assets/editexit.worker-CfTN8vfX.js rename internal/webapp/static/assets/{index-IQjI59Ja.js => index-DyFnf9EY.js} (99%) rename internal/webapp/static/assets/{sharedfile-CQlHsuJ4.js => sharedfile-CtVUr4nt.js} (91%) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2dd73ec..e9bc4849 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict. - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. -- **`VisualEdit` sends an exit beacon for unacknowledged iframe edits when the tab closes.** The editing iframe stays sandboxed without `allow-same-origin`, so it has no session of its own. The app acknowledges each numbered patch (`bd-edit:ack`) and hands the iframe a single-file token URL from `POST /api/p//ycollab/frame`. Once that URL has arrived, an iframe that unloads with an unacknowledged patch posts its edited spans with the source hash, cookie-free (`no-cors`, `keepalive` up to 60,000 bytes), to `POST /api/p//ycollab/frame/`. The hub splices them onto that version and merges the result through `ycollab/sync`; a repeat of an edit the app already saved changes nothing, a same-word clash parks a conflict copy, and an unconfirmed sharp shrink is refused (`422`). Delivery is still subject to the browser's teardown limits. `bdrive desktop` proxies both routes. +- **`VisualEdit` saves unacknowledged iframe edits through a same-origin exit worker when the tab closes.** The editing iframe stays `sandbox="allow-scripts"` and is never given a session, token or URL. `VisualEdit` starts a dedicated Web Worker on the app's origin (`editexit.worker.ts`), keeps it current with the rendered source, the anchored ranges and what the file and document hold after every save, and hands the iframe only one end of a `MessageChannel` (`bd-edit:port`). The app acknowledges each numbered patch it applies (`bd-edit:ack`); when the iframe unloads with an unacknowledged patch, it posts its edited spans to the worker (`bd-edit:exit`). The worker splices only anchored, script-free spans onto the render, merges the result three ways with the current document, and saves it with the app's own cookie: `POST /api/p//ycollab/sync` on a hub or `bdrive desktop`, or `PUT upload/content` on the latest `If-Match` in a plain folder, so it also works after earlier auto-saves. A same-word clash parks a conflict copy, an unconfirmed sharp shrink is not sent, and delivery is still subject to the browser's teardown limits (`keepalive` up to 60,000 bytes). ## v0.18.9 — 2026-11-11 diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index 46f3c31b..6b84cf95 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -191,7 +191,8 @@ classDiagram +collabroute.ts hasCollabRoute (only a project api base has a room; a single volume opens solo at once) +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them) +frameflush.ts frameChannel FrameChannel saveLocked (FIFO queue of iframe messages; drain posts bd-edit:flush, optionally with lock, and waits for bd-edit:flushed; saveLocked unlocks with bd-edit:unlock unless the save landed) - +editbeacon.ts beaconBody EditedSpan (the iframe's exit beacon body: src_hash, src_len, every span edited on this render; null when every patch is acknowledged) + +editbeacon.ts ackEditedSpan unackedExitPatches applyRenderPatches buildExitSaveRequest (pure exit-save logic, tested without a DOM) + +editexit.worker.ts (dedicated same-origin Web Worker: arm / sync / disarm from VisualEdit, bd-edit:exit from the iframe's MessagePort) +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room) +sharedfile.ts rebase (the head sha moved because a co-editor saved) @@ -247,8 +248,8 @@ classDiagram shareMermaid --> lib : renderMermaid inlineComment --> lib : anchor.ts (no app imports) components --> lib : rangeFor describe hitTest (Comments) - components --> lib : merge3PreferRight diffSplices frameChannel saveLocked (VisualEdit), saveNow askingShrink (FileView flush) - note for lib "editbeacon.ts is the VisualEdit iframe's last word. inline-edit.ts numbers each bd-edit:patch (seq) and VisualEdit answers bd-edit:ack once the patch is in the document. VisualEdit fetches a single-file edit URL from POST {prefix}ycollab/frame and hands it to the iframe as bd-edit:beacon. On the iframe's beforeunload or pagehide, if any patch is unacknowledged (patchSeq greater than ackedSeq), inline-edit.ts posts beaconBody straight to POST ycollab/frame/{token}: cookie-free (credentials omit, no-cors), with keepalive when the body is at most 60,000 bytes. The iframe keeps sandbox allow-scripts allow-downloads, with no allow-same-origin; the token, not a session, authorizes the write, and the hub merges it like a staging checkpoint" + components --> lib : merge3PreferRight diffSplices frameChannel saveLocked, Worker(editexit.worker.ts) + MessageChannel (VisualEdit), saveNow askingShrink (FileView flush) + note for lib "The VisualEdit exit save. The editing iframe runs the synced file's own scripts in sandbox allow-scripts with no allow-same-origin, so it is never given a session, a token or a URL. VisualEdit spawns a dedicated same-origin Worker (editexit.worker.ts) and arms it with the rendered source, the anchored allowedRanges and the live (savedText, baseSha, docText), which it keeps current on every save and rebase through SharedFile's onBaseChange. It transfers one end of a MessageChannel to inline-edit.ts as bd-edit:port. inline-edit.ts numbers each bd-edit:patch (seq) and VisualEdit answers bd-edit:ack for each patch it applied (ackEditedSpan). On beforeunload or pagehide with an unacknowledged span, inline-edit.ts posts { type: bd-edit:exit, patches } (unackedExitPatches) over that port. The worker trusts none of it: applyRenderPatches splices only anchored, ordered, script-free spans onto renderText, and buildExitSaveRequest three-way merges the result with docText / savedText, refuses an unconfirmed sharp shrink, and sends one request with the app's own same-origin cookie: POST ycollab/sync with park_on_conflict on a hub or desktop, or PUT upload/content with the latest If-Match and X-Bdrive-Park-On-Conflict on a plain folder (a create-only conflict copy for a same-word clash). keepalive when the body is at most 60,000 bytes" Browser ..> components : Done awaits FileView's flushRef lib --> api : syncCollab putText keepalive (sharedfile) components ..> inlineComment : postMessage via the ?comment=1 iframe diff --git a/architecture/webapp-server.md b/architecture/webapp-server.md index 3789a62b..129dee10 100644 --- a/architecture/webapp-server.md +++ b/architecture/webapp-server.md @@ -52,8 +52,7 @@ classDiagram -syncDurable / awaitDurable(ctx, room, text, synced) sha, snapFailure -mergeStaleUpload(w, r, v, path, base, head, tmp, size) handled, now -moveDocLive(ctx, room, text, to, sha, filed, recompute) - -handleEditFrame() POST {prefix}ycollab/frame, PermWrite - -handleEditFrameFlush() POST {prefix}ycollab/frame/{token} + -parkStaleUpload / stepConflictCopy(w, r, v, up, path, tmp, size, blob, billed) handled } class recordingMux { <> @@ -76,6 +75,7 @@ classDiagram note for Server "clientIP is a METHOD now, not a package func: X-Forwarded-For is honored when the PEER is loopback/private (the operator's own proxy) or TrustProxy is set, and then only its LAST hop. Every caller that gates on an IP — the auth rate limiter, /s/*, device rows, share telemetry — goes through it, so a client-supplied header cannot forge the identity a limiter counts" note for Server "mergeStaleUpload settles a conditional PUT {prefix}upload/content whose If-Match base lost a race: base, the head that replaced it and the incoming bytes are merged three ways (textmerge.Merge), and the result is written held to that head. Every conditional put now records the version it was held to in Op.Base (commitIfBase), so a device merging against it finds the ancestor without guessing. Text only, under maxUploadMergeBytes (4 MiB), never for a room's own write (X-Bdrive-No-Merge), merged again up to three times if the head moves during the append. A retried write whose bytes already landed (landedAfter) and that the head still carries (textmerge.RetainsChanges) is answered as done instead of merged twice. Only the same lines rewritten two ways still return 409. MCP write and edit reach the same door: a stale sha that names a real older version (staleShaError) becomes the base instead of a refusal." note for Server "POST {prefix}ycollab/sync merges a client's Yjs state (or its text against base_text) into the live room over plain HTTP, for a browser whose socket has not connected yet or a shrink it must confirm. peek reads the room without writing. ok rests on positive proof: syncDurable snapshots a few times back to back, then waits for storage (snapshotting each second, or for the lease holder's write in another process) up to ycollabSyncDurableWait (8s); an edit storage does not hold yet is a 503 the browser keeps its edits by." + note for Server "Park on conflict, for a writer that cannot answer a 409 (a closing tab). A conditional PUT {prefix}upload/content carrying X-Bdrive-Park-On-Conflict whose stale base cannot be merged is kept beside the file as a conflict copy (parkStaleUpload) instead of refused; a create-only conflict-copy write (If-None-Match: *) whose name is taken moves to the next free name a second on (stepConflictCopy). A ycollab/sync text checkpoint with park_on_conflict that clashes with the live room is parked the same way. A merged .json or .jsonl result must still parse (validMergedText) or it is not taken as a merge." class volume { -source Source @@ -593,14 +593,12 @@ classDiagram } note for printView "The one thing allowed to relax sandboxInline's wall, and by exactly one flag. The app shell cannot print synced HTML: it renders in a cross-origin frame, and a cross-origin frame prints CLIPPED to its box — the parent may not measure the content to size it, and an over-tall guess prints the slack as blank pages. So ?print=1 serves the document as a TOP-LEVEL page that presses Print itself, which needs allow-modals (the flag that gates print/alert/confirm in a sandbox). allow-same-origin stays off, so the document is still opaque and can no more reach the API or the session cookie than the frame it replaces. text/html only, because the suffix is appended AFTER the stored bytes: HTML's parser accepts that and XHTML — parsed as XML — does not. Never on a download door, where it would corrupt the saved file, and Content-Length is dropped when it fires or the promised length truncates the script straight back off" class frameToken { - <> - HMAC over project, folder or file, reader, expiry, write flag + <> + HMAC over project, folder, reader, expiry key shared at hub/frame-key in Root - read token: the page's folder as its reader, inline only - edit token (frameClaims Write true, Path): one file, exit beacon only + reads the page's folder as its reader, inline only } note for frameToken "Synced HTML renders in an opaque-origin sandbox, so the browser sends no session cookie for the page's own images, and /file?path= cannot be the base a relative src resolves against. /frame mints a path-shaped URL for a signed-in reader; authGate's frameUser resolves its token before the provider, and handleRaw re-checks the folder scope and serves through serveBlob, so the reader's current permissions decide every request. The page can read its own URL, so the token is assumed to leak to the page's authors: what leaks is one reader's read access to one folder for frameTokenTTL" - note for frameToken "The VisualEdit exit beacon. The editing iframe is sandboxed without allow-same-origin, so it has no session to save an edit the app never acknowledged. POST {prefix}ycollab/frame (handleEditFrame, PermWrite, uploads enabled) mints a single-file edit token (Write true, Path) and returns its URL. On the way out the iframe POSTs to ycollab/frame/{token} cookie-free (no-cors, keepalive up to 60,000 bytes) the body { src_hash, src_len, patches }. handleEditFrameFlush checks the token's project and path and the caller's current write access, bounds the flush (maxEditPatches 256), rebuilds the text by splicing each UTF-16 span onto the src_hash version, and hands it to the editor's own save door: ycollab/sync with base_text and park_on_conflict on a hub, the upload door with the park header on a plain folder. The result merges with what the document holds now, is idempotent when the app's own save already landed, and parks a conflict copy when somebody changed the same words. Both routes are proxied by bdrive desktop (desktopRoutes)" class editView { <> text/html only, inline only, PermWrite on the path @@ -816,8 +814,7 @@ classDiagram commentEvent ..> CommentThread : foldComments CommentThread *-- CommentAnchor Server ..> commentView : serveBlob - Server ..> frameToken : handleFrame, handleRaw, authGate, handleEditFrame, handleEditFrameFlush - frameToken ..> ydocs : edit beacon flush through POST ycollab/sync (park_on_conflict) + Server ..> frameToken : handleFrame, handleRaw, authGate frameToken ..> Backend : hub/frame-key Server o-- ReadLedger Server o-- DataIndex : Data diff --git a/cmd/bdrive/desktop.go b/cmd/bdrive/desktop.go index 6cc0e661..53d3ef21 100644 --- a/cmd/bdrive/desktop.go +++ b/cmd/bdrive/desktop.go @@ -77,10 +77,6 @@ const ( routeLocal routeMode = iota // routeProxy forwards to the project's own hub with the device token. routeProxy - // routeProxyCapability forwards to the project's own hub without the - // device token and without originGuard: the URL carries a hub-signed - // capability token, and the sandboxed iframe that posts it has Origin: null. - routeProxyCapability ) // desktopRoutes classifies every per-project route the hub serves, and the @@ -176,10 +172,6 @@ var desktopRoutes = []struct { // it has to be classified, or the desktop answers it locally. {"GET /api/p/{project}/ycollab/{room...}", routeProxy, ""}, {"POST /api/p/{project}/ycollab/sync", routeProxy, ""}, - // A framed HTML page's edit beacon: minted and flushed against the hub's - // live document for the same reason /ycollab/sync is. - {"POST /api/p/{project}/ycollab/frame", routeProxy, ""}, - {"POST /api/p/{project}/ycollab/frame/{token}", routeProxyCapability, ""}, {"POST /api/p/{project}/reads", routeLocal, "the sync client posts these straight to the hub, never through here; the app's own viewer reads go out through desktop_reads.go instead, as human traffic"}, } @@ -214,16 +206,14 @@ func desktopHandler() http.Handler { // Every per-project hub route is classified in desktopRoutes below, and the // proxies are registered FROM it — see the table for why that matters. for _, rt := range desktopRoutes { - switch rt.mode { - case routeProxy: - h := http.HandlerFunc(proxyProject) - if !strings.HasPrefix(rt.pattern, "GET ") { - h = originGuard(h) // every proxied write, exactly as before - } - mux.HandleFunc(rt.pattern, h) - case routeProxyCapability: - mux.HandleFunc(rt.pattern, proxyCapabilityProject) + if rt.mode != routeProxy { + continue // falls through to srv, answered from this machine + } + h := http.HandlerFunc(proxyProject) + if !strings.HasPrefix(rt.pattern, "GET ") { + h = originGuard(h) // every proxied write, exactly as before } + mux.HandleFunc(rt.pattern, h) } // Project creation and its template seeding are hub writes (2026-08-20 // owner decision): create goes to the signed-in hub, uploads go to the @@ -815,19 +805,6 @@ func proxyProject(w http.ResponseWriter, r *http.Request) { proxyDefaultHub(w, r) } -func proxyCapabilityProject(w http.ResponseWriter, r *http.Request) { - if m, ok := desktopMounts()[r.PathValue("project")]; ok { - proxyHubWithAuth(w, r, m.server, false) - return - } - settings, _ := config.LoadSettings() - if settings.Server == "" { - http.Error(w, "not signed in to a hub", http.StatusBadGateway) - return - } - proxyHubWithAuth(w, r, settings.Server, false) -} - // proxyDefaultHub forwards a token-scoped request (share revoke/expiry — // nothing in the path names a project) to the signed-in hub. // ponytail: a mount syncing through a DIFFERENT hub than the signed-in one @@ -865,17 +842,10 @@ func proxyDefaultHub(w http.ResponseWriter, r *http.Request) { } func proxyHub(w http.ResponseWriter, r *http.Request, server string) { - proxyHubWithAuth(w, r, server, true) -} - -func proxyHubWithAuth(w http.ResponseWriter, r *http.Request, server string, attachToken bool) { - var token string - if attachToken { - settings, _ := config.LoadSettings() - token = os.Getenv("BDRIVE_TOKEN") - if token == "" { - token = settings.Token - } + settings, _ := config.LoadSettings() + token := os.Getenv("BDRIVE_TOKEN") + if token == "" { + token = settings.Token } u := server + r.URL.Path if r.URL.RawQuery != "" { @@ -892,7 +862,7 @@ func proxyHubWithAuth(w http.ResponseWriter, r *http.Request, server string, att if ct := r.Header.Get("Content-Type"); ct != "" { req.Header.Set("Content-Type", ct) } - if attachToken && token != "" && tokenGoesTo(server) { + if token != "" && tokenGoesTo(server) { req.Header.Set("Authorization", "Bearer "+token) } // A long-lived stream cannot use initClient: its 10s whole-request timeout diff --git a/cmd/bdrive/desktop_routes_test.go b/cmd/bdrive/desktop_routes_test.go index 517b917a..728329dc 100644 --- a/cmd/bdrive/desktop_routes_test.go +++ b/cmd/bdrive/desktop_routes_test.go @@ -1,14 +1,10 @@ package main import ( - "io" - "net/http" - "net/http/httptest" "sort" "strings" "testing" - "github.com/runbear-io/beardrive/internal/config" "github.com/runbear-io/beardrive/internal/webapp" ) @@ -68,62 +64,3 @@ func TestDesktopRoutesClassified(t *testing.T) { t.Errorf("desktopRoutes lists %q, which the hub no longer serves — renamed or removed?", pat) } } - -func TestDesktopCapabilityBeaconAcceptsOpaqueOriginWithoutAmbientToken(t *testing.T) { - t.Setenv("BDRIVE_HOME", t.TempDir()) - t.Setenv("BDRIVE_TOKEN", "") - - var gotAuth, gotPath, gotBody string - hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") - gotPath = r.URL.Path - b, _ := io.ReadAll(r.Body) - gotBody = string(b) - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"ok":true}`)) - })) - defer hub.Close() - - if err := config.SaveSettings(config.Settings{ - Server: hub.URL, - Token: "ambient-device-secret", - Email: "alice@example.com", - }); err != nil { - t.Fatal(err) - } - - desk := httptest.NewServer(desktopHandler()) - defer desk.Close() - - // Minting an edit token still requires same-origin: Origin: null is refused. - mintReq, _ := http.NewRequest("POST", desk.URL+"/api/p/p-1/ycollab/frame", strings.NewReader(`{"path":"a.html"}`)) - mintReq.Header.Set("Origin", "null") - mintResp, err := http.DefaultClient.Do(mintReq) - if err != nil { - t.Fatal(err) - } - mintResp.Body.Close() - if mintResp.StatusCode != http.StatusForbidden { - t.Fatalf("mint with Origin: null = %d, want 403", mintResp.StatusCode) - } - - // Flushing with the capability token in the URL accepts Origin: null from - // the sandboxed iframe and never attaches the saved device token. - flushReq, _ := http.NewRequest("POST", desk.URL+"/api/p/p-1/ycollab/frame/tok.sig", strings.NewReader(`{"patches":[]}`)) - flushReq.Header.Set("Origin", "null") - flushReq.Header.Set("Content-Type", "text/plain;charset=UTF-8") - flushResp, err := http.DefaultClient.Do(flushReq) - if err != nil { - t.Fatal(err) - } - flushResp.Body.Close() - if flushResp.StatusCode != http.StatusOK { - t.Fatalf("flush with Origin: null = %d, want 200", flushResp.StatusCode) - } - if gotPath != "/api/p/p-1/ycollab/frame/tok.sig" || gotBody != `{"patches":[]}` { - t.Fatalf("proxied path=%q body=%q", gotPath, gotBody) - } - if gotAuth != "" { - t.Fatalf("capability beacon attached ambient Authorization=%q, want empty", gotAuth) - } -} diff --git a/internal/webapp/frame.go b/internal/webapp/frame.go index a6f99f22..d4784857 100644 --- a/internal/webapp/frame.go +++ b/internal/webapp/frame.go @@ -17,10 +17,8 @@ import ( "regexp" "strings" "time" - "unicode/utf16" "github.com/runbear-io/beardrive/internal/remote" - "github.com/runbear-io/beardrive/internal/textmerge" ) /* @@ -60,17 +58,11 @@ const frameTokenTTL = 4 * time.Hour // route can name it. const frameKeyObject = "hub/frame-key" -// frameClaims is what a frame token carries. A read token (Write false) names -// a folder the raw route reads; an edit token (Write true) names one file the -// edit beacon may write. Neither ever serves as the other. type frameClaims struct { Project string `json:"p"` - Dir string `json:"d"` // "" is the project root (raw route) - Path string `json:"f,omitempty"` // the one file an edit token writes - Write bool `json:"w,omitempty"` // an edit token + Dir string `json:"d"` // "" is the project root UserID string `json:"i"` Email string `json:"e"` - Name string `json:"n,omitempty"` Expires int64 `json:"x"` } @@ -78,9 +70,6 @@ type frameClaims struct { // in hub mode (/api/p//raw/...). var frameRouteRe = regexp.MustCompile(`^/api/(?:p/[^/]+/)?raw/([^/]+)/`) -// editFrameRouteRe matches the edit beacon's flush URL in either mode. -var editFrameRouteRe = regexp.MustCompile(`^/api/(?:p/[^/]+/)?ycollab/frame/([^/]+)$`) - // loadFrameKey returns the signing key, creating it on first use. A hub is // several processes, and a token minted by one must verify on another, so the // key is shared through storage rather than drawn per process. Volume mode and @@ -180,25 +169,20 @@ func (s *Server) verifyFrame(ctx context.Context, tok string) (frameClaims, bool return c, true } -// frameUser is authGate's door for raw-route requests and the edit beacon, -// before the provider: the cookie is exactly what these requests do not -// carry. A read token opens only the raw route and an edit token only the -// beacon's POST. handled is false for every other path. +// frameUser is authGate's door for raw-route requests, before the provider: +// the cookie is exactly what these requests do not carry. handled is false for +// every other path. func (s *Server) frameUser(w http.ResponseWriter, r *http.Request) (u User, handled, ok bool) { - write := false m := frameRouteRe.FindStringSubmatch(r.URL.Path) - if m == nil && r.Method == http.MethodPost { - m, write = editFrameRouteRe.FindStringSubmatch(r.URL.Path), true - } if m == nil { return User{}, false, false } c, valid := s.verifyFrame(r.Context(), m[1]) - if !valid || c.Write != write || (write && c.Path == "") { + if !valid { http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized) return User{}, true, false } - return User{ID: c.UserID, Email: c.Email, Name: c.Name}, true, true + return User{ID: c.UserID, Email: c.Email}, true, true } // handleFrame mints the path-shaped URL a page renders from. Asking for it is @@ -245,11 +229,6 @@ func (s *Server) handleRaw(v *volume, w http.ResponseWriter, r *http.Request) { http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized) return } - if c.Write { - // An edit token writes one file; it never reads a folder. - http.NotFound(w, r) - return - } p := r.PathValue("path") if c.Project != r.PathValue("project") || !underDir(p, c.Dir) { http.Error(w, "no such file: "+p, http.StatusNotFound) @@ -266,286 +245,6 @@ func (s *Server) handleRaw(v *volume, w http.ResponseWriter, r *http.Request) { s.serveBlob(v, w, r2, false) } -/* -The edit beacon: what a framed page that is being edited sends as it unloads. - -A page edited in place lives in the same opaque-origin frame, and its edits -reach the editor by postMessage — one hop the tab can close in the middle of. -The frame's own pagehide still runs, and a keepalive fetch it starts outlives -the page; but it carries no cookie and can read no answer (no-cors). So the -frame is handed, while the page is open, a URL that carries its own -credential: an edit token naming the editor, the project and the ONE file, -good for frameTokenTTL, opening nothing but this POST. It is minted only for -someone who may write that file, and every flush checks that again, so a -revoked editor's open page stops writing at once. - -A flush is a set of patches against the exact bytes the page was rendered -from — the hash and the UTF-16 length the editable view stamps on it -(htmledit.go) — each replacing one stamped element's inner range. The hub -rebuilds the edited text from those bytes and hands it to the door the -editor's own save takes (/ycollab/sync on a hub, the upload door on a plain -folder): merged with whatever the document holds now, idempotent when it -already holds the edit, and parked as a conflict copy when somebody changed -the same words, since a page that is gone cannot be asked. -*/ - -// maxEditPatches bounds one flush: a page edits a handful of elements. -const maxEditPatches = 256 - -// handleEditFrame mints the edit beacon's URL for one file the caller may write. -func (s *Server) handleEditFrame(v *volume, w http.ResponseWriter, r *http.Request) { - if !s.Upload.Enabled { - http.Error(w, "uploads are disabled on this server", http.StatusForbidden) - return - } - p, err := cleanUploadPath(r.URL.Query().Get("path")) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !s.writablePath(w, r, p) { - return - } - if _, _, code, err := s.lookup(v, r); err != nil { - http.Error(w, err.Error(), code) - return - } - u := s.requestUser(r) - project := r.PathValue("project") - exp := time.Now().Add(frameTokenTTL) - tok, err := s.signFrame(r.Context(), frameClaims{ - Project: project, Path: p, Write: true, - UserID: u.ID, Email: u.Email, Name: u.Name, Expires: exp.Unix(), - }) - if err != nil { - storageErr(w, http.StatusBadGateway, "could not prepare the editor", err) - return - } - base := "/api/" - if project != "" { - base += "p/" + url.PathEscape(project) + "/" - } - writeJSON(w, map[string]any{"url": base + "ycollab/frame/" + tok, "expires": exp.UnixMilli()}) -} - -type editPatch struct { - Start int `json:"start"` - End int `json:"end"` - HTML string `json:"html"` -} - -// handleEditFrameFlush applies an unloading page's unsent edits. Its caller -// is gone before the answer arrives; the answer is for tests and logs. -func (s *Server) handleEditFrameFlush(v *volume, w http.ResponseWriter, r *http.Request) { - if !s.Upload.Enabled { - http.Error(w, "uploads are disabled on this server", http.StatusForbidden) - return - } - c, ok := s.verifyFrame(r.Context(), r.PathValue("token")) - if !ok || !c.Write || c.Path == "" || c.Project != r.PathValue("project") { - http.Error(w, "this page link has expired; reload the page", http.StatusUnauthorized) - return - } - // Who may write, decided now: the token names the editor, never grants. - if !s.writablePath(w, r, c.Path) { - return - } - var req struct { - SrcHash string `json:"src_hash"` - SrcLen int `json:"src_len"` - Patches []editPatch `json:"patches"` - } - if err := json.NewDecoder(io.LimitReader(r.Body, maxSeedBytes+64<<10)).Decode(&req); err != nil { - http.Error(w, "invalid request body", http.StatusBadRequest) - return - } - if len(req.Patches) == 0 || len(req.Patches) > maxEditPatches || !blobRe.MatchString(req.SrcHash) { - http.Error(w, "invalid edit", http.StatusBadRequest) - return - } - // The page is closing and may drop the socket: the write still finishes. - ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second) - defer cancel() - - base, found := s.editBase(ctx, v, c.Path, req.SrcHash) - if !found { - writeJSONStatus(w, http.StatusConflict, map[string]any{"error": "the page's version of this file is gone", "path": c.Path}) - return - } - want, err := applyEditPatches(base, req.SrcLen, req.Patches) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if fi, ok := s.headFile(ctx, v, c.Path); ok && sharpShrink(fi.Size, int64(len(want))) { - // Nobody is left to confirm it. - writeJSONStatus(w, http.StatusUnprocessableEntity, map[string]any{ - "error": "this save would empty or sharply shrink the file", "shrink": true, "path": c.Path, - }) - return - } - who := s.requestUser(r) - var out *memWriter - if c.Project != "" { - // The editor's own save door, whole: the room's merge, the conflict - // copy, durability, quota and folder rules. - body, _ := json.Marshal(map[string]any{ - "base": req.SrcHash, "base_text": base, "text": want, "park_on_conflict": true, - }) - out = s.reenter(ctx, who, http.MethodPost, - "/api/p/"+url.PathEscape(c.Project)+"/ycollab/sync?path="+url.QueryEscape(c.Path), body, nil) - } else { - out = s.flushToFile(ctx, v, who, c.Path, base, want) - } - if ct := out.hdr.Get("Content-Type"); ct != "" { - w.Header().Set("Content-Type", ct) - } - w.WriteHeader(out.code) - _, _ = w.Write(out.body.Bytes()) -} - -// flushToFile is the edit beacon on a plain folder, which has no room: the -// edit is merged against the file as it is now and written conditionally on -// it, and a clash is parked beside it. -func (s *Server) flushToFile(ctx context.Context, v *volume, who User, p, base, want string) *memWriter { - put := func(path, text string, hdr http.Header) *memWriter { - hdr.Set(parkOnConflictHeader, "1") - return s.reenter(ctx, who, http.MethodPut, "/api/upload/content?path="+url.QueryEscape(path), []byte(text), hdr) - } - fi, ok := s.headFile(ctx, v, p) - if !ok { - w := newMemWriter() - w.code = http.StatusNotFound - w.body.WriteString("no such file: " + p) - return w - } - cur, ok := s.readHead(ctx, v, p, fi) - if !ok { - w := newMemWriter() - w.code = http.StatusBadGateway - w.body.WriteString("could not read " + p) - return w - } - text := want - switch { - case string(cur) == want: - w := newMemWriter() - writeJSON(w, map[string]any{"ok": true, "path": p, "sha": fi.Blob, "unchanged": true}) - return w - case string(cur) != base: - merged, ok := textmerge.Merge([]byte(base), cur, []byte(want)) - if !ok || !validMergedText(p, merged) { - return put(conflictPath(p, who, time.Now()), want, http.Header{"If-None-Match": {"*"}}) - } - text = string(merged) - } - return put(p, text, http.Header{"If-Match": {fi.Blob}}) -} - -// reenter runs one request through the API as who, the way putAs does. -func (s *Server) reenter(ctx context.Context, who User, method, target string, body []byte, hdr http.Header) *memWriter { - req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body)) - if err != nil { - return &memWriter{code: http.StatusInternalServerError, hdr: http.Header{}} - } - for k, vs := range hdr { - req.Header[k] = vs - } - w := newMemWriter() - s.apiMux.ServeHTTP(w, withUser(req, who)) - return w -} - -// editBase is the text of p whose content hash is sha: the file as it is, -// or — on a journal-backed source — a version p itself once held. Never any -// other path's: the hash is checked against p's own history before a blob -// is read, so a caller cannot read arbitrary content by naming its hash. -func (s *Server) editBase(ctx context.Context, v *volume, p, sha string) (string, bool) { - ok := func(b []byte) bool { - return len(b) < maxSeedBytes && textmerge.IsText(b) && sha256Hex(b) == sha - } - if fi, found := s.headFile(ctx, v, p); found { - if b, read := s.readHead(ctx, v, p, fi); read && ok(b) { - return string(b), true - } - } - rs, isRemote := v.source.(*RemoteSource) - if !isRemote { - return "", false - } - ops, err := rs.loadSourcedOps(ctx) - if err != nil { - return "", false - } - held := false - for _, so := range ops { - if so.Op.Path == p && so.Op.Blob == sha { - held = true - break - } - } - if !held { - return "", false - } - rc, err := rs.OpenBlob(ctx, sha) - if err != nil { - return "", false - } - defer rc.Close() - b, err := io.ReadAll(io.LimitReader(rc, maxSeedBytes+1)) - if err != nil || !ok(b) { - return "", false - } - return string(b), true -} - -// readHead reads p's current bytes, bounded like a seed. -func (s *Server) readHead(ctx context.Context, v *volume, p string, fi FileInfo) ([]byte, bool) { - rc, err := v.source.Open(ctx, p, fi) - if err != nil { - return nil, false - } - defer rc.Close() - b, err := io.ReadAll(io.LimitReader(rc, maxSeedBytes+1)) - return b, err == nil -} - -// applyEditPatches rebuilds an edited page from the bytes it was rendered -// from. Offsets are UTF-16 code units, as the editable view stamps them -// (utf16Len) and as the browser's strings count. Each patch replaces one -// element's inner range, which always sits strictly inside the document — -// past its start tag and before its end tag — so none can replace the whole -// file; they are in order and do not overlap, and none splits a surrogate -// pair. -func applyEditPatches(base string, srcLen int, patches []editPatch) (string, error) { - units := utf16.Encode([]rune(base)) - if len(units) != srcLen { - return "", errors.New("the page's length does not match its version of the file") - } - inPair := func(i int) bool { - return i > 0 && i < len(units) && utf16.IsSurrogate(rune(units[i])) && units[i] >= 0xDC00 - } - out := make([]uint16, 0, len(units)) - prev := 0 - for i, p := range patches { - if p.Start <= 0 || p.Start > p.End || p.End >= srcLen || p.Start < prev || (i > 0 && p.Start < patches[i-1].End) { - return "", errors.New("edit ranges are out of order or outside the page") - } - if inPair(p.Start) || inPair(p.End) || !textmerge.IsText([]byte(p.HTML)) { - return "", errors.New("an edit is not text") - } - out = append(out, units[prev:p.Start]...) - out = append(out, utf16.Encode([]rune(p.HTML))...) - prev = p.End - } - out = append(out, units[prev:]...) - want := string(utf16.Decode(out)) - if len(want) >= maxSeedBytes { - return "", errors.New("the edited page is too large to save") - } - return want, nil -} - func underDir(p, dir string) bool { if p == "" || strings.Contains("/"+p+"/", "/../") { return false diff --git a/internal/webapp/frame_test.go b/internal/webapp/frame_test.go index 199e89c4..4a8a0d8a 100644 --- a/internal/webapp/frame_test.go +++ b/internal/webapp/frame_test.go @@ -3,9 +3,9 @@ package webapp import ( "bytes" "context" - "encoding/json" "errors" "io" + "encoding/json" "net/http" "net/http/httptest" "net/url" @@ -293,131 +293,3 @@ func TestFrameKeyCreateIsAtomicOrRefused(t *testing.T) { } } } - -// beacon is what the edit frame's unload sends: a no-cors keepalive POST, no -// cookie, a text/plain body. -func beacon(h http.Handler, target string, body any) *httptest.ResponseRecorder { - data, _ := json.Marshal(body) - req := httptest.NewRequest("POST", target, bytes.NewReader(data)) - req.Header.Set("Content-Type", "text/plain;charset=UTF-8") - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - return rec -} - -/* -An edit typed into a framed page whose postMessage never reached the editor — -the tab closed first — still lands: the frame's own unload beacon carries it, -with a token that writes that one file and nothing else. - - A read token cannot write and an edit token cannot read. The beacon - merges into the document, is idempotent when repeated, parks a conflict - copy when somebody changed the same words meanwhile, and stops the - moment the editor may no longer write. -*/ -func TestEditFrameFlushSavesUnackedSpanAndBlocksReadTokens(t *testing.T) { - h, srv, c, p := frameHub(t) - const path = "site/page.html" - const page = "

Hello world

Second line

\n" - api := "/api/p/" + p.ID + "/" - file := func() string { - t.Helper() - return doAs(t, h, "GET", api+"file?path="+url.QueryEscape(path), nil, c["alice"]).Body.String() - } - if rec := doAs(t, h, "PUT", api+"upload/content?path="+url.QueryEscape(path), []byte(page), c["bob"]); rec.Code != 200 { - t.Fatalf("seed: %d %s", rec.Code, rec.Body) - } - - // A read token opens the raw route only. - readURL := frameURL(t, h, p, path, c["bob"]) - readTok := strings.Split(strings.TrimPrefix(readURL, api+"raw/"), "/")[0] - if rec := beacon(h, api+"ycollab/frame/"+readTok, map[string]any{}); rec.Code != http.StatusUnauthorized && rec.Code != http.StatusForbidden { - t.Fatalf("a read token flushed an edit: %d %s", rec.Code, rec.Body) - } - - rec := doAs(t, h, "POST", api+"ycollab/frame?path="+url.QueryEscape(path), nil, c["bob"]) - if rec.Code != 200 { - t.Fatalf("mint edit token: %d %s", rec.Code, rec.Body) - } - var minted struct{ URL string } - if err := json.Unmarshal(rec.Body.Bytes(), &minted); err != nil || !strings.HasPrefix(minted.URL, api+"ycollab/frame/") { - t.Fatalf("minted %s", rec.Body) - } - editTok := strings.TrimPrefix(minted.URL, api+"ycollab/frame/") - if rec := cookieless(h, api+"raw/"+editTok+"/"+path); rec.Code != http.StatusUnauthorized && rec.Code != http.StatusNotFound { - t.Fatalf("an edit token read the page: %d %s", rec.Code, rec.Body) - } - if rec := doAs(t, h, "POST", api+"ycollab/frame?path="+url.QueryEscape(path), nil, c["dave"]); rec.Code != http.StatusForbidden { - t.Fatalf("an outsider minted an edit token: %d", rec.Code) - } - - flush := func(word string) *httptest.ResponseRecorder { - start := strings.Index(page, "Hello world") - return beacon(h, minted.URL, map[string]any{ - "src_hash": shaOf(page), "src_len": len(page), - "patches": []map[string]any{{"start": start, "end": start + len("Hello world"), "html": word}}, - }) - } - edited := strings.Replace(page, "Hello world", "Hello there", 1) - for attempt := range 2 { // the second is the same beacon again - if rec := flush("Hello there"); rec.Code != 200 { - t.Fatalf("flush (attempt %d): %d %s", attempt, rec.Code, rec.Body) - } - if got := file(); got != edited { - t.Fatalf("file after flush %d = %q, want %q", attempt, got, edited) - } - } - if cc := conflictTexts(t, srv, p.ID, path); len(cc) != 0 { - t.Fatalf("an idempotent flush parked %d copies", len(cc)) - } - - // Out-of-range and malformed patches write nothing. - for _, bad := range []map[string]any{ - {"src_hash": shaOf(page), "src_len": len(page), "patches": []map[string]any{{"start": 0, "end": len(page), "html": "x"}}}, - {"src_hash": shaOf(page), "src_len": len(page) + 1, "patches": []map[string]any{{"start": 5, "end": 6, "html": "x"}}}, - {"src_hash": shaOf("not this page"), "src_len": 13, "patches": []map[string]any{{"start": 1, "end": 2, "html": "x"}}}, - } { - if rec := beacon(h, minted.URL, bad); rec.Code == 200 { - t.Fatalf("bad flush %v accepted: %s", bad, rec.Body) - } - } - if got := file(); got != edited { - t.Fatalf("a refused flush wrote: %q", got) - } - - // Carol changes the same words; the page that never saw it still flushes - // against what it rendered. The page's edit is kept beside the file. - carols := strings.Replace(page, "Hello world", "Hello carol", 1) - if rec := doAs(t, h, "PUT", api+"upload/content?path="+url.QueryEscape(path), []byte(carols), c["carol"]); rec.Code != 200 { - t.Fatalf("carol's write: %d %s", rec.Code, rec.Body) - } - rec = flush("Hello bob") - if rec.Code != 200 { - t.Fatalf("clashing flush: %d %s", rec.Code, rec.Body) - } - var out struct { - Parked string `json:"parked"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || !strings.HasPrefix(out.Parked, path+".bdrive-conflict-") { - t.Fatalf("clashing flush answered %s: want a conflict copy", rec.Body) - } - if got := file(); got != carols { - t.Fatalf("file = %q, want carol's %q", got, carols) - } - want := strings.Replace(page, "Hello world", "Hello bob", 1) - if got := doAs(t, h, "GET", api+"file?path="+url.QueryEscape(out.Parked), nil, c["alice"]).Body.String(); got != want { - t.Fatalf("copy %s = %q, want the page's %q", out.Parked, got, want) - } - - // Bob may no longer write: the open page's beacon stops at once. - if err := srv.Projects.SetPerm(p.ID, "bob@x.io", PermRead); err != nil { - t.Fatal(err) - } - before := file() - if rec := flush("Hello again"); rec.Code != http.StatusForbidden { - t.Fatalf("flush after write was revoked: %d %s", rec.Code, rec.Body) - } - if got := file(); got != before { - t.Fatalf("a revoked flush wrote: %q", got) - } -} diff --git a/internal/webapp/frontend/e2e/inline-edit.spec.ts b/internal/webapp/frontend/e2e/inline-edit.spec.ts index b6c6af86..a4f5b6cb 100644 --- a/internal/webapp/frontend/e2e/inline-edit.spec.ts +++ b/internal/webapp/frontend/e2e/inline-edit.spec.ts @@ -1,4 +1,10 @@ import { test, expect, Page, FrameLocator } from "@playwright/test"; +import { execFileSync, spawn } from "node:child_process"; +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { login, ADMIN, READER } from "./helpers"; /* Click-to-edit on a synced HTML file, end to end: the real hub, the real @@ -474,11 +480,36 @@ test("two people editing different paragraphs both land", async ({ page, browser expect(after).toContain(''); }); +/* Every message the editing iframe receives, recorded inside it (init scripts + run in every frame), so a spec can prove what the sandbox was handed. */ +async function recordFrameMessages(page: Page) { + await page.addInitScript(() => { + const seen: string[] = []; + Object.defineProperty(window, "__bdSeen", { value: seen }); + window.addEventListener("message", (e) => seen.push(JSON.stringify(e.data) ?? ""), true); + }); +} + +// Every bd-edit:patch is dropped before VisualEdit's listener can see it, so +// nothing it carries is spliced, saved or acknowledged by the app. +async function dropPatches(page: Page) { + await page.evaluate(() => { + window.addEventListener( + "message", + (e) => { + const d: unknown = e.data; + if (d && typeof d === "object" && "type" in d && d.type === "bd-edit:patch") e.stopImmediatePropagation(); + }, + true, + ); + }); +} + /* A tab closed before the edit's postMessage reached the app. The app never - hears the patch (every one is dropped on its way in, so nothing is spliced - and nothing is acknowledged), so its own exit flush has nothing to send. - The frame, sandboxed without a session, posts the edit itself on the way - out to the single-file beacon URL the app handed it — and it lands. */ + hears the patch, so its own exit flush has nothing to send. The frame hands + the edit down its MessagePort to the app's exit worker, which saves it with + the app's session as the tab goes — and the frame was never handed a URL, + a token or anything else it could write with. */ test("an edit whose postMessage is not delivered before tab close still lands", async ({ page, browser }) => { await login(page, ADMIN); // the verifier: makes the file and reads it back const id = await project(page); @@ -488,33 +519,26 @@ test("an edit whose postMessage is not delivered before tab close still lands", try { const editor = await ctx.newPage(); await login(editor, ADMIN); - const issued = editor.waitForResponse( - (r) => r.url().includes("/ycollab/frame?") && r.request().method() === "POST" && r.ok(), - ); + await recordFrameMessages(editor); await editor.goto(`/${id}/${file}`); await editor.click("#edit-btn"); const frame = editor.frameLocator("iframe.htmlview"); - await frame.locator("html[data-bd-ready]").waitFor(); - await issued; - // The URL reaches the frame as a postMessage of its own, which nothing in - // the frame makes observable; one beat for that task to run. - await editor.waitForTimeout(200); - - // Every patch is dropped before VisualEdit's listener can see it. - await editor.evaluate(() => { - window.addEventListener( - "message", - (e) => { - const d: unknown = e.data; - if (d && typeof d === "object" && "type" in d && d.type === "bd-edit:patch") e.stopImmediatePropagation(); - }, - true, - ); - }); + await frame.locator("html[data-bd-exit='ready']").waitFor(); + await dropPatches(editor); await frame.locator("p.lead").click(); await editor.keyboard.press("End"); await editor.keyboard.type(" Saved across close."); + + // What the sandbox was ever sent: control messages only, no URL, no token. + const child = editor.frames().find((f) => f.url().includes("edit=1")); + expect(child).toBeTruthy(); + const seen = await child!.evaluate(() => (window as unknown as { __bdSeen: string[] }).__bdSeen.slice()); + const types = seen.map((s) => (JSON.parse(s) as { type?: string } | null)?.type); + expect(types).toContain("bd-edit:port"); + for (const t of types) expect(["bd-edit:port", "bd-edit:ack", "bd-edit:flush", "bd-edit:unlock"]).toContain(t); + for (const s of seen) expect(s).not.toMatch(/https?:|\/api\/|token/i); + await editor.close({ runBeforeUnload: true }); // the tab goes at once // The context (its network) outlives the tab, as the browser does; only @@ -527,6 +551,89 @@ test("an edit whose postMessage is not delivered before tab close still lands", } }); +const REPO = fileURLToPath(new URL("../../../../", import.meta.url)); + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.once("error", reject); + srv.listen(0, "127.0.0.1", () => { + const addr = srv.address(); + srv.close(() => (addr && typeof addr === "object" ? resolve(addr.port) : reject(new Error("no port")))); + }); + }); +} + +/* A plain folder (`bdrive serve --upload --dir`, DirSource): no room, no past + versions — a file is named by its mtime and size, so once autosave #1 has + rewritten it the version the frame rendered is gone. Edit #2 is then never + delivered to the app before the tab closes; the exit worker must build it + on the LATEST version (autosave #1's), not the render, or it is refused and + lost. Both edits must be on disk. */ +test("plain-folder mode: an auto-saved edit followed by an undelivered edit before tab close keeps both", async ({ + browser, +}) => { + test.setTimeout(240_000); // includes building the binary + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bdrive-dir-e2e-")); + const site = path.join(tmp, "site"); + fs.mkdirSync(site); + const page = path.join(site, "page.html"); + fs.writeFileSync(page, FIXTURE); + const bin = path.join(tmp, "bdrive"); + execFileSync("go", ["build", "-o", bin, "./cmd/bdrive"], { cwd: REPO, stdio: "inherit" }); + const port = await freePort(); + const server = spawn(bin, ["serve", "--upload", "--addr", `127.0.0.1:${port}`, "--dir", site], { + env: { ...process.env, BDRIVE_HOME: path.join(tmp, "home") }, + stdio: "inherit", + }); + const ctx = await browser.newContext(); + try { + const base = `http://127.0.0.1:${port}`; + await expect + .poll( + async () => { + try { + return (await fetch(base + "/api/config")).status; + } catch { + return 0; + } + }, + { timeout: 30_000 }, + ) + .toBe(200); + const onDisk = () => fs.readFileSync(page, "utf8"); + + const editor = await ctx.newPage(); + await editor.goto(base + "/page.html"); + await editor.click("#edit-btn"); + const frame = editor.frameLocator("iframe.htmlview"); + await frame.locator("html[data-bd-exit='ready']").waitFor(); + + // Edit #1 autosaves: the file on disk (and its ETag) moves on. + await frame.locator("p.lead").click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" First autosaved."); + await expect.poll(onDisk, { timeout: 15_000 }).toContain("First autosaved."); + + // Edit #2, in another element, never reaches the app; the tab goes. + await dropPatches(editor); + await frame.locator("h1").click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" Second across close."); + await editor.close({ runBeforeUnload: true }); + + await expect.poll(onDisk, { timeout: 15_000 }).toContain("Second across close."); + const after = onDisk(); + expect(after).toContain("Revenue grew steadily across every region. First autosaved."); + expect(after).toContain("Quarterly report Second across close."); + expect(after.split("").length - 1).toBe(1); + } finally { + await ctx.close().catch(() => {}); + server.kill(); + fs.rmSync(tmp, { recursive: true, force: true }); + } +}); + /* A file that is not in English, edited through the whole real stack. The offsets the server stamps are UTF-16 code units, because that is how a diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index e09724bc..dbee4bef 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -1,7 +1,6 @@ import { useEffect, useRef, useState } from "react"; import * as Y from "yjs"; import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile"; -import { postJSON } from "../api/http"; import { diffSplices, merge3PreferRight } from "../lib/merge3"; import { frameChannel, saveLocked } from "../lib/frameflush"; import { type CollabStatus } from "../lib/collab"; @@ -33,8 +32,8 @@ import { askShrink, withdrawShrink } from "./ShrinkDialog"; // the frame held. type Ready = { type: "bd-edit:ready"; hash: string; len: number; ranges: Span[] }; // `seq` numbers the frame's patches; each is acknowledged (`bd-edit:ack`) once -// it is in the document, and one never acknowledged goes out by the frame's -// own exit beacon (lib/editbeacon.ts). +// it is in the document, and one never acknowledged is handed on the way out +// to this component's exit worker (lib/editexit.worker.ts). type Patch = { type: "bd-edit:patch"; seq?: number; start: number; end: number; html: string }; type Clobbered = { type: "bd-edit:clobbered" }; type Flushed = { type: "bd-edit:flushed"; id: number }; @@ -165,7 +164,7 @@ export function VisualEdit({ const retryTimer = setTimeout(() => { if (!anchored && attempt.current < 1) { attempt.current++; - setGen((g) => g + 1); + reload(); } }, 11_000); const stuckTimer = setTimeout(() => setStuck(true), 24_000); @@ -177,32 +176,69 @@ export function VisualEdit({ decides whether the editor may close. */ const channel = frameChannel(); let frameReady = false; - /* The frame's way out for a patch that never reaches here — a tab closed - between the keystroke and its message (lib/editbeacon.ts): a - single-file save URL it may post to without cookies. Fetched for each - render, refreshed before it expires, handed to the frame once ready. */ - let beaconPath = ""; - let beaconTimer: ReturnType | undefined; - let beaconStopped = false; - const sendBeaconURL = () => { - if (beaconPath && frameReady) frame.current?.contentWindow?.postMessage({ type: "bd-edit:beacon", url: beaconPath }, "*"); + /* The exit save (lib/editexit.worker.ts): a patch that never reaches here + — a tab closed between the keystroke and its message — is posted by + the frame down a MessagePort to a dedicated worker on this origin, + which outlives the tab long enough to save it with the app's own + session. The frame never sees a URL or a credential. The worker is + armed once the ranges are anchored, kept on what the file holds as + saves land, and disarmed whenever the frame is replaced on purpose. */ + let exitWorker: Worker | null = null; + try { + exitWorker = + typeof Worker !== "undefined" + ? new Worker(new URL("../lib/editexit.worker.ts", import.meta.url), { type: "module" }) + : null; + } catch { + exitWorker = null; // no worker (a CSP, an old browser): no exit save, as before + } + let workerDisarmed = false; + let latestSavedText = seed.current; + let latestBaseSha: string | undefined = shaRef.current; + const activeDocText = () => + stageDoc ? stageDoc.getText("body").toString() : (fileRef.current?.collab.text.toString() ?? ""); + const syncExitWorker = () => { + if (!exitWorker || workerDisarmed) return; + exitWorker.postMessage({ + type: "sync", + savedText: latestSavedText, + baseSha: latestBaseSha, + hasBaseSha: true, + docText: activeDocText(), + }); }; - const fetchBeacon = () => { - postJSON<{ url?: unknown; expires?: unknown }>(apiBase + "ycollab/frame?path=" + encodeURIComponent(path), {}) - .then((r) => { - if (beaconStopped || typeof r?.url !== "string") return; - beaconPath = r.url; - sendBeaconURL(); - if (typeof r.expires !== "number") return; - // A deadline (epoch ms) or a lifetime (ms): renewed a minute early. - const left = r.expires > 1e12 ? r.expires - Date.now() : r.expires; - beaconTimer = setTimeout(fetchBeacon, Math.max(30_000, left - 60_000)); - }) - .catch(() => { - // An older hub: no beacon, exactly as before. - }); + const disarmExitWorker = () => { + if (!exitWorker || workerDisarmed) return; + workerDisarmed = true; + exitWorker.postMessage({ type: "disarm" }); + exitWorker.terminate(); + }; + // Every deliberate re-render of the frame: its unload is no tab closing. + const reload = () => { + disarmExitWorker(); + setGen((g) => g + 1); + }; + const armExitWorker = (renderText: string) => { + const win = frame.current?.contentWindow; + if (!exitWorker || workerDisarmed || !win) return; + const mc = new MessageChannel(); + exitWorker.postMessage( + { + type: "arm", + apiBase, + path, + who: meRef.current?.name, + renderText, + renderLen: renderText.length, + allowedRanges: [...anchors.keys()], + savedText: latestSavedText, + baseSha: latestBaseSha, + docText: renderText, + }, + [mc.port1], + ); + win.postMessage({ type: "bd-edit:port" }, "*", [mc.port2]); }; - fetchBeacon(); const ackPatch = (msg: Patch) => { if (typeof msg.seq === "number") frame.current?.contentWindow?.postMessage({ type: "bd-edit:ack", seq: msg.seq }, "*"); }; @@ -300,7 +336,7 @@ export function VisualEdit({ } else { anchors.clear(); anchored = false; - if (prevText !== nextText) setGen((g) => g + 1); + if (prevText !== nextText) reload(); } prev.destroy(); } @@ -326,6 +362,11 @@ export function VisualEdit({ onPeers: (n) => cb.current.onPeers?.(n), onSaved: (t) => cb.current.onSaved?.(t), onWriting: () => cb.current.onWriting?.(), + onBaseChange: (savedText, nextBaseSha) => { + latestSavedText = savedText; + latestBaseSha = nextBaseSha; + syncExitWorker(); + }, soloText: () => (stageDoc ? stageDoc.getText("body").toString() : seed.current), soloApply: ({ from, to, insert }) => { if (!stageDoc) return; @@ -404,7 +445,7 @@ export function VisualEdit({ // and it fails closed on any future way the two could drift apart. if (ranges.some((r) => r.end > text.length || r.start > r.end)) { ranges = null; - setGen((g) => g + 1); + reload(); return; } /* The ranges describe the document the SERVER served. If this side holds @@ -420,7 +461,7 @@ export function VisualEdit({ digest !== null ? digest !== srcHash : srcLen >= 0 && text.length !== srcLen; if (moved) { ranges = null; - setGen((g) => g + 1); + reload(); return; } anchors.clear(); @@ -433,6 +474,7 @@ export function VisualEdit({ }); } anchored = true; + armExitWorker(text); setArmed(true); cb.current.onRendered?.(); }; @@ -463,16 +505,19 @@ export function VisualEdit({ srcHash = msg.hash; srcLen = msg.len; frameReady = true; - sendBeaconURL(); return anchorRanges(); // no-op until the document is seeded too } if (msg.type !== "bd-edit:patch") return; if (!anchored) return anchorRanges().then(() => { - if (applyPatch(msg)) ackPatch(msg); + if (!applyPatch(msg)) return; + ackPatch(msg); + syncExitWorker(); }); - if (applyPatch(msg)) ackPatch(msg); + if (!applyPatch(msg)) return; + ackPatch(msg); + syncExitWorker(); }; const applyPatch = (msg: Patch): boolean => { const a = anchors.get(key(msg)); @@ -487,7 +532,7 @@ export function VisualEdit({ if ((sWhole && a.span < sText.length) || sSpan > a.span * 4 + 256) { anchors.clear(); anchored = false; - setGen((g) => g + 1); + reload(); return false; } const sLive = sText.toString().slice(sFrom.index, sTo.index); @@ -535,7 +580,7 @@ export function VisualEdit({ // The ranges cannot be trusted any more; re-render and re-anchor. anchors.clear(); anchored = false; - setGen((g) => g + 1); + reload(); return false; } @@ -572,7 +617,10 @@ export function VisualEdit({ // The document filling in is itself a reason to try anchoring again: the // relay may seed AFTER onReady fires, and a peer's first update is the // other way an empty room becomes a real one. - const retry = () => void anchorRanges(); + const retry = () => { + syncExitWorker(); + void anchorRanges(); + }; file.collab.text.observe(retry); window.addEventListener("message", onMessage); @@ -580,8 +628,9 @@ export function VisualEdit({ if (handle?.current === exposed) handle.current = null; frameReady = false; channel.close(); - beaconStopped = true; - clearTimeout(beaconTimer); + // The exit worker stays armed: a tab closing goes through here too, and + // the frame's last patch may yet arrive at it. Disarmed below, once the + // editor is really gone and nothing more can come. clearTimeout(retryTimer); clearTimeout(stuckTimer); clearTimeout(stageTimer); @@ -602,6 +651,7 @@ export function VisualEdit({ window.removeEventListener("message", onMessage); clearTimeout(stageTimer); file.destroy(); + disarmExitWorker(); stageDoc?.destroy(); }, 300); }; diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts index 2158a2ce..c4095f22 100644 --- a/internal/webapp/frontend/src/inline-edit.ts +++ b/internal/webapp/frontend/src/inline-edit.ts @@ -11,9 +11,10 @@ patch before the answer has landed — and, with `lock`, stops accepting edits until `bd-edit:unlock`, so nothing typed during Done's save can be left out of it. It also takes `bd-edit:ack` (each patch's `seq`, once the - app has it in the document) and `bd-edit:beacon` (a single-file save URL): - a tab closed before a patch was acknowledged posts every edit here to that - URL on the way out — cookie-free, so the sandbox still holds no session. + app has it in the document) and `bd-edit:port` (a MessagePort to the app's + exit worker, lib/editexit.worker.ts): a tab closed before a patch was + acknowledged posts every edited span down that port on the way out. This + frame never holds a URL or credential and makes no request of its own. Three things had to be true at once, and they decided the design: @@ -40,7 +41,7 @@ import { EditorView } from "@tiptap/pm/view"; import { keymap } from "@tiptap/pm/keymap"; import { baseKeymap, toggleMark } from "@tiptap/pm/commands"; import { history, undo, redo } from "@tiptap/pm/history"; -import { ackEditedSpan, beaconBody, type EditedSpan } from "./lib/editbeacon"; +import { ackEditedSpan, unackedExitPatches, type EditedSpan } from "./lib/editbeacon"; const SRC_ATTR = "data-bd-src"; @@ -190,12 +191,12 @@ let before = ""; /* Done's save is on the wire: no edit may start until the app says how it went (`bd-edit:unlock` if the editor stays; a page torn down otherwise). */ let locked = false; -/* The exit beacon (lib/editbeacon.ts): every patch is numbered, the app +/* The exit path (lib/editbeacon.ts): every patch is numbered, the app acknowledges each once it is in the document, and a page that goes with a - patch unacknowledged posts every span edited on this render to the URL the - app gave it. */ + patch unacknowledged hands every span edited on this render to the app's + exit worker, which saves it with the app's own session. */ let patchSeq = 0; -let beaconURL = ""; +let exitPort: MessagePort | null = null; const editedSpans = new Map(); // The document as markup, or null if there is no live editor. @@ -209,12 +210,18 @@ function flush() { if (html === null || html === before) return; before = html; const seq = ++patchSeq; - editedSpans.set(range.start + "," + range.end, { + const k = range.start + "," + range.end; + const prev = editedSpans.get(k); + const history = prev?.history ?? new Map(); + history.set(seq, html); + editedSpans.set(k, { start: range.start, end: range.end, html, seq, acked: false, + ackedHtml: prev?.ackedHtml, + history, }); send({ type: "bd-edit:patch", seq, start: range.start, end: range.end, html }); } @@ -414,27 +421,26 @@ send({ // the only observable difference between "rendered" and "editable". document.documentElement.setAttribute("data-bd-ready", ""); -/* Leaving with an edit the app never acknowledged: post it to the hub - ourselves, once per unload (marking it acknowledged), without cookies. A - keepalive body is capped by the browser; past that it goes as an ordinary - request that may still finish. */ -function beaconUnacked() { - const body = beaconBody({ url: beaconURL, hash, len, spans: editedSpans.values() }); - if (body === null) return; +/* Leaving with an edit the app never acknowledged: hand it to the exit + worker, once per unload (marking it acknowledged). The worker, not this + frame, decides whether and how it is saved. */ +function exitUnacked() { + if (!exitPort) return; + const patches = unackedExitPatches(editedSpans.values()); + if (patches === null) return; for (const s of editedSpans.values()) s.acked = true; - const keepalive = new TextEncoder().encode(body).byteLength <= 60_000; - void fetch(beaconURL, { method: "POST", mode: "no-cors", credentials: "omit", keepalive, body }).catch(() => {}); + exitPort.postMessage({ type: "bd-edit:exit", patches }); } window.addEventListener("beforeunload", () => { unmount(); - beaconUnacked(); + exitUnacked(); }); // Flush on pagehide too; keep the open element mounted when entering bfcache. window.addEventListener("pagehide", (e: PageTransitionEvent) => { if (e.persisted) flush(); else unmount(); - beaconUnacked(); + exitUnacked(); }); /* Done in the app: post what the open editor holds, then answer. The answer @@ -444,20 +450,16 @@ window.addEventListener("pagehide", (e: PageTransitionEvent) => { saved). Only the app (the parent window) may ask. */ window.addEventListener("message", (e) => { if (e.source !== window.parent) return; - const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown; url?: unknown } | null; + const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown } | null; if (!msg) return; if (msg.type === "bd-edit:ack" && typeof msg.seq === "number") { ackEditedSpan(editedSpans.values(), msg.seq); return; } - if (msg.type === "bd-edit:beacon" && typeof msg.url === "string" && msg.url.startsWith("/")) { - // The document's own URL has the hub's scheme and host even though this - // sandbox's origin is the opaque "null". - try { - beaconURL = new URL(msg.url, window.location.href).href; - } catch { - // an unusable URL: no beacon, as before - } + if (msg.type === "bd-edit:port" && e.ports[0]) { + exitPort?.close(); + exitPort = e.ports[0]; + document.documentElement.setAttribute("data-bd-exit", "ready"); return; } if (msg.type === "bd-edit:flush" && typeof msg.id === "number") { diff --git a/internal/webapp/frontend/src/lib/editbeacon.ts b/internal/webapp/frontend/src/lib/editbeacon.ts index 7d29982e..29482f0f 100644 --- a/internal/webapp/frontend/src/lib/editbeacon.ts +++ b/internal/webapp/frontend/src/lib/editbeacon.ts @@ -3,14 +3,23 @@ An edit reaches the app as a postMessage, and the app acknowledges each patch once it is in the document. A tab closed between the keystroke and that acknowledgement leaves an edit only the iframe holds — and the iframe - is sandboxed without allow-same-origin, so it has no session to save it - with. What it has instead is a single-file capability the app fetched for - it (POST ycollab/frame): on the way out it posts, cookie-free, the rendered - document's hash and every span it edited, and the hub splices them onto - that version and merges the result like any staging checkpoint (idempotent - if the app's own save also landed). + is sandboxed without allow-same-origin and runs the synced file's own + scripts, so it must never hold a session or any reusable write credential. - Pure, so it is tested without a DOM; inline-edit.ts owns the state. */ + So the save is made somewhere else: a dedicated worker the app starts on + its own origin (editexit.worker.ts), which outlives the closing tab long + enough to send one request with the app's own cookie. The iframe holds only + a MessagePort to it, and on the way out posts the spans it edited. The + worker trusts none of that: it splices them onto the render it was armed + with, only at ranges the app anchored, refuses script and sharp shrinks, + and merges the result against what the app last knew the file held. + + Pure, so it is tested without a DOM or a worker. */ + +import { conflictName } from "./conflict"; +import { hasCollabRoute } from "./collabroute"; +import { merge3ForPath } from "./merge3"; +import { byteLength, sharpShrink } from "./meeting"; export type EditedSpan = { start: number; @@ -18,34 +27,192 @@ export type EditedSpan = { html: string; seq: number; acked?: boolean; + ackedHtml?: string; + history?: Map; }; -/* Marks the span whose latest edit is `seq` acknowledged. A later edit to a - different span (higher `seq`) never acknowledges an earlier rejected span, - and an older ack arriving after a newer edit to the same span leaves the - newer edit unacknowledged until its own `seq` is confirmed. */ +/* Marks the span edit `seq` acknowledged, recording the HTML that `seq` + carried (`ackedHtml`) as the ancestor already present in the app's document. + A later edit to a different span never clears an earlier unapplied span, and + an older ack arriving after a newer edit to the same span advances `ackedHtml` + to what landed while keeping the newer edit unacknowledged. */ export function ackEditedSpan(spans: Iterable, seq: number): void { for (const s of spans) { - if (s.seq === seq) s.acked = true; + const h = s.history?.get(seq); + if (h !== undefined) { + s.ackedHtml = h; + if (s.seq === seq) s.acked = true; + } else if (s.seq === seq) { + s.ackedHtml = s.html; + s.acked = true; + } } } -/* The beacon's body, or null when nothing is owed: no capability yet, every - edited span acknowledged, no rendered version to splice onto, or nothing - edited. Every span edited on this render goes once any span is unacked: - the hub rebuilds the document from `src_hash`, so the patches spell the - full render state. */ -export function beaconBody(o: { - url: string; - hash: string; - len: number; - spans: Iterable; -}): string | null { - if (!o.url || !o.hash || o.len < 0) return null; - const all = [...o.spans]; +export type ExitPatch = { start: number; end: number; html: string; ackedHtml?: string }; + +/* What the frame posts on the way out, or null when nothing is owed (every + span acknowledged, or nothing edited). Every span edited on this render + goes once any is unacknowledged, carrying `ackedHtml` for spans the app + already applied so the worker merges from the acknowledged document rather + than re-merging an edit that already landed. */ +export function unackedExitPatches(spans: Iterable): ExitPatch[] | null { + const all = [...spans]; if (!all.some((s) => !s.acked)) return null; - const patches = all + return all .sort((a, b) => a.start - b.start) - .map(({ start, end, html }) => ({ start, end, html })); - return JSON.stringify({ src_hash: o.hash, src_len: o.len, patches }); + .map(({ start, end, html, ackedHtml }) => ({ + start, + end, + html, + ...(ackedHtml !== undefined ? { ackedHtml } : {}), + })); +} + +// What the worker was armed with, kept current by the app as it saves. +export type ExitWorkerState = { + apiBase: string; + path: string; + who?: string; + // The source the frame rendered, which every patch range indexes. + renderText: string; + renderLen: number; + // The ranges the app anchored ("start,end"): the only ones a patch may name. + allowedRanges: ReadonlySet; + // The version the file is known to hold, and its sha. + savedText: string; + baseSha?: string; + // The app's document as it stands (staging buffer or shared document). + docText: string; +}; + +// Far more than one render has elements; a body claiming more is not one. +const MAX_EXIT_PATCHES = 256; +// The hub's largest seed (maxSeedBytes): nothing bigger is spliced here. +const MAX_EXIT_BYTES = 1 << 20; +// Browsers cap the keepalive bodies in flight; past it, an ordinary request. +const KEEPALIVE_MAX_BYTES = 60_000; + +const inSurrogatePair = (s: string, i: number) => + i > 0 && + i < s.length && + s.charCodeAt(i) >= 0xdc00 && + s.charCodeAt(i) <= 0xdfff && + s.charCodeAt(i - 1) >= 0xd800 && + s.charCodeAt(i - 1) <= 0xdbff; + +/* The render with the frame's patches spliced in, or null if any patch is + not one the app could have received: a range it did not anchor, overlapping + or out of order, splitting a character, carrying a script or a NUL — the + frame runs the page's own scripts, so its word is checked, not taken. */ +export function applyRenderPatches( + renderText: string, + renderLen: number, + allowedRanges: ReadonlySet, + patches: ReadonlyArray, +): string | null { + if (renderText.length !== renderLen) return null; + if (patches.length < 1 || patches.length > MAX_EXIT_PATCHES) return null; + let want = ""; + let prev = 0; + for (const { start, end, html } of patches) { + if (!Number.isInteger(start) || !Number.isInteger(end)) return null; + if (start <= 0 || start > end || end >= renderLen || start < prev) return null; + if (!allowedRanges.has(start + "," + end)) return null; + if (inSurrogatePair(renderText, start) || inSurrogatePair(renderText, end)) return null; + if (typeof html !== "string" || html.includes("\0") || /<\s*script\b/i.test(html)) return null; + want += renderText.slice(prev, start) + html; + prev = end; + } + want += renderText.slice(prev); + return byteLength(want) < MAX_EXIT_BYTES ? want : null; +} + +export type ExitSaveRequest = { + url: string; + method: "POST" | "PUT"; + headers: Record; + body: string; + keepalive: boolean; +}; + +/* The one request the worker sends, or null when there is nothing to send + or nothing it may: patches it refuses, an unconfirmed sharp shrink, or a + result the file already holds. + + The frame's edits are on the RENDER; the file may have moved since (the + app's own autosaves, a co-editor). They are merged three ways onto what + the app last knew the document held. Merged: the result goes as an + ordinary save from `savedText`/`baseSha`. A same-word clash: the frame's + own document goes beside the file, as every conflict does. + + In a project (a room): a checkpoint asking the hub to park a clash itself. + In a plain folder (no room): a conditional PUT on the latest base — the + render's version is gone from a folder once an autosave replaced it, so + the base has to move with the saves — or, for a clash, a create-only + conflict copy. */ +export function buildExitSaveRequest( + state: ExitWorkerState, + patches: ReadonlyArray, +): ExitSaveRequest | null { + const renderedWant = applyRenderPatches(state.renderText, state.renderLen, state.allowedRanges, patches); + if (renderedWant === null) return null; + const ackedPatches = patches + .filter((p) => typeof p.ackedHtml === "string") + .map((p) => ({ start: p.start, end: p.end, html: p.ackedHtml as string })); + const ancestor = + ackedPatches.length > 0 + ? applyRenderPatches(state.renderText, state.renderLen, state.allowedRanges, ackedPatches) + : state.renderText; + if (ancestor === null) return null; + const latest = state.docText || state.savedText; + let mergedOk = true; + let want = renderedWant; + if (latest !== ancestor && latest !== renderedWant) { + const m = merge3ForPath(state.path, ancestor, latest, renderedWant); + if (m.ok) want = m.text; + else mergedOk = false; + } + if (state.savedText.length > 0 && sharpShrink(byteLength(state.savedText), byteLength(want))) return null; + if (mergedOk && want === state.savedText) return null; + + if (hasCollabRoute(state.apiBase)) { + const payload = mergedOk + ? { base: state.baseSha, base_text: state.savedText, text: want, park_on_conflict: true } + : { base_text: state.renderText, text: renderedWant, park_on_conflict: true }; + const body = JSON.stringify(payload); + return { + url: state.apiBase + "ycollab/sync?path=" + encodeURIComponent(state.path), + method: "POST", + headers: { "Content-Type": "application/json" }, + body, + keepalive: byteLength(body) <= KEEPALIVE_MAX_BYTES, + }; + } + + const text = "text/plain; charset=utf-8"; + if (mergedOk) { + const headers: Record = { + "Content-Type": text, + "X-Bdrive-Park-On-Conflict": "1", + }; + if (state.baseSha) headers["If-Match"] = `"${state.baseSha}"`; + return { + url: state.apiBase + "upload/content?path=" + encodeURIComponent(state.path), + method: "PUT", + headers, + body: want, + keepalive: byteLength(want) <= KEEPALIVE_MAX_BYTES, + }; + } + return { + url: + state.apiBase + + "upload/content?path=" + + encodeURIComponent(conflictName(state.path, state.who || "browser", new Date())), + method: "PUT", + headers: { "Content-Type": text, "If-None-Match": "*", "X-Bdrive-Park-On-Conflict": "1" }, + body: renderedWant, + keepalive: byteLength(renderedWant) <= KEEPALIVE_MAX_BYTES, + }; } diff --git a/internal/webapp/frontend/src/lib/editexit.worker.ts b/internal/webapp/frontend/src/lib/editexit.worker.ts new file mode 100644 index 00000000..9a212075 --- /dev/null +++ b/internal/webapp/frontend/src/lib/editexit.worker.ts @@ -0,0 +1,94 @@ +/* The visual editor's exit save, in a dedicated worker on the app's origin. + + A tab closed before the editing iframe's last patch reached the app leaves + that edit only in the iframe — which runs the synced file's own scripts, + so it is never given a session or any credential (lib/editbeacon.ts). This + worker is started by VisualEdit on the app's origin, outlives the closing + tab long enough for one request, and sends it with the app's own cookie. + The iframe holds nothing but a MessagePort to it. + + Messages from the app: + arm — the render, its anchored ranges, what the file holds; the + transferred port is the iframe's end of the channel + sync — what the file holds / the document now, as the app saves + disarm — the editor reloaded or closed normally: nothing more to do + From the iframe (the port), once: bd-edit:exit with every edited span. */ + +import { buildExitSaveRequest, type ExitPatch, type ExitWorkerState } from "./editbeacon"; + +type Arm = { + type: "arm"; + apiBase: string; + path: string; + who?: string; + renderText: string; + renderLen: number; + allowedRanges: string[]; + savedText: string; + baseSha?: string; + docText: string; +}; +type Sync = { type: "sync"; savedText?: string; baseSha?: string; hasBaseSha?: boolean; docText?: string }; +type FromApp = Arm | Sync | { type: "disarm" }; + +let state: ExitWorkerState | null = null; +let childPort: MessagePort | null = null; +let disarmed = false; +let exited = false; + +const onExit = (ev: MessageEvent) => { + const msg = ev.data as { type?: unknown; patches?: unknown } | null; + if (!msg || msg.type !== "bd-edit:exit" || !Array.isArray(msg.patches)) return; + if (disarmed || exited || !state) return; + exited = true; + childPort?.close(); + childPort = null; + // Shapes are checked spliced (applyRenderPatches): a bad one sends nothing. + const req = buildExitSaveRequest(state, msg.patches as ExitPatch[]); + if (!req) return; + void fetch(req.url, { + method: req.method, + credentials: "same-origin", + headers: req.headers, + body: req.body, + keepalive: req.keepalive, + }).catch(() => {}); +}; + +self.onmessage = (ev: MessageEvent) => { + const msg = ev.data as FromApp | null; + if (!msg || typeof msg !== "object" || disarmed) return; + if (msg.type === "arm") { + state = { + apiBase: msg.apiBase, + path: msg.path, + who: msg.who, + renderText: msg.renderText, + renderLen: msg.renderLen, + allowedRanges: new Set(msg.allowedRanges), + savedText: msg.savedText, + baseSha: msg.baseSha, + docText: msg.docText, + }; + // A re-arm (a new render) replaces the iframe's channel; nothing sent yet. + childPort?.close(); + childPort = ev.ports[0] ?? null; + exited = false; + if (childPort) childPort.onmessage = onExit; + return; + } + if (msg.type === "sync") { + if (!state) return; + if (typeof msg.savedText === "string") state.savedText = msg.savedText; + if (msg.hasBaseSha) state.baseSha = msg.baseSha; + if (typeof msg.docText === "string") state.docText = msg.docText; + return; + } + if (msg.type === "disarm") { + disarmed = true; + state = null; + childPort?.close(); + childPort = null; + self.close(); + } +}; diff --git a/internal/webapp/frontend/src/lib/sharedfile.ts b/internal/webapp/frontend/src/lib/sharedfile.ts index 1bb988a5..90ef3eee 100644 --- a/internal/webapp/frontend/src/lib/sharedfile.ts +++ b/internal/webapp/frontend/src/lib/sharedfile.ts @@ -172,6 +172,10 @@ export type SharedFileOptions = { iframe) brings them all in and stops taking more before the join reads the buffer; the join calls the returned release once it is done. */ beforeJoin?: () => Promise<() => void>; + /** The file's known version moved (every adopt and rebase): the text it + holds and the sha to build the next save on. VisualEdit keeps its exit + worker on it, so a save from a closing tab is built on the latest. */ + onBaseChange?: (savedText: string, baseSha?: string) => void; }; /* Three ways to be connected, and what writes the file in each: @@ -585,6 +589,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { } else { saved = landed.sent; savedSha = undefined; + opts.onBaseChange?.(saved, base); } } }; @@ -1199,6 +1204,7 @@ export function openSharedFile(opts: SharedFileOptions): SharedFile { so our next save is not refused for a conflict that does not exist. */ const rebase = (sha?: string) => { if (sha) base = sha; + opts.onBaseChange?.(saved, base); }; const merge = (next: string, nextSha?: string, how?: { held?: boolean }): MergeResult => { diff --git a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts index c028b351..c75f3513 100644 --- a/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts +++ b/internal/webapp/frontend/src/lib/sharedfile_restore.test.ts @@ -56,7 +56,7 @@ const { openSharedFile, SAVE_RETRY_MS } = await import("./sharedfile.ts"); const { parseConflict } = await import("./conflict.ts"); const { merge3, merge3PreferRight, merge3ForPath, validMergedText } = await import("./merge3.ts"); const { frameChannel, saveLocked } = await import("./frameflush.ts"); -const { ackEditedSpan, beaconBody } = await import("./editbeacon.ts"); +const { ackEditedSpan, unackedExitPatches, applyRenderPatches, buildExitSaveRequest } = await import("./editbeacon.ts"); /* toEqual's semantics: a property that is undefined is a property that is absent. Only plain objects and arrays are rebuilt; anything else (a @@ -2847,44 +2847,120 @@ test("frameChannel keeps arrival order behind an async handler, then handles at channel.close(); }); -/* The frame's exit beacon goes only when a patch is still unacknowledged, - and then carries every span edited on the render, in source order, over - the rendered version's hash — enough for the hub to rebuild the whole - document. Acknowledged, or nothing to splice onto: nothing is sent. */ -test("beaconBody: per-span ack keeps an unapplied earlier span owed even after a later span is acked", () => { +/* The frame hands its edits to the exit worker only while a patch is still + unacknowledged, and then hands every span edited on the render, in source + order, so the worker can rebuild the whole document from the render. */ +test("unackedExitPatches: per-span acks, gaps and re-edits", () => { const spans: EditedSpan[] = [ { start: 40, end: 52, html: "Second", seq: 2, acked: false }, { start: 10, end: 20, html: "First", seq: 1, acked: false }, ]; - const base = { url: "https://hub/api/p/x/ycollab/frame/tok", hash: "h", len: 100, spans }; - - // Patch 1 was not applied (no ack 1), while patch 2 on another span succeeded (ack 2): - // patch 1 is still unacknowledged, so unload still sends the beacon! + // Patch 1 was not applied (no ack 1) while patch 2 was: 1 is still owed. ackEditedSpan(spans, 2); - same(JSON.parse(beaconBody(base) ?? "null"), { - src_hash: "h", - src_len: 100, - patches: [ - { start: 10, end: 20, html: "First" }, - { start: 40, end: 52, html: "Second" }, - ], - }); - - // Once patch 1 is also acknowledged, nothing is owed. + same(unackedExitPatches(spans), [ + { start: 10, end: 20, html: "First" }, + { start: 40, end: 52, html: "Second", ackedHtml: "Second" }, + ]); ackEditedSpan(spans, 1); - assert.equal(beaconBody(base), null); + assert.equal(unackedExitPatches(spans), null); - // Re-editing span 1 (seq 3) resets acked=false; a stale ack(1) does not clear seq 3. + // A re-edit (seq 3) is owed until its own ack: a stale ack(1) clears nothing. spans[1] = { start: 10, end: 20, html: "First again", seq: 3, acked: false }; ackEditedSpan(spans, 1); - assert.notEqual(beaconBody(base), null); + assert.notEqual(unackedExitPatches(spans), null); ackEditedSpan(spans, 3); - assert.equal(beaconBody(base), null); - - // Missing capability, hash, length, or spans -> null even when unacked. - spans[1].acked = false; - assert.equal(beaconBody({ ...base, url: "" }), null); - assert.equal(beaconBody({ ...base, hash: "" }), null); - assert.equal(beaconBody({ ...base, len: -1 }), null); - assert.equal(beaconBody({ ...base, spans: [] }), null); + assert.equal(unackedExitPatches(spans), null); + assert.equal(unackedExitPatches([]), null); +}); + +/* The exit worker's one request. The frame's spans are spliced onto the + render (only at ranges the app anchored, never a script), merged onto what + the file holds now, and sent the way the mode saves: a room checkpoint on + a hub, a conditional PUT on the LATEST base in a plain folder — where the + render's version is gone once an autosave replaced it. */ +test("buildExitSaveRequest: hub checkpoint, plain-folder save after an autosave, and refusals", () => { + const v0 = '\n

Title

\n

Lead.

\n'; + const h1 = { start: v0.indexOf("Title"), end: v0.indexOf("Title") + "Title".length }; + const lead = { start: v0.indexOf("Lead."), end: v0.indexOf("Lead.") + "Lead.".length }; + const allowedRanges = new Set([h1.start + "," + h1.end, lead.start + "," + lead.end]); + const edit1 = { ...lead, html: "Lead. First autosaved." }; + const edit2 = { ...h1, html: "Title Second across close." }; + const v1 = v0.replace("Lead.", edit1.html); + const v2 = v1.replace("Title", edit2.html); + const state = { + apiBase: "/api/", + path: "page.html", + who: "tester", + renderText: v0, + renderLen: v0.length, + allowedRanges, + savedText: v0, + baseSha: "sha-0", + docText: v0, + }; + + // 1) A hub: a checkpoint into the room, asking the hub to park a clash. + const hub = buildExitSaveRequest({ ...state, apiBase: "/api/p/p-1/" }, [edit1]); + assert.ok(hub); + assert.equal(hub.method, "POST"); + assert.equal(hub.url, "/api/p/p-1/ycollab/sync?path=page.html"); + same(JSON.parse(hub.body), { base: "sha-0", base_text: v0, text: v1, park_on_conflict: true }); + assert.equal(hub.keepalive, true); + + // 2) A plain folder after autosave #1: the file holds v1 under a new ETag, + // edit1 was acknowledged (ackedHtml set), and edit2 was never delivered. + // Built from the acknowledged ancestor v1 and PUT on the latest base: + // both edits land with no duplicate insertion — including a follow-up + // unacked edit to the SAME paragraph that autosaved! + const dir = buildExitSaveRequest( + { ...state, savedText: v1, baseSha: "dir-2000-110", docText: v1 }, + [edit2, { ...edit1, ackedHtml: edit1.html }], + ); + assert.ok(dir); + assert.equal(dir.method, "PUT"); + assert.equal(dir.url, "/api/upload/content?path=page.html"); + same(dir.headers, { + "Content-Type": "text/plain; charset=utf-8", + "X-Bdrive-Park-On-Conflict": "1", + "If-Match": '"dir-2000-110"', + }); + assert.equal(dir.body, v2); + + const sameParaFollowUp = buildExitSaveRequest( + { ...state, savedText: v1, baseSha: "dir-2000-110", docText: v1 }, + [{ ...lead, html: "Lead. First autosaved. More words.", ackedHtml: edit1.html }], + ); + assert.ok(sameParaFollowUp); + assert.equal(sameParaFollowUp.body, v0.replace("Lead.", "Lead. First autosaved. More words.")); + // The same words changed outside: the frame's document goes beside the file. + const outside = v0.replace("Title", "Other"); + const mine = { ...h1, html: "Mine" }; + const clash = buildExitSaveRequest({ ...state, savedText: outside, docText: outside }, [mine]); + assert.ok(clash); + assert.ok(clash.url.startsWith("/api/upload/content?path=page.html.bdrive-conflict-tester-")); + assert.equal(clash.headers["If-None-Match"], "*"); + assert.equal(clash.body, v0.replace("Title", "Mine")); + + // Nothing new: nothing sent. + assert.equal(buildExitSaveRequest({ ...state, savedText: v1, docText: v1 }, [edit1]), null); + + // 3) Refusals: a range the app never anchored, a script, an unconfirmed shrink. + assert.equal(applyRenderPatches(v0, v0.length, allowedRanges, [{ start: 1, end: 5, html: "x" }]), null); + assert.equal(buildExitSaveRequest(state, [{ start: 1, end: 5, html: "x" }]), null); + assert.equal(buildExitSaveRequest(state, [{ ...h1, html: "" }]), null); + assert.equal(buildExitSaveRequest(state, [{ ...h1, html: "< SCRIPT src=x>" }]), null); + assert.equal(buildExitSaveRequest(state, [{ ...h1, html: "a\0b" }]), null); + assert.equal(buildExitSaveRequest(state, [edit2, edit2]), null); // overlapping + assert.equal(buildExitSaveRequest({ ...state, renderLen: v0.length + 1 }, [edit2]), null); + const big = "\n

" + "word ".repeat(1000) + "

\n"; + const para = { start: big.indexOf("word"), end: big.lastIndexOf("

") }; + const bigState = { + ...state, + renderText: big, + renderLen: big.length, + allowedRanges: new Set([para.start + "," + para.end]), + savedText: big, + docText: big, + }; + assert.equal(buildExitSaveRequest(bigState, [{ ...para, html: "x" }]), null); }); diff --git a/internal/webapp/server.go b/internal/webapp/server.go index c2239211..34e3d242 100644 --- a/internal/webapp/server.go +++ b/internal/webapp/server.go @@ -1706,10 +1706,6 @@ func (s *Server) Handler() http.Handler { // A client's state merged into the live room over plain HTTP (no // socket, or a shrink to confirm). It writes, so it needs write. mux.HandleFunc("POST "+prefix+"ycollab/sync", resolve(PermWrite, s.handleYCollabSync)) - // A framed HTML page's edit beacon (frame.go): minted with the - // session, flushed by the cookieless page as it unloads. - mux.HandleFunc("POST "+prefix+"ycollab/frame", resolve(PermWrite, s.handleEditFrame)) - mux.HandleFunc("POST "+prefix+"ycollab/frame/{token}", resolve(PermWrite, s.handleEditFrameFlush)) mux.HandleFunc("POST "+prefix+"upload/init", resolve(PermWrite, s.handleUploadInit)) mux.HandleFunc("PUT "+prefix+"upload/content", resolve(PermWrite, s.handleUploadContent)) mux.HandleFunc("POST "+prefix+"upload/commit", resolve(PermWrite, s.handleUploadCommit)) diff --git a/internal/webapp/static/assets/Editor-yrlJG67f.js b/internal/webapp/static/assets/Editor-CsLWwTRs.js similarity index 99% rename from internal/webapp/static/assets/Editor-yrlJG67f.js rename to internal/webapp/static/assets/Editor-CsLWwTRs.js index dad69fcf..38e04058 100644 --- a/internal/webapp/static/assets/Editor-yrlJG67f.js +++ b/internal/webapp/static/assets/Editor-CsLWwTRs.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,c as Vh,d as CO,r as oe,e as ZO,f as XO,g as AO,h as RO,j as wn,t as wl,w as MO,a as jO}from"./index-IQjI59Ja.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CQlHsuJ4.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DyFnf9EY.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CtVUr4nt.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js b/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js new file mode 100644 index 00000000..42847f13 --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js @@ -0,0 +1 @@ +import{r as u,j as E,w as Ce,a as Fe}from"./index-DyFnf9EY.js";import{o as Ne,D as qe,c as L,a as V,m as ge,d as we}from"./sharedfile-CtVUr4nt.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Ae=50,De=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function Ie(){let o=null;const l=new Map;let d=0,x=!1;const M=()=>o?o.then(()=>{}):Promise.resolve(),P=c=>{const f=c.catch(()=>{}).finally(()=>{o===f&&(o=null)});o=f};return{enqueue(c){if(o){P(o.then(c));return}try{const f=c();De(f)&&P(Promise.resolve(f))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,f,_=!1){if(await M(),x||f())return;const h=++d;let j;const G=new Promise(C=>{l.set(h,C),j=setInterval(()=>{!x&&!f()||(l.delete(h),C())},Ae)});try{c(_?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await G}finally{clearInterval(j)}await M()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function _e(o,l,d){let x=!1;try{return await o(),x=await l(),x}finally{x||d()}}async function Ge(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(d=>d.toString(16).padStart(2,"0")).join("")}catch{return null}}function Xe({apiBase:o,fileURL:l,path:d,initial:x,me:M,onStateChange:P,onCollab:c,onPeers:f,onConflictCopy:_,baseSha:h,onSaved:j,onWriting:G,onRendered:C,handle:H}){const b=u.useRef(null),[te,be]=u.useState(null),[ve,ne]=u.useState(!1),[Te,re]=u.useState(!1),oe=u.useRef(0),[se,Se]=u.useState(0),y=u.useRef({onStateChange:P,onCollab:c,onPeers:f,onSaved:j,onWriting:G,onRendered:C,onConflictCopy:_});y.current={onStateChange:P,onCollab:c,onPeers:f,onSaved:j,onWriting:G,onRendered:C,onConflictCopy:_};const F=u.useRef(x),O=u.useRef(M);O.current=M;const X=u.useRef(h);X.current=h;const Y=u.useRef(null);return u.useEffect(()=>{Y.current?.rebase(h)},[h]),u.useEffect(()=>{let S=null,N=!1,r=null,v;const ke=700;ne(!1),re(!1);const Re=setTimeout(()=>{!T&&oe.current<1&&(oe.current++,k())},11e3),We=setTimeout(()=>re(!0),24e3),B=Ie();let z=!1,m=null;try{m=typeof Worker<"u"?new Worker(new URL("/assets/editexit.worker-CfTN8vfX.js",import.meta.url),{type:"module"}):null}catch{m=null}let J=!1,K=F.current,Q=X.current;const Ee=()=>r?r.getText("body").toString():Y.current?.collab.text.toString()??"",U=()=>{!m||J||m.postMessage({type:"sync",savedText:K,baseSha:Q,hasBaseSha:!0,docText:Ee()})},ae=()=>{!m||J||(J=!0,m.postMessage({type:"disarm"}),m.terminate())},k=()=>{ae(),Se(e=>e+1)},Le=e=>{const t=b.current?.contentWindow;if(!m||J||!t)return;const s=new MessageChannel;m.postMessage({type:"arm",apiBase:o,path:d,who:O.current?.name,renderText:e,renderLen:e.length,allowedRanges:[...g.keys()],savedText:K,baseSha:Q,docText:e},[s.port1]),t.postMessage({type:"bd-edit:port"},"*",[s.port2])},ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},Me=async e=>{const t=b.current,s=t?.contentWindow;if(!t||!s)return;let a=!1;const n=()=>{a=!0};t.addEventListener("load",n);try{await B.drain(w=>s.postMessage(w,"*"),()=>!z||a||b.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(v),v=void 0},q=new Map,ce=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};q.set(e,(q.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const a=(q.get(e)??1)-1;if(a>0){q.set(e,a);return}q.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await Me(!0)}catch(a){throw s(),a}return s},i=Y.current=Ne({apiBase:o,path:d,seed:F.current,baseSha:X.current,who:O.current?.name,me:O.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>Fe(d,e),onShrinkWithdrawn:Ce,beforeJoin:async()=>r?ce():()=>{},onReady:()=>{if(clearTimeout(v),v=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(T&&t===s)for(const[a,n]of g){const w=L(n.from,e),A=L(n.to,e);w&&A&&g.set(a,{from:V(i.collab.text,w.index),to:V(i.collab.text,A.index),span:n.span,orig:n.orig})}else g.clear(),T=!1,t!==s&&k();e.destroy()}N=!0,R()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,F.current),N=!0,R()},onStalled:()=>{N||r||(r=new qe,r.getText("body").insert(0,F.current),N=!0,R())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),onBaseChange:(e,t)=>{K=e,Q=t,U()},soloText:()=>r?r.getText("body").toString():F.current,soloApply:({from:e,to:t,insert:s})=>{r&&r.transact(()=>{const a=r.getText("body");t>e&&a.delete(e,t-e),s&&a.insert(e,s)})}});let le=null;const ue={...i,saveNow:()=>{let e=()=>{};return le??=_e(async()=>{e=await ce()},()=>i.saveNow(),()=>e()).finally(()=>{le=null})}};H&&(H.current=ue);const g=new Map,de=e=>e.start+","+e.end,R=async()=>{if(T||!S||!N)return;const e=r?r.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(S.some(n=>n.end>t.length||n.start>n.end)){S=null,k();return}const s=await Ge(t);if(s!==null?s!==fe:Z>=0&&t.length!==Z){S=null,k();return}g.clear();for(const n of S)g.set(de(n),{from:V(e,n.start),to:V(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Le(t),ne(!0),y.current.onRendered?.()};let fe="",Z=-1,T=!1;const Pe=e=>{if(e.type==="bd-edit:flushed"){B.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){be("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return S=e.ranges,fe=e.hash,Z=e.len,z=!0,R();if(e.type==="bd-edit:patch"){if(!T)return R().then(()=>{pe(e)&&(ie(e),U())});pe(e)&&(ie(e),U())}},pe=e=>{const t=g.get(de(e));if(!t)return!1;if(r){const p=L(t.from,r),D=L(t.to,r);if(!p||!D||p.index>D.index)return!1;const I=r.getText("body"),je=D.index-p.index;if(p.index===0&&D.index===I.length&&t.spant.span*4+256)return g.clear(),T=!1,k(),!1;const ee=I.toString().slice(p.index,D.index),me=ge(t.orig,ee,e.html);return t.orig=e.html,ee===me||(r.transact(()=>{for(const W of we(ee,me))W.deleteCount>0&&I.delete(p.index+W.index,W.deleteCount),W.insertText&&I.insert(p.index+W.index,W.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(v),v=setTimeout(()=>{i.saveNow()},ke)),!0}const s=i.collab.doc,a=L(t.from,s),n=L(t.to,s);if(!a||!n||a.index>n.index)return!1;const w=i.collab.text,A=n.index-a.index;if(a.index===0&&n.index===w.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:A,stamped:t.span,docLength:w.length}),g.clear(),T=!1,k(),!1;const $=w.toString().slice(a.index,n.index),ye=ge(t.orig,$,e.html);return t.orig=e.html,$===ye||i.collab.applySplices(we($,ye).map(p=>({...p,index:p.index+a.index}))),!0},xe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||B.enqueue(()=>Pe(t))},he=()=>{U(),R()};return i.collab.text.observe(he),window.addEventListener("message",xe),()=>{H?.current===ue&&(H.current=null),z=!1,B.close(),clearTimeout(Re),clearTimeout(We),clearTimeout(v),i.collab.text.unobserve(he),setTimeout(()=>{window.removeEventListener("message",xe),clearTimeout(v),i.destroy(),ae(),r?.destroy()},300)}},[o,d,se]),E.jsxs(E.Fragment,{children:[te&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:te}),Te&&!ve&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:d},se)]})}export{Xe as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-CnYT3nlY.js b/internal/webapp/static/assets/VisualEdit-CnYT3nlY.js deleted file mode 100644 index 3c9dad1d..00000000 --- a/internal/webapp/static/assets/VisualEdit-CnYT3nlY.js +++ /dev/null @@ -1 +0,0 @@ -import{r as u,j as E,p as Pe,w as Me,a as We}from"./index-IQjI59Ja.js";import{o as je,D as Ce,c as L,a as J,m as me,d as be}from"./sharedfile-CQlHsuJ4.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Fe=50,Ne=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function qe(){let o=null;const l=new Map;let f=0,x=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),M=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){M(o.then(c));return}try{const p=c();Ne(p)&&M(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,D=!1){if(await P(),x||p())return;const h=++f;let W;const I=new Promise(j=>{l.set(h,j),W=setInterval(()=>{!x&&!p()||(l.delete(h),j())},Fe)});try{c(D?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await I}finally{clearInterval(W)}await P()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function Ae(o,l,f){let x=!1;try{return await o(),x=await l(),x}finally{x||f()}}async function De(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Ue({apiBase:o,fileURL:l,path:f,initial:x,me:P,onStateChange:M,onCollab:c,onPeers:p,onConflictCopy:D,baseSha:h,onSaved:W,onWriting:I,onRendered:j,handle:_}){const b=u.useRef(null),[K,ge]=u.useState(null),[we,Q]=u.useState(!1),[Te,X]=u.useState(!1),Z=u.useRef(0),[$,S]=u.useState(0),y=u.useRef({onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D});y.current={onStateChange:M,onCollab:c,onPeers:p,onSaved:W,onWriting:I,onRendered:j,onConflictCopy:D};const G=u.useRef(x),U=u.useRef(P);U.current=P;const ee=u.useRef(h);ee.current=h;const te=u.useRef(null);return u.useEffect(()=>{te.current?.rebase(h)},[h]),u.useEffect(()=>{let R=null,C=!1,s=null,g;const ve=700;Q(!1),X(!1);const Se=setTimeout(()=>{!T&&Z.current<1&&(Z.current++,S(e=>e+1))},11e3),Re=setTimeout(()=>X(!0),24e3),H=qe();let O=!1,V="",ne,re=!1;const oe=()=>{V&&O&&b.current?.contentWindow?.postMessage({type:"bd-edit:beacon",url:V},"*")},se=()=>{Pe(o+"ycollab/frame?path="+encodeURIComponent(f),{}).then(e=>{if(re||typeof e?.url!="string"||(V=e.url,oe(),typeof e.expires!="number"))return;const t=e.expires>1e12?e.expires-Date.now():e.expires;ne=setTimeout(se,Math.max(3e4,t-6e4))}).catch(()=>{})};se();const ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},ke=async e=>{const t=b.current,i=t?.contentWindow;if(!t||!i)return;let r=!1;const n=()=>{r=!0};t.addEventListener("load",n);try{await H.drain(m=>i.postMessage(m,"*"),()=>!O||r||b.current!==t||t.contentWindow!==i,e)}finally{t.removeEventListener("load",n)}clearTimeout(g),g=void 0},F=new Map,ae=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};F.set(e,(F.get(e)??0)+1);let t=!1;const i=()=>{if(t)return;t=!0;const r=(F.get(e)??1)-1;if(r>0){F.set(e,r);return}F.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await ke(!0)}catch(r){throw i(),r}return i},a=te.current=je({apiBase:o,path:f,seed:G.current,baseSha:ee.current,who:U.current?.name,me:U.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>We(f,e),onShrinkWithdrawn:Me,beforeJoin:async()=>s?ae():()=>{},onReady:()=>{if(clearTimeout(g),g=void 0,s){const e=s;s=null;const t=e.getText("body").toString(),i=a.collab.text.toString();if(T&&t===i)for(const[r,n]of w){const m=L(n.from,e),N=L(n.to,e);m&&N&&w.set(r,{from:J(a.collab.text,m.index),to:J(a.collab.text,N.index),span:n.span,orig:n.orig})}else w.clear(),T=!1,t!==i&&S(r=>r+1);e.destroy()}C=!0,k()},onSolo:()=>{a.collab.text.length||a.collab.text.insert(0,G.current),C=!0,k()},onStalled:()=>{C||s||(s=new Ce,s.getText("body").insert(0,G.current),C=!0,k())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),soloText:()=>s?s.getText("body").toString():G.current,soloApply:({from:e,to:t,insert:i})=>{s&&s.transact(()=>{const r=s.getText("body");t>e&&r.delete(e,t-e),i&&r.insert(e,i)})}});let ce=null;const le={...a,saveNow:()=>{let e=()=>{};return ce??=Ae(async()=>{e=await ae()},()=>a.saveNow(),()=>e()).finally(()=>{ce=null})}};_&&(_.current=le);const w=new Map,ue=e=>e.start+","+e.end,k=async()=>{if(T||!R||!C)return;const e=s?s.getText("body"):a.collab.text,t=e.toString();if(!t)return;if(R.some(n=>n.end>t.length||n.start>n.end)){R=null,S(n=>n+1);return}const i=await De(t);if(i!==null?i!==de:Y>=0&&t.length!==Y){R=null,S(n=>n+1);return}w.clear();for(const n of R)w.set(ue(n),{from:J(e,n.start),to:J(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Q(!0),y.current.onRendered?.()};let de="",Y=-1,T=!1;const Ee=e=>{if(e.type==="bd-edit:flushed"){H.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){ge("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return R=e.ranges,de=e.hash,Y=e.len,O=!0,oe(),k();if(e.type==="bd-edit:patch"){if(!T)return k().then(()=>{fe(e)&&ie(e)});fe(e)&&ie(e)}},fe=e=>{const t=w.get(ue(e));if(!t)return!1;if(s){const d=L(t.from,s),q=L(t.to,s);if(!d||!q||d.index>q.index)return!1;const A=s.getText("body"),Le=q.index-d.index;if(d.index===0&&q.index===A.length&&t.spant.span*4+256)return w.clear(),T=!1,S(v=>v+1),!1;const B=A.toString().slice(d.index,q.index),ye=me(t.orig,B,e.html);return t.orig=e.html,B===ye||(s.transact(()=>{for(const v of be(B,ye))v.deleteCount>0&&A.delete(d.index+v.index,v.deleteCount),v.insertText&&A.insert(d.index+v.index,v.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(g),g=setTimeout(()=>{a.saveNow()},ve)),!0}const i=a.collab.doc,r=L(t.from,i),n=L(t.to,i);if(!r||!n||r.index>n.index)return!1;const m=a.collab.text,N=n.index-r.index;if(r.index===0&&n.index===m.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:N,stamped:t.span,docLength:m.length}),w.clear(),T=!1,S(d=>d+1),!1;const z=m.toString().slice(r.index,n.index),he=me(t.orig,z,e.html);return t.orig=e.html,z===he||a.collab.applySplices(be(z,he).map(d=>({...d,index:d.index+r.index}))),!0},pe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||H.enqueue(()=>Ee(t))},xe=()=>{k()};return a.collab.text.observe(xe),window.addEventListener("message",pe),()=>{_?.current===le&&(_.current=null),O=!1,H.close(),re=!0,clearTimeout(ne),clearTimeout(Se),clearTimeout(Re),clearTimeout(g),a.collab.text.unobserve(xe),setTimeout(()=>{window.removeEventListener("message",pe),clearTimeout(g),a.destroy(),s?.destroy()},300)}},[o,f,$]),E.jsxs(E.Fragment,{children:[K&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:K}),Te&&!we&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},$)]})}export{Ue as VisualEdit}; diff --git a/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js b/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js new file mode 100644 index 00000000..27eef186 --- /dev/null +++ b/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js @@ -0,0 +1,11 @@ +(function(){"use strict";function H(e,t,n){const r=h=>String(h).padStart(2,"0"),s=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+s,i=e.lastIndexOf("/"),d=i<0?"":e.slice(0,i+1),x=i<0?e:e.slice(i+1);return d+x.slice(0,Math.max(0,255-l.length))+l}function K(e){return/\/p\/[^/]+\/$/.test(e)}const z=4e3;function U(e,t){let n=0;for(;n0?h[o-1]:null,p=new Int32Array(2*o+1);for(let f=-o;f<=o;f+=2){let a;o===0?a=0:f===-o||f!==o&&c[f-1+o-1]=s&&g>=l){T=o;break}}h.push(p)}if(T<0)return[{aS:n,aE:n+s,bS:n,bE:n+l}];const y=[];let b=s,S=l;for(let o=T;o>0;o--){const c=h[o-1],p=b-S,f=p===-o||p!==o&&c[p-1+o-1]m&&S>L;)b--,S--,y.push(b,S);b=a,S=g}for(;b>0&&S>0;)b--,S--,y.push(b,S);const C=[];let E=0,u=0;for(let o=y.length-2;o>=0;o-=2){const c=y[o],p=y[o+1];(c>E||p>u)&&C.push({aS:n+E,aE:n+c,bS:n+u,bE:n+p}),E=c+1,u=p+1}return(El.startsWith(i)&&(i===""||i.endsWith(` +`)||l[i.length]===` +`);return e.length>=t.length&&s(e,t)?e:t.length>e.length&&s(t,e)?t:null}return n?Y(e,t)<=0?e+t:t+e:null}function M(e,t,n,r,s=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const l=new Map,i=v(e,r),d=v(t,r),x=v(n,r),h=w(i,l),T=[...U(h,w(d,l)).map(u=>({h:u,toks:d,side:0})),...U(h,w(x,l)).map(u=>({h:u,toks:x,side:1}))];T.sort((u,o)=>u.h.aS-o.h.aS||u.h.aE-o.h.aE||u.side-o.side);const y=(u,o,c)=>u.slice(o,c).join(""),b=(u,o,c,p)=>{let f="",a=c;for(const g of u)g.side===o&&(f+=y(i,a,g.h.aS)+y(g.toks,g.h.bS,g.h.bE),a=g.h.aE);return f+y(i,a,p)};let S="",C=0,E=0;for(;Em.side)).size===1){S+=b(u,u[0].side,o,c);continue}const f=b(u,0,o,c),a=b(u,1,o,c);if(f===a){S+=f;continue}if(o===c){const m=$(f,a,r!==_,i.length===0);if(m===null){if(!s)return null;S+=a;continue}S+=m;continue}if(r===_)return null;const g=r===W?M(y(i,o,c),f,a,_):M(y(i,o,c),f,a,r+1,s);if(g===null){if(!s)return null;S+=a;continue}S+=g}return S+y(i,C,i.length)}const R=e=>e===""||e.endsWith(` +`)?e:e+` +`;function q(e,t,n,r){let s=t.endsWith(` +`);return s===e.endsWith(` +`)&&(s=n.endsWith(` +`)),r===""||s===r.endsWith(` +`)?r:s?r+` +`:r.slice(0,-1)}function J(e,t,n){const r=M(R(e),R(t),R(n),B);return r===null?{ok:!1}:{ok:!0,text:q(e,t,n,r)}}function Z(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),r=n.lastIndexOf("."),s=r>=0?n.slice(r).toLowerCase():"",l=i=>{try{return JSON.parse(i),!0}catch{return!1}};if(s===".json")return l(t);if(s===".jsonl")for(const i of t.split(` +`)){const d=i.trim();if(d.length>0&&!l(d))return!1}return!0}function V(e,t,n,r){const s=J(t,n,r);return!s.ok||n===r||n===t||r===t||Z(e,s.text)?s:{ok:!1}}const G=256;function Q(e,t){return e<=0||t>=e?!1:t===0?!0:e>=G&&t*5new TextEncoder().encode(e).length,ee=256,te=1<<20,O=6e4,X=(e,t)=>t>0&&t=56320&&e.charCodeAt(t)<=57343&&e.charCodeAt(t-1)>=55296&&e.charCodeAt(t-1)<=56319;function j(e,t,n,r){if(e.length!==t||r.length<1||r.length>ee)return null;let s="",l=0;for(const{start:i,end:d,html:x}of r){if(!Number.isInteger(i)||!Number.isInteger(d)||i<=0||i>d||d>=t||itypeof h.ackedHtml=="string").map(h=>({start:h.start,end:h.end,html:h.ackedHtml})),s=r.length>0?j(e.renderText,e.renderLen,e.allowedRanges,r):e.renderText;if(s===null)return null;const l=e.docText||e.savedText;let i=!0,d=n;if(l!==s&&l!==n){const h=V(e.path,s,l,n);h.ok?d=h.text:i=!1}if(e.savedText.length>0&&Q(I(e.savedText),I(d))||i&&d===e.savedText)return null;if(K(e.apiBase)){const h=i?{base:e.baseSha,base_text:e.savedText,text:d,park_on_conflict:!0}:{base_text:e.renderText,text:n,park_on_conflict:!0},T=JSON.stringify(h);return{url:e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path),method:"POST",headers:{"Content-Type":"application/json"},body:T,keepalive:I(T)<=O}}const x="text/plain; charset=utf-8";if(i){const h={"Content-Type":x,"X-Bdrive-Park-On-Conflict":"1"};return e.baseSha&&(h["If-Match"]=`"${e.baseSha}"`),{url:e.apiBase+"upload/content?path="+encodeURIComponent(e.path),method:"PUT",headers:h,body:d,keepalive:I(d)<=O}}return{url:e.apiBase+"upload/content?path="+encodeURIComponent(H(e.path,e.who||"browser",new Date)),method:"PUT",headers:{"Content-Type":x,"If-None-Match":"*","X-Bdrive-Park-On-Conflict":"1"},body:n,keepalive:I(n)<=O}}let A=null,k=null,P=!1,N=!1;const re=e=>{const t=e.data;if(!t||t.type!=="bd-edit:exit"||!Array.isArray(t.patches)||P||N||!A)return;N=!0,k?.close(),k=null;const n=ne(A,t.patches);n&&fetch(n.url,{method:n.method,credentials:"same-origin",headers:n.headers,body:n.body,keepalive:n.keepalive}).catch(()=>{})};self.onmessage=e=>{const t=e.data;if(!(!t||typeof t!="object"||P)){if(t.type==="arm"){A={apiBase:t.apiBase,path:t.path,who:t.who,renderText:t.renderText,renderLen:t.renderLen,allowedRanges:new Set(t.allowedRanges),savedText:t.savedText,baseSha:t.baseSha,docText:t.docText},k?.close(),k=e.ports[0]??null,N=!1,k&&(k.onmessage=re);return}if(t.type==="sync"){if(!A)return;typeof t.savedText=="string"&&(A.savedText=t.savedText),t.hasBaseSha&&(A.baseSha=t.baseSha),typeof t.docText=="string"&&(A.docText=t.docText);return}t.type==="disarm"&&(P=!0,A=null,k?.close(),k=null,self.close())}}})(); diff --git a/internal/webapp/static/assets/index-IQjI59Ja.js b/internal/webapp/static/assets/index-DyFnf9EY.js similarity index 99% rename from internal/webapp/static/assets/index-IQjI59Ja.js rename to internal/webapp/static/assets/index-DyFnf9EY.js index 852d4a1d..9a0c40ab 100644 --- a/internal/webapp/static/assets/index-IQjI59Ja.js +++ b/internal/webapp/static/assets/index-DyFnf9EY.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-yrlJG67f.js","assets/sharedfile-CQlHsuJ4.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CnYT3nlY.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CsLWwTRs.js","assets/sharedfile-CtVUr4nt.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CGKGr6GV.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-yrlJG67f.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CnYT3nlY.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CsLWwTRs.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CGKGr6GV.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` -`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,SV as c,qB as d,GB as e,kf as f,Mo as g,BB as h,BM as i,o as j,PB as k,YB as l,KB as m,xV as n,ZB as o,Sn as p,b as r,uy as s,Ne as t,HB as w}; +`),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-CQlHsuJ4.js b/internal/webapp/static/assets/sharedfile-CtVUr4nt.js similarity index 91% rename from internal/webapp/static/assets/sharedfile-CQlHsuJ4.js rename to internal/webapp/static/assets/sharedfile-CtVUr4nt.js index 1cceabac..20f42ae8 100644 --- a/internal/webapp/static/assets/sharedfile-CQlHsuJ4.js +++ b/internal/webapp/static/assets/sharedfile-CtVUr4nt.js @@ -1,4 +1,4 @@ -import{H as et,i as En,k as Jt,l as Qo,m as xr,n as de,f as Lr,g as Or}from"./index-IQjI59Ja.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-DyFnf9EY.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=` `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i{const s=Kt(t),r=K(),i=C(s),o=e.messageHandlers[i];return o?o `)?s:r?s+` `:s.slice(0,-1)}function Kh(e,t,n){const s=Yn(se(e),se(t),se(n),qt);return s===null?{ok:!1}:{ok:!0,text:jo(e,t,n,s)}}function du(e,t,n){if(t===n)return t;if(e===t)return n;if(e===n)return t;const s=Yn(se(e),se(t),se(n),qt,!0)??se(n);return jo(e,t,n,s)}function Qh(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),s=n.lastIndexOf("."),r=s>=0?n.slice(s).toLowerCase():"",i=o=>{try{return JSON.parse(o),!0}catch{return!1}};if(r===".json")return i(t);if(r===".jsonl")for(const o of t.split(` `)){const l=o.trim();if(l.length>0&&!i(l))return!1}return!0}function Zh(e,t,n,s){const r=Kh(t,n,s);return!r.ok||n===s||n===t||s===t||Qh(e,r.text)?r:{ok:!1}}function li(e,t){if(e===t)return[];const n=[],s=new Map,r=_t(e,qt),i=_t(t,qt),o=u=>{const a=new Array(u.length+1);a[0]=0;for(let h=0;h0?p.charCodeAt(w-1):0;A>=55296&&A<=56319&&w--;const O=S>0?p.charCodeAt(p.length-S):0;O>=56320&&O<=57343&&S--,b+=w,p=p.slice(w,p.length-S),k=k.slice(w,k.length-S),(p.length||k.length)&&s.push({index:b,deleteCount:p.length,insertText:k}),u=f,a=d}}function In(e,t,n){const s=new Map,r=Et(_t(t,qt),s),i=Ue(Et(_t(e,qt),s),r),o=Ue(r,Et(_t(n,qt),s));for(const c of i)for(const u of o)if(c.bSc.bE):!(u.aE<=c.bS||u.aS>=c.bE))return!1}else if(u.bSc.endsWith(` -`);return!(l(t)!==l(e)&&l(n)!==l(t))}function ze(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ci=700,pe=[2e3,4e3,8e3,15e3],ai=2e3,eu=4,nu=64,su=8,ru=32e3,iu=32;function gu(e){const t=(g,m,y)=>Zh(e.path,g,m,y);let n=e.seed,s=e.baseSha;const r=(g,m)=>{n=g,i=m,ct(m);const y=Bt.lastIndexOf(g);y>=0?Bt.splice(0,y+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const m=[];for(let y=g;y!==null&&m.length<4;y=y.prev)y.sent!==y.from&&!m.includes(y.sent)&&m.push(y.sent);return m.length?m:void 0},l=(g,m=Z)=>{const y=o(m);return i&&i===s&&n.length>ru?{base:s,text:g,...y?{prior_sent:y}:{}}:{base:s,base_text:n,text:g,...y?{prior_sent:y}:{}}};let c=!1,u=!1,a=!1,h=!1,f=!1,d=0,p=null,k=!1,b=!1,w=!1,S=null,A=null,O="",U=0;const N=(g=Date.now())=>{const m=Math.max(g,U+1e3);return U=m,Qo(e.path,e.who||"browser",new Date(m))},F=new Map;let Qt=0,St=!1,ft=null,Fe=0,os=!1,Z=null,ot=!1;const Bt=[],kr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>iu&&Bt.shift())};let Lt=!1,Be=null,Zt=0;const Ve=()=>{Lt=!1,Be=null},ls=g=>{Zt===g&&Ve()};let tt=0,lt=0,pn=null,Vt=null,wn=!1,jt=null,Ot=null,je=!1,te=null,dt=null;const $=g=>e.onState?.(g),mn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ht=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let yn=null,cs=0;const He=()=>{clearTimeout(yn??void 0),yn=null},kn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const y=pe[Math.min(cs,pe.length-1)];cs++,yn=setTimeout(()=>{yn=null,!f&&!a&&Pe()},y)},Sr=()=>{He(),cs=0},Je=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},ci)},Rt=g=>{if(f)return p=g,!0;const m=L();if(m===g)return!0;const y=li(m,g);if(Dr())return x.applySplices(y),!0;if(!e.soloApply)return!1;for(const I of y)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(k)return b?Promise.resolve():We();if(Vt)return wn=!0,Vt;const g=(async()=>{try{for(;jt;)await jt;await Ho()}finally{Vt=null}})();return Vt=g,g},Ho=async()=>{let g=0;for(;;){if(wn=!1,V||a||w)return;const m=L();if(m===n&&!ot){$("clean");return}if($("saving"),e.onWriting?.(),St){if(S!==null&&A===m){if(await Sn(m,O)==="stop")return;continue}St=!1}const y=c||u?await Jo(m):await Wo(m);if(y==="stop")return;if(y==="rebased"){if(++g>eu){await Sn(L(),s??"");return}continue}if(!wn){$(L()===n&&!ot?"clean":"dirty");return}}};let mt=!1;const Jo=async g=>{Ot=g,je=!1;let m;try{m=await En(mn(e.path),g,s,mt)}catch(y){return Ot=null,y instanceof et&&y.status===422&&ze(y)?(mt=!1,ee(g),"stop"):y instanceof et&&y.status===409?await as(n,!1)?"rebased":"stop":($("error"),kn(y),"stop")}return Ot=null,mt=!1,Sr(),m.merged?await as(g,!0)?"rebased":"stop":(je||r(g,m.sha),e.onSaved?.(g),"done")},as=async(g,m)=>{let y;try{y=await Lr(Or(e.apiBase,e.path))}catch(R){return $("error"),L()!==n&&kn(R),!1}if(y.kind!=="text")return $("error"),!1;const I=L(),E=t(g,y.text,I);return!E.ok||!Rt(E.text)?(m&&ct(y.sha),await Sn(I,y.sha??"")==="rebased"):(r(y.text,y.sha),m&&e.onSaved?.(y.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){Z=null;return}let m=null;for(let y=Z;y!==null;y=y.prev)if(y.sent!==y.from&&In(y.from,y.sent,g.text)){m=y;break}if(Z=null,m){ot=!0;const y=t(m.sent,g.text,L());y.ok&&Rt(y.text)?(n=g.text,i=void 0,ct(g.sha)):(n=m.sent,i=void 0)}},Wo=async g=>{Ot=g,je=!1;let m;const y=Z;try{Z={sent:g,from:n,prev:y},m=await Jt(Ht,{...l(g,y),...mt?{confirm_shrink:!0}:{}})}catch(E){if(Ot=null,E instanceof et&&[400,401,403,404,405,409,413].includes(E.status)&&(Z=y),E instanceof et&&(E.status===404||E.status===405))return u=!0,"rebased";if(E instanceof et&&E.status===422&&ze(E))return mt=!1,ee(g),"stop";if(E instanceof et&&E.status===409&&!a){let R={};try{R=JSON.parse(E.body)}catch{}const P=typeof R.text=="string"?R.text:null;if(P!==null){const st=t(n,P,L());if(st.ok&&Rt(st.text))return n=P,i=void 0,ct(R.sha),"rebased"}return Sn(L(),R.sha??"")}return $(a?"dirty":"error"),kn(E),"stop"}if(Ot=null,mt=!1,Sr(),m.update&&x.applyRemoteUpdate(m.update),Z=null,ot=!1,a)return"stop";const I=t(g,m.text,L());return I.ok&&Rt(I.text)&&(je||r(m.text,m.sha)),e.onSaved?.(m.text),"done"};let V=null;const ee=g=>{V||f||!e.onShrinkRefused||($("error"),V={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const m=tt,y=Zt;try{const I=await Jt(Ht,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),hs(m,y);const E=!Lt&<>=tt;$(E?"clean":"dirty"),e.onSaved?.(n),!h&&!f&<{if(!f)try{const m=await Lr(Or(e.apiBase,e.path));if(f||m.kind!=="text")return;if(r(m.text,m.sha),Rt(m.text),V=null,a&&!h){if(await fe(!1),f)return;$(lt>=tt&&!Lt?"clean":"dirty");return}lt=tt,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{V=null}}},e.onShrinkRefused(V))};let gt=null;const Yo=()=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{const g=L();xr(de(n),de(g))&&ee(g)},ci)},br=async(g,m,y=N())=>{const I=++Qt;let E=y;for(let R=1;;R++){const P=E;F.set(P,g);try{return await En(mn(P),g,void 0,!1,!1,!1,!0),I===Qt&&!a&&(n=g,i=void 0,m&&(s=m),$("clean")),e.onConflictCopy?.(P),null}catch(st){if(st instanceof et&&st.status===409&&R{const E=(R,P)=>{En(mn(R),m,void 0,!1,!0,!0,!0).then(st=>I?.(st.parked??R),st=>{if(st instanceof et&&st.status===409&&P{(S===null||A!==g)&&(S=N(),A=g);const y=S;O=m,St=!0;const I=await br(g,m,y);return f?"stop":I?(kn(I.err),"stop"):(St=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},hs=(g,m)=>{lt=Math.max(lt,g),ls(m),!(f||h)&&(d=tt-lt,e.onPending?.(d))},qo=()=>{f||h||V||dt||(dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai))},fe=g=>{if(clearTimeout(dt??void 0),dt=null,g){if(lt>=tt)return Promise.resolve();const y=tt,I=Zt;return Jt(Ht,{update:x.encodeState(),base:s},!0).then(E=>{ct(E.sha),hs(y,I)})}if(pn)return pn;const m=(async()=>{try{for(;!h&&!f&&!V&<{k=!1,S=null,A=null,Fe=0,clearTimeout(ft??void 0),ft=null,ot=!1,a=!0,kr(x.text.toString()),g?.(),os&&(os=!1,e.onReady(x))},We=async()=>{if(f||a||b||w)return;if(clearTimeout(ft??void 0),ft=null,te&&clearTimeout(te),te=null,Vt||jt){w=!0;try{for(;Vt||jt;)await(Vt??jt)}finally{w=!1}if(f||a)return;if(!h){L()!==n&&Je();return}}if(Z!==null&&!u){let m;w=!0;try{m=await Jt(Ht,{peek:!0})}catch{if(f||a)return;const y=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},y);return}finally{w=!1}if(f||a)return;if(Po(m),!h){(L()!==n||ot)&&Je();return}}let g;if(e.beforeJoin){w=!0;try{g=await e.beforeJoin()}catch{}finally{w=!1}if(f||a){g?.();return}if(!h){g?.(),(L()!==n||ot)&&Je();return}}try{const m=e.soloText?.();if(m===void 0||m===n)return us();const y=x.text.toString(),I=t(n,y,m);if(I.ok)return us(()=>x.applySplices(li(y,I.text)));k=!0,(S===null||A!==m)&&(S=N(),A=m),b=!0;let E;try{E=await br(m,s??"",S)}finally{b=!1}if(f)return;if(!E)return e.soloText?.()!==m?(S=null,A=null,We()):us(()=>{n=x.text.toString()});const R=E.err;if(R instanceof et&&!(R.status>=500||R.status===429))return;const P=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},P)}finally{g?.()}},x=new Jh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{h=g==="live",g==="solo"&&(c=!0),h&&(dt&&clearTimeout(dt),dt=null,He(),a||We(),lt=tt,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):os=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),Er=(g,m)=>{const y=a?x.text.toString():null;if(y!==null&&kr(y),!x.isRemote(m?.origin)){if($("dirty"),a){Lt=!0,Be=y,Zt+=1,h||(tt+=1,d=tt-lt,e.onPending?.(d),clearTimeout(dt??void 0),dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai)),Yo();return}Je()}};x.text.observe(Er);const Cr=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Cr),Wh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Dr()?x.text.toString():e.soloText?.()??"",Dr=()=>a||c&&x.text.length>0,ct=g=>{g&&(s=g)},zo=(g,m,y)=>{if(y?.held)return r(g,m),"same";if(g===n||g===Ot)return ct(m),"same";const I=L();if(g===I)return r(g,m),a&&(Ve(),$("clean")),"same";if(a){const R=n;return Bt.includes(g)||In(R,g,I)?(r(g,m),Lt&&(Be===null||g===Be||In(R,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,m),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const E=t(n,g,I);return E.ok?(Ot!==null&&(je=!0),r(g,m),Rt(E.text),E.text!==g?Je():Ot===null&&$("clean"),E.text===I?"same":"merged"):"blocked"},bn=()=>f?!1:a?h?Lt:ltmt||!e.onShrinkRefused||!xr(de(n),de(L()))?!1:(clearTimeout(gt??void 0),gt=null,ee(L()),!0),Xo=async()=>{const g=Zt;$("saving");try{const m=await Jt(Ht,{update:x.encodeState()});return f?!1:(m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),ls(g),$(Lt?"dirty":"clean"),e.onSaved?.(n),!0)}catch(m){return f||m instanceof et&&m.status===422&&ze(m)&&(clearTimeout(gt??void 0),gt=null,ee(L()),V)||$(Lt?"dirty":"clean"),!1}};let Ye=null;const Ko=()=>{if(Ye)return Vt&&(wn=!0),Ye;if(f||V)return Promise.resolve(!1);if(!bn())return Promise.resolve(!0);const m=(async()=>{for(;!f&&!V&&bn();){if(Go())return!1;if(a){if(h){if(!await Xo())return!1;continue}if(await fe(!1),f||V||!h&<{Ye===m&&(Ye=null)});return Ye=m,m};let Ut=null;const _n=g=>()=>{Ut===g&&(Ut=null)},Ar=(g,m)=>{if(V)return;if(a){const T=!h&&d>0;if(!T&&!(h&&Lt))return;const j="room\0"+x.text.toString();if(Ut===j)return;Ut=j;const Mt=Zt;(T?fe(!0):Jt(Ht,{update:x.encodeState()},!0).then(gs=>ct(gs.sha))).then(()=>ls(Mt),_n(j));return}if(k||St){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let j=S!==null&&A===g?S:null;for(const[Mt,at]of F)j===null&&at===g&&(j=Mt);j??=N(),_r(j,g,T);return}if(g===n&&!ot)return;const y="text\0"+g;if(Ut===y)return;if((c||u)&&!m){Pe();return}Ut=y;const I=n,E=!(c||u),R=Z,P={sent:g,from:I,prev:R};E&&(Z=P);const st=T=>{if(E&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&Z===P&&(Z=R),T instanceof et&&T.status===422&&ze(T)){_n(y)(),f||(clearTimeout(gt??void 0),gt=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return _n(y)();let j={};try{const at=JSON.parse(T.body);at&&typeof at=="object"&&(j=at)}catch{}if(typeof j.text=="string"&&(j.text===g||In(I,g,j.text))){if(!f&&!a){const at=t(g,j.text,L());at.ok&&Rt(at.text)&&(n=j.text,i=void 0,typeof j.sha=="string"&&ct(j.sha))}return}if(!g.trim())return;St=!0;let Mt=S!==null&&A===g?S:null;for(const[at,gs]of F)Mt===null&&gs===g&&(Mt=at);Mt??=N(),S=Mt,A=g,_r(Mt,g,y,at=>{St=!1,e.onConflictCopy?.(at)})},qe=(T,j)=>{n=g,i=void 0,ct(j),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let fs;E?fs=Jt(Ht,{...l(g,R),park_on_conflict:!0},!0).then(T=>{if(mt=!1,Z===P&&(Z=null),ot=!1,T.parked)return qe(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ct(T.sha);return}const j=t(g,T.text,L());j.ok&&Rt(j.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},st):fs=En(mn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return qe(T.parked,T.sha);if(T.merged){f?ct(T.sha):as(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},st);const ds=fs.then(()=>{},()=>{});jt=ds,ds.then(()=>{jt===ds&&(jt=null)})},Ir=()=>{f||Ar(L(),!0)},Tr=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ir),window.addEventListener("pageshow",Tr)),{collab:x,current:L,merge:zo,rebase:ct,saveNow:Ko,askingShrink:()=>V!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ir),window.removeEventListener("pageshow",Tr)),clearTimeout(te??void 0),clearTimeout(gt??void 0),He(),clearTimeout(ft??void 0),ft=null;const g=L();f=!0,p=g,V?e.onShrinkWithdrawn?.(V):Ar(g,!1),clearTimeout(dt??void 0),x.awareness.off("change",Cr),x.text.unobserve(Er),x.destroy()}}}export{he as D,ci as S,fu as U,hu as a,_a as b,Aa as c,li as d,uu as e,Ps as f,ae as g,lu as h,vt as i,du as m,gu as o,au as r,cu as t}; +`);return!(l(t)!==l(e)&&l(n)!==l(t))}function ze(e){try{return JSON.parse(e.body).shrink===!0}catch{return!1}}const ci=700,pe=[2e3,4e3,8e3,15e3],ai=2e3,eu=4,nu=64,su=8,ru=32e3,iu=32;function gu(e){const t=(g,m,y)=>Zh(e.path,g,m,y);let n=e.seed,s=e.baseSha;const r=(g,m)=>{n=g,i=m,ct(m);const y=Bt.lastIndexOf(g);y>=0?Bt.splice(0,y+1):Bt.length=0};let i=e.baseSha;const o=g=>{if(!g)return;const m=[];for(let y=g;y!==null&&m.length<4;y=y.prev)y.sent!==y.from&&!m.includes(y.sent)&&m.push(y.sent);return m.length?m:void 0},l=(g,m=Z)=>{const y=o(m);return i&&i===s&&n.length>ru?{base:s,text:g,...y?{prior_sent:y}:{}}:{base:s,base_text:n,text:g,...y?{prior_sent:y}:{}}};let c=!1,u=!1,a=!1,h=!1,f=!1,d=0,p=null,k=!1,b=!1,w=!1,S=null,A=null,O="",U=0;const N=(g=Date.now())=>{const m=Math.max(g,U+1e3);return U=m,Qo(e.path,e.who||"browser",new Date(m))},F=new Map;let Qt=0,St=!1,ft=null,Fe=0,os=!1,Z=null,ot=!1;const Bt=[],kr=g=>{Bt.at(-1)!==g&&(Bt.push(g),Bt.length>iu&&Bt.shift())};let Lt=!1,Be=null,Zt=0;const Ve=()=>{Lt=!1,Be=null},ls=g=>{Zt===g&&Ve()};let tt=0,lt=0,pn=null,Vt=null,wn=!1,jt=null,Ot=null,je=!1,te=null,dt=null;const $=g=>e.onState?.(g),mn=g=>e.apiBase+"upload/content?path="+encodeURIComponent(g),Ht=e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path);let yn=null,cs=0;const He=()=>{clearTimeout(yn??void 0),yn=null},kn=g=>{if(!(g instanceof et?g.status>=500||g.status===429:!0)||f||a)return;He();const y=pe[Math.min(cs,pe.length-1)];cs++,yn=setTimeout(()=>{yn=null,!f&&!a&&Pe()},y)},Sr=()=>{He(),cs=0},Je=()=>{He(),te&&clearTimeout(te),te=setTimeout(()=>{Pe()},ci)},Rt=g=>{if(f)return p=g,!0;const m=L();if(m===g)return!0;const y=li(m,g);if(Dr())return x.applySplices(y),!0;if(!e.soloApply)return!1;for(const I of y)e.soloApply({from:I.index,to:I.index+I.deleteCount,insert:I.insertText});return!0},Pe=()=>{if(a)return Promise.resolve();if(k)return b?Promise.resolve():We();if(Vt)return wn=!0,Vt;const g=(async()=>{try{for(;jt;)await jt;await Ho()}finally{Vt=null}})();return Vt=g,g},Ho=async()=>{let g=0;for(;;){if(wn=!1,V||a||w)return;const m=L();if(m===n&&!ot){$("clean");return}if($("saving"),e.onWriting?.(),St){if(S!==null&&A===m){if(await Sn(m,O)==="stop")return;continue}St=!1}const y=c||u?await Jo(m):await Wo(m);if(y==="stop")return;if(y==="rebased"){if(++g>eu){await Sn(L(),s??"");return}continue}if(!wn){$(L()===n&&!ot?"clean":"dirty");return}}};let mt=!1;const Jo=async g=>{Ot=g,je=!1;let m;try{m=await En(mn(e.path),g,s,mt)}catch(y){return Ot=null,y instanceof et&&y.status===422&&ze(y)?(mt=!1,ee(g),"stop"):y instanceof et&&y.status===409?await as(n,!1)?"rebased":"stop":($("error"),kn(y),"stop")}return Ot=null,mt=!1,Sr(),m.merged?await as(g,!0)?"rebased":"stop":(je||r(g,m.sha),e.onSaved?.(g),"done")},as=async(g,m)=>{let y;try{y=await Lr(Or(e.apiBase,e.path))}catch(R){return $("error"),L()!==n&&kn(R),!1}if(y.kind!=="text")return $("error"),!1;const I=L(),E=t(g,y.text,I);return!E.ok||!Rt(E.text)?(m&&ct(y.sha),await Sn(I,y.sha??"")==="rebased"):(r(y.text,y.sha),m&&e.onSaved?.(y.text),!0)},Po=g=>{if(g.update&&x.applyRemoteUpdate(g.update),typeof g.text!="string"){Z=null;return}let m=null;for(let y=Z;y!==null;y=y.prev)if(y.sent!==y.from&&In(y.from,y.sent,g.text)){m=y;break}if(Z=null,m){ot=!0;const y=t(m.sent,g.text,L());y.ok&&Rt(y.text)?(n=g.text,i=void 0,ct(g.sha)):(n=m.sent,i=void 0,e.onBaseChange?.(n,s))}},Wo=async g=>{Ot=g,je=!1;let m;const y=Z;try{Z={sent:g,from:n,prev:y},m=await Jt(Ht,{...l(g,y),...mt?{confirm_shrink:!0}:{}})}catch(E){if(Ot=null,E instanceof et&&[400,401,403,404,405,409,413].includes(E.status)&&(Z=y),E instanceof et&&(E.status===404||E.status===405))return u=!0,"rebased";if(E instanceof et&&E.status===422&&ze(E))return mt=!1,ee(g),"stop";if(E instanceof et&&E.status===409&&!a){let R={};try{R=JSON.parse(E.body)}catch{}const P=typeof R.text=="string"?R.text:null;if(P!==null){const st=t(n,P,L());if(st.ok&&Rt(st.text))return n=P,i=void 0,ct(R.sha),"rebased"}return Sn(L(),R.sha??"")}return $(a?"dirty":"error"),kn(E),"stop"}if(Ot=null,mt=!1,Sr(),m.update&&x.applyRemoteUpdate(m.update),Z=null,ot=!1,a)return"stop";const I=t(g,m.text,L());return I.ok&&Rt(I.text)&&(je||r(m.text,m.sha)),e.onSaved?.(m.text),"done"};let V=null;const ee=g=>{V||f||!e.onShrinkRefused||($("error"),V={was:de(n),now:de(g),confirm:async()=>{if(!f){if(a){$("saving"),e.onWriting?.();const m=tt,y=Zt;try{const I=await Jt(Ht,{update:x.encodeState(),base:s,confirm_shrink:!0});r(I.text,I.sha),hs(m,y);const E=!Lt&<>=tt;$(E?"clean":"dirty"),e.onSaved?.(n),!h&&!f&<{if(!f)try{const m=await Lr(Or(e.apiBase,e.path));if(f||m.kind!=="text")return;if(r(m.text,m.sha),Rt(m.text),V=null,a&&!h){if(await fe(!1),f)return;$(lt>=tt&&!Lt?"clean":"dirty");return}lt=tt,d&&(d=0,e.onPending?.(0)),Ve(),$("clean")}catch{$("error")}finally{V=null}}},e.onShrinkRefused(V))};let gt=null;const Yo=()=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{const g=L();xr(de(n),de(g))&&ee(g)},ci)},br=async(g,m,y=N())=>{const I=++Qt;let E=y;for(let R=1;;R++){const P=E;F.set(P,g);try{return await En(mn(P),g,void 0,!1,!1,!1,!0),I===Qt&&!a&&(n=g,i=void 0,m&&(s=m),$("clean")),e.onConflictCopy?.(P),null}catch(st){if(st instanceof et&&st.status===409&&R{const E=(R,P)=>{En(mn(R),m,void 0,!1,!0,!0,!0).then(st=>I?.(st.parked??R),st=>{if(st instanceof et&&st.status===409&&P{(S===null||A!==g)&&(S=N(),A=g);const y=S;O=m,St=!0;const I=await br(g,m,y);return f?"stop":I?(kn(I.err),"stop"):(St=!1,A===g&&(S=null,A=null,O=""),L()!==g?"rebased":"stop")},hs=(g,m)=>{lt=Math.max(lt,g),ls(m),!(f||h)&&(d=tt-lt,e.onPending?.(d))},qo=()=>{f||h||V||dt||(dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai))},fe=g=>{if(clearTimeout(dt??void 0),dt=null,g){if(lt>=tt)return Promise.resolve();const y=tt,I=Zt;return Jt(Ht,{update:x.encodeState(),base:s},!0).then(E=>{ct(E.sha),hs(y,I)})}if(pn)return pn;const m=(async()=>{try{for(;!h&&!f&&!V&<{k=!1,S=null,A=null,Fe=0,clearTimeout(ft??void 0),ft=null,ot=!1,a=!0,kr(x.text.toString()),g?.(),os&&(os=!1,e.onReady(x))},We=async()=>{if(f||a||b||w)return;if(clearTimeout(ft??void 0),ft=null,te&&clearTimeout(te),te=null,Vt||jt){w=!0;try{for(;Vt||jt;)await(Vt??jt)}finally{w=!1}if(f||a)return;if(!h){L()!==n&&Je();return}}if(Z!==null&&!u){let m;w=!0;try{m=await Jt(Ht,{peek:!0})}catch{if(f||a)return;const y=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},y);return}finally{w=!1}if(f||a)return;if(Po(m),!h){(L()!==n||ot)&&Je();return}}let g;if(e.beforeJoin){w=!0;try{g=await e.beforeJoin()}catch{}finally{w=!1}if(f||a){g?.();return}if(!h){g?.(),(L()!==n||ot)&&Je();return}}try{const m=e.soloText?.();if(m===void 0||m===n)return us();const y=x.text.toString(),I=t(n,y,m);if(I.ok)return us(()=>x.applySplices(li(y,I.text)));k=!0,(S===null||A!==m)&&(S=N(),A=m),b=!0;let E;try{E=await br(m,s??"",S)}finally{b=!1}if(f)return;if(!E)return e.soloText?.()!==m?(S=null,A=null,We()):us(()=>{n=x.text.toString()});const R=E.err;if(R instanceof et&&!(R.status>=500||R.status===429))return;const P=pe[Math.min(Fe,pe.length-1)];Fe++,ft=setTimeout(()=>{ft=null,We()},P)}finally{g?.()}},x=new Jh(e.apiBase+"ycollab?path="+encodeURIComponent(e.path),g=>{h=g==="live",g==="solo"&&(c=!0),h&&(dt&&clearTimeout(dt),dt=null,He(),a||We(),lt=tt,d&&(d=0,e.onPending?.(0))),e.onCollab?.(g)},()=>{a?e.onReady(x):os=!0},()=>{!f&&!a&&e.onStalled?.()},e.me),Er=(g,m)=>{const y=a?x.text.toString():null;if(y!==null&&kr(y),!x.isRemote(m?.origin)){if($("dirty"),a){Lt=!0,Be=y,Zt+=1,h||(tt+=1,d=tt-lt,e.onPending?.(d),clearTimeout(dt??void 0),dt=setTimeout(()=>{dt=null,!h&&!f&&fe(!1)},ai)),Yo();return}Je()}};x.text.observe(Er);const Cr=()=>e.onPeers?.(x.peerCount());x.awareness.on("change",Cr),Wh(e.apiBase)?x.connect():queueMicrotask(()=>{f||(c=!0,x.stop(),e.onSolo())});const L=()=>p!==null?p:Dr()?x.text.toString():e.soloText?.()??"",Dr=()=>a||c&&x.text.length>0,ct=g=>{g&&(s=g),e.onBaseChange?.(n,s)},zo=(g,m,y)=>{if(y?.held)return r(g,m),"same";if(g===n||g===Ot)return ct(m),"same";const I=L();if(g===I)return r(g,m),a&&(Ve(),$("clean")),"same";if(a){const R=n;return Bt.includes(g)||In(R,g,I)?(r(g,m),Lt&&(Be===null||g===Be||In(R,Be,g))&&(Ve(),$("clean")),"same"):I!==n||x.peerCount()>0?"blocked":(r(g,m),Rt(g),Ve(),"merged")}if(!x.text.length&&!e.soloApply)return"blocked";const E=t(n,g,I);return E.ok?(Ot!==null&&(je=!0),r(g,m),Rt(E.text),E.text!==g?Je():Ot===null&&$("clean"),E.text===I?"same":"merged"):"blocked"},bn=()=>f?!1:a?h?Lt:ltmt||!e.onShrinkRefused||!xr(de(n),de(L()))?!1:(clearTimeout(gt??void 0),gt=null,ee(L()),!0),Xo=async()=>{const g=Zt;$("saving");try{const m=await Jt(Ht,{update:x.encodeState()});return f?!1:(m.update&&x.applyRemoteUpdate(m.update),r(m.text,m.sha),ls(g),$(Lt?"dirty":"clean"),e.onSaved?.(n),!0)}catch(m){return f||m instanceof et&&m.status===422&&ze(m)&&(clearTimeout(gt??void 0),gt=null,ee(L()),V)||$(Lt?"dirty":"clean"),!1}};let Ye=null;const Ko=()=>{if(Ye)return Vt&&(wn=!0),Ye;if(f||V)return Promise.resolve(!1);if(!bn())return Promise.resolve(!0);const m=(async()=>{for(;!f&&!V&&bn();){if(Go())return!1;if(a){if(h){if(!await Xo())return!1;continue}if(await fe(!1),f||V||!h&<{Ye===m&&(Ye=null)});return Ye=m,m};let Ut=null;const _n=g=>()=>{Ut===g&&(Ut=null)},Ar=(g,m)=>{if(V)return;if(a){const T=!h&&d>0;if(!T&&!(h&&Lt))return;const j="room\0"+x.text.toString();if(Ut===j)return;Ut=j;const Mt=Zt;(T?fe(!0):Jt(Ht,{update:x.encodeState()},!0).then(gs=>ct(gs.sha))).then(()=>ls(Mt),_n(j));return}if(k||St){if(!g.trim())return;const T="park\0"+g;if(Ut===T)return;Ut=T;let j=S!==null&&A===g?S:null;for(const[Mt,at]of F)j===null&&at===g&&(j=Mt);j??=N(),_r(j,g,T);return}if(g===n&&!ot)return;const y="text\0"+g;if(Ut===y)return;if((c||u)&&!m){Pe();return}Ut=y;const I=n,E=!(c||u),R=Z,P={sent:g,from:I,prev:R};E&&(Z=P);const st=T=>{if(E&&T instanceof et&&[400,401,403,404,405,409,413].includes(T.status)&&Z===P&&(Z=R),T instanceof et&&T.status===422&&ze(T)){_n(y)(),f||(clearTimeout(gt??void 0),gt=null,ee(L()));return}if(!(T instanceof et&&T.status===409))return _n(y)();let j={};try{const at=JSON.parse(T.body);at&&typeof at=="object"&&(j=at)}catch{}if(typeof j.text=="string"&&(j.text===g||In(I,g,j.text))){if(!f&&!a){const at=t(g,j.text,L());at.ok&&Rt(at.text)&&(n=j.text,i=void 0,typeof j.sha=="string"&&ct(j.sha))}return}if(!g.trim())return;St=!0;let Mt=S!==null&&A===g?S:null;for(const[at,gs]of F)Mt===null&&gs===g&&(Mt=at);Mt??=N(),S=Mt,A=g,_r(Mt,g,y,at=>{St=!1,e.onConflictCopy?.(at)})},qe=(T,j)=>{n=g,i=void 0,ct(j),!f&&L()===g&&$("clean"),e.onConflictCopy?.(T)};let fs;E?fs=Jt(Ht,{...l(g,R),park_on_conflict:!0},!0).then(T=>{if(mt=!1,Z===P&&(Z=null),ot=!1,T.parked)return qe(T.parked,T.sha);if(T.update&&x.applyRemoteUpdate(T.update),f||a||typeof T.text!="string"){ct(T.sha);return}const j=t(g,T.text,L());j.ok&&Rt(j.text)&&(r(T.text,T.sha),L()===n&&$("clean")),e.onSaved?.(T.text)},st):fs=En(mn(e.path),g,s,mt,!0,!0).then(T=>{if(mt=!1,T.parked)return qe(T.parked,T.sha);if(T.merged){f?ct(T.sha):as(g,!0);return}r(g,T.sha),!f&&L()===n&&$("clean"),e.onSaved?.(g)},st);const ds=fs.then(()=>{},()=>{});jt=ds,ds.then(()=>{jt===ds&&(jt=null)})},Ir=()=>{f||Ar(L(),!0)},Tr=()=>{Ut=null};return typeof window<"u"&&(window.addEventListener("pagehide",Ir),window.addEventListener("pageshow",Tr)),{collab:x,current:L,merge:zo,rebase:ct,saveNow:Ko,askingShrink:()=>V!==null,destroy(){typeof window<"u"&&(window.removeEventListener("pagehide",Ir),window.removeEventListener("pageshow",Tr)),clearTimeout(te??void 0),clearTimeout(gt??void 0),He(),clearTimeout(ft??void 0),ft=null;const g=L();f=!0,p=g,V?e.onShrinkWithdrawn?.(V):Ar(g,!1),clearTimeout(dt??void 0),x.awareness.off("change",Cr),x.text.unobserve(Er),x.destroy()}}}export{he as D,ci as S,fu as U,hu as a,_a as b,Aa as c,li as d,uu as e,Ps as f,ae as g,lu as h,vt as i,du as m,gu as o,au as r,cu as t}; diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index cefed51c..a64f9238 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -9,7 +9,7 @@ BearDrive - + diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js index b604eef3..413156e9 100644 --- a/internal/webapp/static/inline-edit.js +++ b/internal/webapp/static/inline-edit.js @@ -1,21 +1,21 @@ -(function(){"use strict";var Dr=Object.defineProperty,hl=(n,e)=>{let t={};for(var r in n)Dr(t,r,{get:n[r],enumerable:!0});return Dr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ar(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function vr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Lt(t+1,s):Lt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Br(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Pr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Pr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Pr(s.content,e-i-1,t-i-1)))}function Br(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Br(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function pl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return zr(n,e,t,0)}function zr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&wn(n,e,i+1),o=r.depth>i&&wn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Fr(s,o),Be(ze(s,Lr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,$t(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,$t(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function $t(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=wn(n,e,t+1);Be(ze(i,$t(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function ml(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Wt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Vr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),$r(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):$r(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function $r(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new kl(e,t);if(r.next==null)return Le.empty;let i=Wr(r);r.next&&r.err("Unexpected trailing text");let s=Ol(Tl(i));return Nl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}Le.empty=new Le(!0);class kl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Wr(n){let e=[];do e.push(xl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function xl(n){let e=[];do e.push(Sl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Sl(n){let e=wl(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=Ml(n,e);else break;return e}function jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Ml(n,e){let t=jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Cl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function wl(n){if(n.eat("(")){let e=Wr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Cl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Tl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Kr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new al(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function El(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Dl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?El(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Jt{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Ur(e,i.attrs),this.excluded=null;let s=Hr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Kr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Jt(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Yr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Gr.compile(this.spec.nodes,this),this.marks=Jt.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Xr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Xr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Gr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Xr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Al(n){return n.tag!=null}function Il(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Al(i))this.tags.push(i);else if(Il(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ti(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ti(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ni(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ni(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Qr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Rl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Zr={ol:!0,ul:!0},gt=1,Tn=2,yt=4;function ei(n,e,t){return e!=null?(e?gt:0)|(e==="full"?Tn:0):n&&n.whitespace=="pre"?gt|Tn:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Qr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ti{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ei(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Tn?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ri(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function vl(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Zr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Pl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ni(n){let e={};for(let t in n)e[t]=n[t];return e}function ri(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Kt(Ht(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Kt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ii(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ii(e.marks)}}function ii(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Ht(n){return n.document||window.document}const si=new WeakMap;function Bl(n){let e=si.get(n);return e===void 0&&si.set(n,e=zl(n)),e}function zl(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Kt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const oi=65535,li=Math.pow(2,16);function Fl(n,e){return n+e*li}function ai(n){return n&oi}function Ll(n){return(n-(n&oi))/li}const ci=1,fi=2,_t=4,ui=8;class On{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ui)>0}get deletedBefore(){return(this.delInfo&(ci|_t))>0}get deletedAfter(){return(this.delInfo&(fi|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ai(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Fl(l/3,e-a),m=e==a?fi:e==u?ci:_t;return(t<0?e!=a:e!=u)&&(m|=ui),new On(h,m,p)}i+=f-c}return r?e+i:new On(e+i,0,null)}touches(e,t){let r=0,i=ai(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(En(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function Dn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Vl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function $l(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Jt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function An(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Wl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Kl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&_l(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&mi(n,o,l,s),An(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&pi(n,o,l,s),!1}})}function pi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function _l(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Ul(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Gl(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new R(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return gi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Yl(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&gi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Xl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);mi(n,f.node(),f.before(),l)}o.inlineContent&&An(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new R(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);pi(n,f.node(),f.before(),n.steps.length)}return n}function Ql(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Gt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return yi(i,s,r)?new R(e,t,r):new ea(i,s,r).fit()}function yi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class ea{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new R(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=bi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return xi(e,-1)<=t?!1:(this.unplaced.size>1&&xi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=bi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(ki(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=In(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function bi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,ki(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function In(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!ta(t,s.content,o)?l:null}function ta(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=na(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Si(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function ia(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Ql(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function sa(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Mi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Mi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class Ci{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Gt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return ra(this,e,t,r),this}replaceRangeWith(e,t,r){return ia(this,e,t,r),this}deleteRange(e,t){return sa(this,e,t),this}lift(e,t){return jl(this,e,t),this}join(e,t=1){return Xl(this,e,t),this}wrap(e,t){return Hl(this,e,t),this}setBlockType(e,t=e,r,i=null){return Kl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Ul(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Gl(this,e,t,r),this}addMark(e,t,r){return Vl(this,e,t,r),this}removeMark(e,t,r){return $l(this,e,t,r),this}clearIncompatible(e,t,r){return An(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new oa(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class oa{constructor(e,t){this.$from=e,this.$to=t}}let wi=!1;function Ti(n){!wi&&!n.parent.inlineContent&&(wi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ti(e),Ti(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Yt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Oi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ni=1,Xt=2,Ei=4;class aa extends Ci{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Xt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ei,this}get scrolledIntoView(){return(this.updated&Ei)>0}}function Di(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Di(t.init,r),this.apply=Di(t.apply,r)}}const ca=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Pn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ca.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Pn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ai(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ai(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ai(e.props,this,this.props),this.key=e.key?e.key.key:Ii("plugin")}getState(e){return e[this.key]}}const Bn=Object.create(null);function Ii(n){return n in Bn?n+"$"+ ++Bn[n]:(Bn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ii(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Ri=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function vi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Pi=(n,e,t)=>{let r=vi(n,t);if(!r)return!1;let i=zn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(qi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Gt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},fa=(n,e,t)=>{let r=vi(n,t);if(!r)return!1;let i=zn(r);return i?Bi(n,i,e):!1},ua=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Fn(r);return i?Bi(n,i,e):!1};function Bi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Gt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof R&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const zi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=zn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function zn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Fi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Fi(n,t);if(!r)return!1;let i=Fn(r);if(!i)return!1;let s=i.nodeAfter;if(qi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Gt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Ut(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ha=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Ut(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},pa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},$i=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function Ln(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Ln(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Ln(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ma(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Ln(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const ga=ma(),ya=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ba=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ka(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function qi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ka(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Hi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ki=Hi(-1),_i=Hi(1);function xa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&di(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ui(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Gi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!Sa(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Wt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Na(e,t,n,s):Ea(e,t,s):!0:!1}}function Na(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Da(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Wn=null;const ge=function(n,e,t){let r=Wn||(Wn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Aa=function(){Wn=null},je=function(n,e,t,r){return t&&(Qi(n,e,t,r,-1)||Qi(n,e,t,r,1))},Ia=/^(img|br|input|textarea|hr)$/i;function Qi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Ia.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Ra(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function va(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),ns=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!Zi&&"webkitFontSmoothing"in Zi.documentElement.style,Fa=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function La(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Va(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function rs(n,e,t){if(!Kn(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?La(s):Va(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function $a(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:is(n.dom)}}function is(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Wa({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ss(t,r==0?0:r-e)}function ss(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Ja(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:ls(t,i)}function Ja(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function qa(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ka(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function as(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ka(n,r,i,e))}l==null&&(l=Ha(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Kn(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return _n(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function _n(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function fs(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Ga(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return fs(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=cs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ya=/[\u0590-\u08ac]/;function Xa(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ya.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:fs(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let us=null,ds=null,hs=!1;function Qa(n,e,t){return us==e&&ds==t?hs:(us=e,ds=t,hs=t=="up"||t=="down"?Ga(n,e,t):Xa(n,e,t))}const te=0,ps=1,qe=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ys){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ms&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?qe:ps,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?qe:se}r=o}this.dirty=qe}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?qe:ps;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Za extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Gn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=xs(f,r,t),c?a=new ec(e,t,r,i,f,u||null,d,c):t.isText?new Zt(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&en(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new nc(this,o&&o.node,e);sc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==qe)&&(o&&this.protectLocalComposition(e,o),bs(this.contentDOM,this.children,e),at&&oc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=lc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Za(this,s,t,i);e.input.compositionNodes.push(o),this.children=Gn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(en(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ks(this.dom,this.nodeDOM,Un(this.outerDeco,this.node,t),Un(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function gs(n,e,t,r,i){xs(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class Zt extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new Zt(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ys extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ec extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function bs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function ic(n,e){return n.type.side-e.type.side}function sc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function oc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function lc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Gn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Yn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Qt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Pa(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Ms(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function cc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Os(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ns(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ns(n)}function Ns(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Qn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Es(n){return n.editable&&!n.hasFocus()?!1:Ds(n)}function Ds(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function fc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Zn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function As(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Zn(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=Zn(n.state,e);return i?Ee(n,i):!1}}}function tn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?uc(n):dc(n)}function uc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Is(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=tn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?er(n,t,r):i&&er(n,i,s)}function dc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=tn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function Rs(n,e){let t=n.state.doc.resolve(e);if(!(V||ns)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function vs(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Zn(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Ps(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Bs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function mc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Bs(n,r,"true"),setTimeout(()=>Bs(n,r,"false"),20)}return!1}function gc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function yc(n,e){let t=e.keyCode,r=gc(e);if(t==8||ee&&t==72&&r=="c")return Ps(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Ps(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?Rs(n,n.state.selection.from)=="ltr"?-1:1:-1;return As(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?Rs(n,n.state.selection.from)=="ltr"?1:-1:1;return As(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return vs(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return mc(n)||vs(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function tr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ws[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` +(function(){"use strict";var Dr=Object.defineProperty,ul=(n,e)=>{let t={};for(var r in n)Dr(t,r,{get:n[r],enumerable:!0});return Dr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ar(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Rr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Vt(t+1,s):Vt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Br(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Pr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Pr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Pr(s.content,e-i-1,t-i-1)))}function Br(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Br(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function dl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return zr(n,e,t,0)}function zr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&Tn(n,e,i+1),o=r.depth>i&&Tn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Fr(s,o),Be(ze(s,Lr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,Wt(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,Wt(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function Wt(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Tn(n,e,t+1);Be(ze(i,Wt(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function hl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new jt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Vr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),$r(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class Jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):$r(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function $r(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new yl(e,t);if(r.next==null)return Le.empty;let i=Wr(r);r.next&&r.err("Unexpected trailing text");let s=wl(Cl(i));return Tl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Le.empty=new Le(!0);class yl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Wr(n){let e=[];do e.push(bl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function bl(n){let e=[];do e.push(kl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function kl(n){let e=Ml(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=xl(n,e);else break;return e}function jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function xl(n,e){let t=jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Sl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Ml(n){if(n.eat("(")){let e=Wr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Sl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Cl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Kr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new ol(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Ol(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Nl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ol(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Ht{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Ur(e,i.attrs),this.excluded=null;let s=qr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Kr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Ht(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Yr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Gr.compile(this.spec.nodes,this),this.marks=Ht.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Xr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Xr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Gr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Xr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function El(n){return n.tag!=null}function Dl(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(El(i))this.tags.push(i);else if(Dl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ti(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ti(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ni(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ni(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Qr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Al={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Zr={ol:!0,ul:!0},gt=1,On=2,yt=4;function ei(n,e,t){return e!=null?(e?gt:0)|(e==="full"?On:0):n&&n.whitespace=="pre"?gt|On:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Qr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ti{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ei(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&On?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ri(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Il(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Zr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function vl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ni(n){let e={};for(let t in n)e[t]=n[t];return e}function ri(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&_t(Kt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:_t(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ii(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ii(e.marks)}}function ii(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Kt(n){return n.document||window.document}const si=new WeakMap;function Rl(n){let e=si.get(n);return e===void 0&&si.set(n,e=Pl(n)),e}function Pl(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=_t(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const oi=65535,li=Math.pow(2,16);function Bl(n,e){return n+e*li}function ai(n){return n&oi}function zl(n){return(n-(n&oi))/li}const ci=1,fi=2,Ut=4,ui=8;class Nn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ui)>0}get deletedBefore(){return(this.delInfo&(ci|Ut))>0}get deletedAfter(){return(this.delInfo&(fi|Ut))>0}get deletedAcross(){return(this.delInfo&Ut)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ai(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Bl(l/3,e-a),m=e==a?fi:e==u?ci:Ut;return(t<0?e!=a:e!=u)&&(m|=ui),new Nn(h,m,p)}i+=f-c}return r?e+i:new Nn(e+i,0,null)}touches(e,t){let r=0,i=ai(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Dn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function An(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Fl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Ll(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Ht){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function In(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Vl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Hl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&ql(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&mi(n,o,l,s),In(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&pi(n,o,l,s),!1}})}function pi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function ql(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Kl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function _l(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new v(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return gi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Ul(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&gi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Gl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);mi(n,f.node(),f.before(),l)}o.inlineContent&&In(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new v(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);pi(n,f.node(),f.before(),n.steps.length)}return n}function Yl(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Yt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return yi(i,s,r)?new v(e,t,r):new Ql(i,s,r).fit()}function yi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Ql{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new v(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=bi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return xi(e,-1)<=t?!1:(this.unplaced.size>1&&xi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=bi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(ki(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=vn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function bi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,ki(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function vn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Zl(t,s.content,o)?l:null}function Zl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=ea(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Si(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function na(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Yl(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ra(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Mi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Mi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class Ci{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Yt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return ta(this,e,t,r),this}replaceRangeWith(e,t,r){return na(this,e,t,r),this}deleteRange(e,t){return ra(this,e,t),this}lift(e,t){return $l(this,e,t),this}join(e,t=1){return Gl(this,e,t),this}wrap(e,t){return Jl(this,e,t),this}setBlockType(e,t=e,r,i=null){return Hl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Kl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return _l(this,e,t,r),this}addMark(e,t,r){return Fl(this,e,t,r),this}removeMark(e,t,r){return Ll(this,e,t,r),this}clearIncompatible(e,t,r){return In(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ia(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ia{constructor(e,t){this.$from=e,this.$to=t}}let wi=!1;function Ti(n){!wi&&!n.parent.inlineContent&&(wi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ti(e),Ti(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Xt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Oi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ni=1,Qt=2,Ei=4;class oa extends Ci{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Qt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Qt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Qt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ei,this}get scrolledIntoView(){return(this.updated&Ei)>0}}function Di(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Di(t.init,r),this.apply=Di(t.apply,r)}}const la=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Bn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=la.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Bn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ai(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ai(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ai(e.props,this,this.props),this.key=e.key?e.key.key:Ii("plugin")}getState(e){return e[this.key]}}const zn=Object.create(null);function Ii(n){return n in zn?n+"$"+ ++zn[n]:(zn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ii(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const vi=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ri(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Pi=(n,e,t)=>{let r=Ri(n,t);if(!r)return!1;let i=Fn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Hi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Yt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},aa=(n,e,t)=>{let r=Ri(n,t);if(!r)return!1;let i=Fn(r);return i?Bi(n,i,e):!1},ca=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);return i?Bi(n,i,e):!1};function Bi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Yt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof v&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const zi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Fn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Fn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Fi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);if(!i)return!1;let s=i.nodeAfter;if(Hi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Yt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Gt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ua=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Gt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},da=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},$i=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Vn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Vn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Vn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ha(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Vn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const pa=ha(),ma=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ga=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ya(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Hi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ya(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function qi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ki=qi(-1),_i=qi(1);function ba(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&di(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ui(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Gi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ka(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new jt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ta(e,t,n,s):Oa(e,t,s):!0:!1}}function Ta(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Na(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let jn=null;const ge=function(n,e,t){let r=jn||(jn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ea=function(){jn=null},je=function(n,e,t,r){return t&&(Qi(n,e,t,r,-1)||Qi(n,e,t,r,1))},Da=/^(img|br|input|textarea|hr)$/i;function Qi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Da.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Aa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ia(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),ns=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!Zi&&"webkitFontSmoothing"in Zi.documentElement.style,Ba=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function za(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Fa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function rs(n,e,t){if(!_n(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?za(s):Fa(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function La(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:is(n.dom)}}function is(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Va({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ss(t,r==0?0:r-e)}function ss(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Wa(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:ls(t,i)}function Wa(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Kn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function ja(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ha(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function as(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ha(n,r,i,e))}l==null&&(l=Ja(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function _n(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Un(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Un(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function fs(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function _a(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return fs(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=cs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ua=/[\u0590-\u08ac]/;function Ga(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ua.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:fs(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let us=null,ds=null,hs=!1;function Ya(n,e,t){return us==e&&ds==t?hs:(us=e,ds=t,hs=t=="up"||t=="down"?_a(n,e,t):Ga(n,e,t))}const te=0,ps=1,He=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ys){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ms&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?He:ps,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?He:se}r=o}this.dirty=He}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?He:ps;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Xa extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Yn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=xs(f,r,t),c?a=new Qa(e,t,r,i,f,u||null,d,c):t.isText?new en(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&tn(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new ec(this,o&&o.node,e);rc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==He)&&(o&&this.protectLocalComposition(e,o),bs(this.contentDOM,this.children,e),at&&ic(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=sc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Xa(this,s,t,i);e.input.compositionNodes.push(o),this.children=Yn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(tn(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ks(this.dom,this.nodeDOM,Gn(this.outerDeco,this.node,t),Gn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function gs(n,e,t,r,i){xs(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class en extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new en(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ys extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Qa extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function bs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function nc(n,e){return n.type.side-e.type.side}function rc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ic(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function sc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Yn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Xn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Zt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&va(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Ms(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function lc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Os(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ns(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ns(n)}function Ns(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Zn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Es(n){return n.editable&&!n.hasFocus()?!1:Ds(n)}function Ds(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function ac(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function er(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function As(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=er(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=er(n.state,e);return i?Ee(n,i):!1}}}function nn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?cc(n):fc(n)}function cc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Is(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=nn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?tr(n,t,r):i&&tr(n,i,s)}function fc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=nn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function vs(n,e){let t=n.state.doc.resolve(e);if(!(V||ns)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Rs(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=er(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Ps(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Bs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function hc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Bs(n,r,"true"),setTimeout(()=>Bs(n,r,"false"),20)}return!1}function pc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function mc(n,e){let t=e.keyCode,r=pc(e);if(t==8||ee&&t==72&&r=="c")return Ps(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Ps(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?vs(n,n.state.selection.from)=="ltr"?-1:1:-1;return As(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?vs(n,n.state.selection.from)=="ltr"?1:-1:1;return As(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Rs(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return hc(n)||Rs(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function nr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ws[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` `);return{dom:a,text:d,slice:e}}function zs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=Sc(t),wt&&Mc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!bc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Cc($s(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(kc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const bc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function kc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Ls(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Vs(o[o.length-1],s.length));let f=Fs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Fs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Ls(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function $s(n,e,t){return et})}return Dt.createHTML(n)}function Sc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ws[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=xc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const H={},K={},wc={touchstart:!0,touchmove:!0};class Tc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Oc(n){for(let e in H){let t=H[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Ec(n,r)&&!ir(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},wc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),rr(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Nc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function rr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>ir(n,r))})}function ir(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Ec(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Dc(n,e){!ir(n,e)&&H[e.type]&&(n.editable||!(e.type in K))&&H[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Ks(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||yc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Ks(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Ac(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function sr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Ic(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Rc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function vc(n,e,t,r,i){return sr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Rc(n,t):Ic(n,t))}function Pc(n,e,t,r){return sr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Bc(n,e,t,r){return sr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||zc(n,t,r)}function zc(n,e,t){if(t.button!=0)return!1;let r=Js(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new Lc(n,r)),!0):!1}function Js(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function or(n){return nn(n)}const qs=ee?"metaKey":"ctrlKey";H.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=or(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Ac(t,n.input.lastClick)&&!t[qs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Fc(n,o,t,!!r):(s=="doubleClick"?Pc:Bc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class Hs{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Fc extends Hs{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[qs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):vc(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Lc extends Hs{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Js(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),or(n),xe(n,"pointer")},H.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},H.contextmenu=n=>or(n);function Ks(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Vc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&ns&&$c(n)))n.markCursor=n.state.storedMarks||t.marks(),nn(n,!0),n.markCursor=null;else if(nn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}_s(n,Vc)};function $c(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,_s(n,20))};function _s(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nn(n),e))}function Us(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Wc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Ra(e.focusNode,e.focusOffset),r=va(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Us(n),e||n.docView&&n.docView.dirty){let t=Yn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function jc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=G&&we<15||at&&Fa<604;H.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=tr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):jc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Jc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function qc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?vt(n,r.value,null,i,e):vt(n,r.textContent,r.innerHTML,i,e)},50)}function vt(n,e,t,r,i){let s=zs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Jc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Gs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&vt(n,Gs(r),r.getData("text/html"),i,t)?t.preventDefault():qc(n,t)};class Ys{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Hc=ee?"altKey":"ctrlKey";function Xs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Hc]}H.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=tr(n,l);(!t.dataTransfer.files.length||!V||ts>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new Ys(f,Xs(n,t),o)},H.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Kc(n,e,n.dragging)}finally{n.dragging=null}};function Kc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=zs(n,Gs(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Xs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Zl(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Qn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}H.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},H.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},H.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)H[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Zs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Uc(l,n,e,t,i,s,o),f=sn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Zs(n,l,a+t);if(c){s=!0;let f=sn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Qs(s?eo(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function cr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const Gc={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Yc=G&&we<=11;class Xc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Qc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Xc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Yc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Gc)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Es(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Es(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||tf(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Zc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,nf(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:sf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const sf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},of=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function lf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Yn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let v=n.state.tr.setSelection(N);M=="pointer"?v.setMeta("pointer",!0):M=="key"&&v.scrollIntoView(),s&&v.setMeta("composition",s),n.dispatch(v)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=rf(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!of.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=so(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&cf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let v=so(n,N.doc,c.sel);v&&!(V&&n.composing&&v.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=af(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",v=>v(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function so(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Qn(n,e.resolve(t.anchor),e.resolve(t.head))}function af(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||fr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function ff(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class oo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Tc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(uo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=co(this),ao(this),this.nodeViews=fo(this),this.docView=gs(this.state.doc,lo(this),cr(this),this.dom,this),this.domObserver=new Qc(this,(r,i,s,o)=>lf(this,r,i,s,o)),this.domObserver.start(),Oc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&rr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(uo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Us(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=fo(this);df(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&rr(this),this.editable=co(this),ao(this);let a=cr(this),c=lo(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&$a(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&uf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Wc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=gs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&fc(this)&&p.delaySelUpdate())?ke(this,h):(Os(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Wa(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&rs(this,t.getBoundingClientRect(),e)}else rs(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return _a(this,e)}coordsAtPos(e,t=1){return cs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Qa(this,t||this.state,e)}pasteHTML(e,t){return vt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return vt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return tr(this,e)}destroy(){this.docView&&(Nc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],cr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Aa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Dc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Ba(this.dom.ownerDocument)==this.dom&&ef(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}oo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function lo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function ao(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function co(n){return!n.someProp("editable",e=>e(n.state)===!1)}function uf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function fo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function df(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function uo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},on={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},hf=typeof navigator<"u"&&/Mac/.test(navigator.platform),pf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),on[$]=String.fromCharCode($);for(var ur in Ie)on.hasOwnProperty(ur)||(on[ur]=Ie[ur]);function mf(n){var e=hf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||pf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?on:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const gf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),yf=typeof navigator<"u"&&/Win/.test(navigator.platform);function bf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=cl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:po({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const Mf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Cf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),wf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Tf=n=>e=>n(e),Of=()=>({state:n,dispatch:e})=>ji(n,e),Nf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Ef=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function q(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Df=n=>({tr:e,state:t,dispatch:r})=>{const i=q(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Af=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},If=n=>n.content?/^text(\*|\+)/.test(n.content):!1,mo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:mo(n,t,"left"),to:mo(e,t,"right")}),vf=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Rf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Pf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Bf=()=>({state:n,dispatch:e})=>Wi(n,e);function zf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ln(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:zf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function go(n,e,t={}){return n.find(r=>r.type===e&&ln(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function yo(n,e,t={}){return!!go(n,e,t)}function hr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!go([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&yo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Re(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=hr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},Lf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(an()||ko())&&r.dom.focus(),$f()&&!an()&&!ko()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!bo(t.state.selection))return o(),!0;const l=Vf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},jf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Jf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),xo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&xo(r)}return n};function cn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return xo(t)}function So(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(So(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Yr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(cn(n),t.parseOptions):he.fromSchema(a).parse(cn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(cn(n),t.parseOptions).content:s.parse(cn(n),t.parseOptions)}return dt("",e,t)}function Mo(n){return!("type"in n)}function Co(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const qf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Mo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):So(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&Co(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function wo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=wo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&Co(e,e.steps.length-1,-1)),!0):!1},Kf=()=>({state:n,dispatch:e})=>da(n,e),_f=()=>({state:n,dispatch:e})=>ha(n,e),Uf=()=>({state:n,dispatch:e})=>Pi(n,e),Gf=()=>({state:n,dispatch:e})=>Li(n,e),Yf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Xf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ut(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Qf=()=>({state:n,dispatch:e})=>fa(n,e),Zf=()=>({state:n,dispatch:e})=>ua(n,e);function To(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function eu(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=eu(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function pr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?q(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>ln(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const nu=(n,e={})=>({state:t,dispatch:r})=>pr(t,q(n,t.schema),e)?pa(t,r):!1,ru=()=>({state:n,dispatch:e})=>Ji(n,e),iu=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Oa(r)(e,t)},su=()=>({state:n,dispatch:e})=>$i(n,e);function Oo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function No(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const ou=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,No(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(No(d.attrs,e))))})})}),a},lu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),au=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},cu=()=>({state:n,dispatch:e})=>zi(n,e),fu=()=>({state:n,dispatch:e})=>Vi(n,e),uu=()=>({state:n,dispatch:e})=>ya(n,e),du=()=>({state:n,dispatch:e})=>_i(n,e),hu=()=>({state:n,dispatch:e})=>Ki(n,e);function pu(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const mu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=pu(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Mo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function gu(n,e){const t=Re(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function yu(n,e){const t=new Ci(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function bu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function mr(n){return e=>bu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Eo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Eo(t())]:e}).flat(10)}function ku(n){return typeof n=="function"}function D(n,e=void 0,...t){return ku(n)?e?n.bind(e)(...t):n(...t):n}function xu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function fn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function Su(n){const e=[],{nodeExtensions:t,markExtensions:r}=fn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function Mu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Do(n){const e=[],t=Mu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Do(r[i]),...Do(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Ao(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>un(t,r),{})}function Cu(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Io(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Cu(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Ro(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&xu(t)?!1:t!=null))}function vo(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function wu(n,e){var t;const r=Su(n),{nodeExtensions:i,markExtensions:s}=fn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ro({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(vo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Io(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Ao(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=Ro({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(vo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Io(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Ao(m,f)})),[c.name,d]}));return new Yr({topNode:o,nodes:l,marks:a})}function Tu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Ou(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Eu(n,e){return wu(Nu(n),e)}function Du(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` +`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=kc(t),wt&&xc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!gc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Sc($s(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(yc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const gc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function yc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Ls(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Vs(o[o.length-1],s.length));let f=Fs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Fs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Ls(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function $s(n,e,t){return et})}return Dt.createHTML(n)}function kc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ws[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=bc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},Mc={touchstart:!0,touchmove:!0};class Cc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function wc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Oc(n,r)&&!sr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},Mc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),ir(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Tc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function ir(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>sr(n,r))})}function sr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Oc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Nc(n,e){!sr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Ks(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||mc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Ks(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Ec(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function or(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Dc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Ac(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ic(n,e,t,r,i){return or(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Ac(n,t):Dc(n,t))}function vc(n,e,t,r){return or(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Rc(n,e,t,r){return or(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Pc(n,t,r)}function Pc(n,e,t){if(t.button!=0)return!1;let r=Js(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new zc(n,r)),!0):!1}function Js(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function lr(n){return rn(n)}const Hs=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=lr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Ec(t,n.input.lastClick)&&!t[Hs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Bc(n,o,t,!!r):(s=="doubleClick"?vc:Rc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class qs{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Bc extends qs{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Hs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):Ic(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class zc extends qs{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Js(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),lr(n),xe(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},q.contextmenu=n=>lr(n);function Ks(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Fc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&ns&&Lc(n)))n.markCursor=n.state.storedMarks||t.marks(),rn(n,!0),n.markCursor=null;else if(rn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}_s(n,Fc)};function Lc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,_s(n,20))};function _s(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>rn(n),e))}function Us(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Vc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Aa(e.focusNode,e.focusOffset),r=Ia(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function rn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Us(n),e||n.docView&&n.docView.dirty){let t=Xn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function $c(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const vt=G&&we<15||at&&Ba<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=vt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=nr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):$c(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Wc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function jc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Rt(n,r.value,null,i,e):Rt(n,r.textContent,r.innerHTML,i,e)},50)}function Rt(n,e,t,r,i){let s=zs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Wc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Gs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=vt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Rt(n,Gs(r),r.getData("text/html"),i,t)?t.preventDefault():jc(n,t)};class Ys{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Jc=ee?"altKey":"ctrlKey";function Xs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Jc]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=nr(n,l);(!t.dataTransfer.files.length||!V||ts>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(vt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",vt||t.dataTransfer.setData("text/plain",c),n.dragging=new Ys(f,Xs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Hc(n,e,n.dragging)}finally{n.dragging=null}};function Hc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=zs(n,Gs(e.dataTransfer),vt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Xs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Xl(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Zn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class sn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof sn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Zs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Kc(l,n,e,t,i,s,o),f=on(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Zs(n,l,a+t);if(c){s=!0;let f=on(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Qs(s?eo(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function fr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const _c={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Uc=G&&we<=11;class Gc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Yc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Gc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Uc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,_c)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Es(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Es(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Zc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Xc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,ef(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:nf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const nf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},rf=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function sf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Xn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let R=n.state.tr.setSelection(N);M=="pointer"?R.setMeta("pointer",!0):M=="key"&&R.scrollIntoView(),s&&R.setMeta("composition",s),n.dispatch(R)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=tf(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!rf.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=so(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&lf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let R=so(n,N.doc,c.sel);R&&!(V&&n.composing&&R.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=of(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",R=>R(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function so(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Zn(n,e.resolve(t.anchor),e.resolve(t.head))}function of(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||ur(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function af(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class oo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Cc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(uo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=co(this),ao(this),this.nodeViews=fo(this),this.docView=gs(this.state.doc,lo(this),fr(this),this.dom,this),this.domObserver=new Yc(this,(r,i,s,o)=>sf(this,r,i,s,o)),this.domObserver.start(),wc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ir(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(uo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Us(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=fo(this);ff(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&ir(this),this.editable=co(this),ao(this);let a=fr(this),c=lo(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&La(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&cf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Vc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=gs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ac(this)&&p.delaySelUpdate())?ke(this,h):(Os(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Va(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&rs(this,t.getBoundingClientRect(),e)}else rs(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return qa(this,e)}coordsAtPos(e,t=1){return cs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ya(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return nr(this,e)}destroy(){this.docView&&(Tc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],fr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ea())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Nc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Ra(this.dom.ownerDocument)==this.dom&&Qc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}oo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function lo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function ao(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function co(n){return!n.someProp("editable",e=>e(n.state)===!1)}function cf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function fo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function ff(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function uo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},ln={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uf=typeof navigator<"u"&&/Mac/.test(navigator.platform),df=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),ln[$]=String.fromCharCode($);for(var dr in Ie)ln.hasOwnProperty(dr)||(ln[dr]=Ie[dr]);function hf(n){var e=uf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||df&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ln:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const pf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),mf=typeof navigator<"u"&&/Win/.test(navigator.platform);function gf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=ll.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:po({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const xf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Sf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),Mf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Cf=n=>e=>n(e),wf=()=>({state:n,dispatch:e})=>ji(n,e),Tf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Of=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Nf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Ef=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Df=n=>n.content?/^text(\*|\+)/.test(n.content):!1,mo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:mo(n,t,"left"),to:mo(e,t,"right")}),If=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Af(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},vf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Rf=()=>({state:n,dispatch:e})=>Wi(n,e);function Pf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function an(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Pf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function go(n,e,t={}){return n.find(r=>r.type===e&&an(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function yo(n,e,t={}){return!!go(n,e,t)}function pr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!go([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&yo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=ve(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=pr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},zf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(cn()||ko())&&r.dom.focus(),Lf()&&!cn()&&!ko()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!bo(t.state.selection))return o(),!0;const l=Ff(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},$f=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Wf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),xo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&xo(r)}return n};function fn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return xo(t)}function So(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(So(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Yr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(fn(n),t.parseOptions):he.fromSchema(a).parse(fn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(fn(n),t.parseOptions).content:s.parse(fn(n),t.parseOptions)}return dt("",e,t)}function Mo(n){return!("type"in n)}function Co(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const jf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Mo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):So(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&Co(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function wo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=wo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&Co(e,e.steps.length-1,-1)),!0):!1},Hf=()=>({state:n,dispatch:e})=>fa(n,e),qf=()=>({state:n,dispatch:e})=>ua(n,e),Kf=()=>({state:n,dispatch:e})=>Pi(n,e),_f=()=>({state:n,dispatch:e})=>Li(n,e),Uf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Gt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Gf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Gt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Yf=()=>({state:n,dispatch:e})=>aa(n,e),Xf=()=>({state:n,dispatch:e})=>ca(n,e);function To(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Qf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Qf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function mr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>an(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const eu=(n,e={})=>({state:t,dispatch:r})=>mr(t,H(n,t.schema),e)?da(t,r):!1,tu=()=>({state:n,dispatch:e})=>Ji(n,e),nu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)},ru=()=>({state:n,dispatch:e})=>$i(n,e);function Oo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function No(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const iu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=ve(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,No(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(No(d.attrs,e))))})})}),a},su=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ou=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},lu=()=>({state:n,dispatch:e})=>zi(n,e),au=()=>({state:n,dispatch:e})=>Vi(n,e),cu=()=>({state:n,dispatch:e})=>ma(n,e),fu=()=>({state:n,dispatch:e})=>_i(n,e),uu=()=>({state:n,dispatch:e})=>Ki(n,e);function du(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const hu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=du(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Mo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function pu(n,e){const t=ve(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function mu(n,e){const t=new Ci(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function gu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function gr(n){return e=>gu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Eo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Eo(t())]:e}).flat(10)}function yu(n){return typeof n=="function"}function D(n,e=void 0,...t){return yu(n)?e?n.bind(e)(...t):n(...t):n}function bu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function un(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function ku(n){const e=[],{nodeExtensions:t,markExtensions:r}=un(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function xu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Do(n){const e=[],t=xu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Do(r[i]),...Do(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Ao(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>dn(t,r),{})}function Su(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Io(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Su(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function vo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&bu(t)?!1:t!=null))}function Ro(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Mu(n,e){var t;const r=ku(n),{nodeExtensions:i,markExtensions:s}=un(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Ro))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Io(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Ao(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Ro))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Io(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Ao(m,f)})),[c.name,d]}));return new Yr({topNode:o,nodes:l,marks:a})}function Cu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function wu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Ou(n,e){return Mu(Tu(n),e)}function Nu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Au(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Iu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Ru(n){const e=Iu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function vu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Ru(r)}function Po(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=hr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function dn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Pu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Re(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>ln(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>ln(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function gr(n,e){const{nodeExtensions:t}=fn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Bo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Bo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Bu(n,e,t){const{selection:r}=e;let i=null;if(bo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const zu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Re(n,r.schema);if(i)if(o){const c=gu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Bu(r,t,a)},Fu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Lu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=q(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ui(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ui(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},$u=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Wu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},ju=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Da(r)(e,t)};function zo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Ju=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=dn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&zo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:wo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&zo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},qu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=q(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=v+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...dn(u,f.type.name,f.attrs),...e},m={...dn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Fo(n){return!n||n==="1"?null:n}function Lo(n,e){return Fo(n)===Fo(e)}const yr=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},br=(n,e)=>{const t=mr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Hu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Ku=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=q(n,o.schema),p=q(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=mr(et=>gr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,v=ne&&N&&gr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??v,Hd=!!_&&w.depth>=1&&w.depth-_.depth<=1,ll=!!v;if((Hd||ll)&&Ze){if(Ze.node.type===h)return ne&&ll?a().command(({tr:et,dispatch:Sn})=>{const Mn=Hu(et);return Mn?(et.setSelection(Mn),Sn&&Sn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(gr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>yr(s,h)).command(()=>br(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Sn=A.filter(Mn=>d.includes(Mn.type.name));return s.ensureMarks(Sn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>yr(s,h)).command(()=>br(s,h)).run()},_u=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Re(n,r.schema);return Pu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Uu=(n,e,t={})=>({state:r,commands:i})=>{const s=q(n,r.schema),o=q(e,r.schema),l=pr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Gu=(n,e={})=>({state:t,commands:r})=>{const i=q(n,t.schema);return pr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Yu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Xu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Qu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Re(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=hr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Zu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},ed=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},td=new ie("__tiptap_decorations__"),nd=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(td,{type:"force",name:n}),!0),rd=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return xa(i,e)(t,r)},id=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Ca(i,e)(t,r)};var sd=hl({blur:()=>Mf,clearContent:()=>Cf,clearNodes:()=>wf,command:()=>Tf,createParagraphNear:()=>Of,cut:()=>Nf,deleteCurrentNode:()=>Ef,deleteNode:()=>Df,deleteRange:()=>Af,deleteSelection:()=>vf,enter:()=>Pf,exitCode:()=>Bf,extendMarkRange:()=>Ff,first:()=>Lf,focus:()=>Wf,forEach:()=>jf,insertContent:()=>Jf,insertContentAt:()=>qf,insertDefaultBlock:()=>Hf,joinBackward:()=>Uf,joinDown:()=>_f,joinForward:()=>Gf,joinItemBackward:()=>Yf,joinItemForward:()=>Xf,joinTextblockBackward:()=>Qf,joinTextblockForward:()=>Zf,joinUp:()=>Kf,keyboardShortcut:()=>tu,lift:()=>nu,liftEmptyBlock:()=>ru,liftListItem:()=>iu,newlineInCode:()=>su,resetAttributes:()=>ou,scrollIntoView:()=>lu,selectAll:()=>au,selectNodeBackward:()=>cu,selectNodeForward:()=>fu,selectParentNode:()=>uu,selectTextblockEnd:()=>du,selectTextblockStart:()=>hu,setContent:()=>mu,setMark:()=>zu,setMeta:()=>Fu,setNode:()=>Lu,setNodeSelection:()=>Vu,setTextDirection:()=>$u,setTextSelection:()=>Wu,sinkListItem:()=>ju,splitBlock:()=>Ju,splitListItem:()=>qu,toggleList:()=>Ku,toggleMark:()=>_u,toggleNode:()=>Uu,toggleWrap:()=>Gu,undoInputRule:()=>Yu,unsetAllMarks:()=>Xu,unsetMark:()=>Qu,unsetTextDirection:()=>Zu,updateAttributes:()=>ed,updateDecorations:()=>nd,wrapIn:()=>rd,wrapInList:()=>id});typeof process<"u"&&process.env.NODE_ENV;function od(n){return Object.prototype.toString.call(n).slice(8,-1)}function hn(n){return od(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Vo(n,e){const t={...n};return hn(n)&&hn(e)&&Object.keys(e).forEach(r=>{hn(e[r])&&hn(n[r])?t[r]=Vo(n[r],e[r]):t[r]=e[r]}),t}var ld=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},kr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Vo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},pn=class fl extends kr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new fl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},ad=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class ul extends kr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new ul(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Au(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Du(r,{from:a.pos,to:c.pos},l)).join(o??` +`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Eu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Du(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Au(n){const e=Du(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Iu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Au(r)}function Po(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=pr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function hn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function vu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?ve(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>an(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>an(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function yr(n,e){const{nodeExtensions:t}=un(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Bo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Bo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Ru(n,e,t){const{selection:r}=e;let i=null;if(bo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Pu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=ve(n,r.schema);if(i)if(o){const c=pu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Ru(r,t,a)},Bu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),zu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ui(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ui(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Fu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Lu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},$u=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Na(r)(e,t)};function zo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Wu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=hn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&zo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:wo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&zo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},ju=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=R+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...hn(u,f.type.name,f.attrs),...e},m={...hn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Fo(n){return!n||n==="1"?null:n}function Lo(n,e){return Fo(n)===Fo(e)}const br=(n,e)=>{const t=gr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},kr=(n,e)=>{const t=gr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Ju(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Hu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=gr(et=>yr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,R=ne&&N&&yr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??R,qd=!!_&&w.depth>=1&&w.depth-_.depth<=1,sl=!!R;if((qd||sl)&&Ze){if(Ze.node.type===h)return ne&&sl?a().command(({tr:et,dispatch:Mn})=>{const Cn=Ju(et);return Cn?(et.setSelection(Cn),Mn&&Mn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(yr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>br(s,h)).command(()=>kr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>br(s,h)).command(()=>kr(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Mn=A.filter(Cn=>d.includes(Cn.type.name));return s.ensureMarks(Mn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>br(s,h)).command(()=>kr(s,h)).run()},qu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=ve(n,r.schema);return vu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ku=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=mr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},_u=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return mr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Uu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Gu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Yu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=ve(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=pr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Xu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Qu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=ve(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Zu=new ie("__tiptap_decorations__"),ed=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Zu,{type:"force",name:n}),!0),td=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)},nd=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return Sa(i,e)(t,r)};var rd=ul({blur:()=>xf,clearContent:()=>Sf,clearNodes:()=>Mf,command:()=>Cf,createParagraphNear:()=>wf,cut:()=>Tf,deleteCurrentNode:()=>Of,deleteNode:()=>Nf,deleteRange:()=>Ef,deleteSelection:()=>If,enter:()=>vf,exitCode:()=>Rf,extendMarkRange:()=>Bf,first:()=>zf,focus:()=>Vf,forEach:()=>$f,insertContent:()=>Wf,insertContentAt:()=>jf,insertDefaultBlock:()=>Jf,joinBackward:()=>Kf,joinDown:()=>qf,joinForward:()=>_f,joinItemBackward:()=>Uf,joinItemForward:()=>Gf,joinTextblockBackward:()=>Yf,joinTextblockForward:()=>Xf,joinUp:()=>Hf,keyboardShortcut:()=>Zf,lift:()=>eu,liftEmptyBlock:()=>tu,liftListItem:()=>nu,newlineInCode:()=>ru,resetAttributes:()=>iu,scrollIntoView:()=>su,selectAll:()=>ou,selectNodeBackward:()=>lu,selectNodeForward:()=>au,selectParentNode:()=>cu,selectTextblockEnd:()=>fu,selectTextblockStart:()=>uu,setContent:()=>hu,setMark:()=>Pu,setMeta:()=>Bu,setNode:()=>zu,setNodeSelection:()=>Fu,setTextDirection:()=>Lu,setTextSelection:()=>Vu,sinkListItem:()=>$u,splitBlock:()=>Wu,splitListItem:()=>ju,toggleList:()=>Hu,toggleMark:()=>qu,toggleNode:()=>Ku,toggleWrap:()=>_u,undoInputRule:()=>Uu,unsetAllMarks:()=>Gu,unsetMark:()=>Yu,unsetTextDirection:()=>Xu,updateAttributes:()=>Qu,updateDecorations:()=>ed,wrapIn:()=>td,wrapInList:()=>nd});typeof process<"u"&&process.env.NODE_ENV;function id(n){return Object.prototype.toString.call(n).slice(8,-1)}function pn(n){return id(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Vo(n,e){const t={...n};return pn(n)&&pn(e)&&Object.keys(e).forEach(r=>{pn(e[r])&&pn(n[r])?t[r]=Vo(n[r],e[r]):t[r]=e[r]}),t}var sd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},xr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Vo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},mn=class al extends xr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new al(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},od=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class cl extends xr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new cl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Eu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Nu(r,{from:a.pos,to:c.pos},l)).join(o??` -`)}}})]}}),fe.create({name:"commands",addCommands(){return{...sd}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=yu(n.before,[n,...e]);vu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const cd=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:cd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return an()||To()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Bo(t.doc))return;const f=t.tr,u=po({state:t,transaction:f}),{commands:d}=new Sf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=fn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new ld({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Po(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var $o=class dl extends kr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new dl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new ad({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Po(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var fd=$o.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`)}}})]}}),fe.create({name:"commands",addCommands(){return{...rd}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=mu(n.before,[n,...e]);Iu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const ld=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:ld,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return cn()||To()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Bo(t.doc))return;const f=t.tr,u=po({state:t,transaction:f}),{commands:d}=new kf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=un(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new sd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Po(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var $o=class fl extends xr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new fl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new od({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Po(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var ad=$o.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""}),ud=$o.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Wo=new WeakSet,jo=new WeakSet;function Ge(n){const e=n;return Wo.add(e),e}function xr(n){return Array.isArray(n)&&Wo.has(n)}function Jo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&jo.has(e)&&!xr(e)?Jo(e):[e])}function dd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!xr(i)&&!jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(xr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=Jo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const qo=(n,e)=>dd(n,e),hd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,pd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,md=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,gd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var yd=pn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return qo("strong",{...un(this.options.HTMLAttributes,n),children:qo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:hd,type:this.type}),Bt({find:md,type:this.type})]},addPasteRules(){return[zt({find:pd,type:this.type}),zt({find:gd,type:this.type})]}});const bd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,kd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,xd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Sd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var Md=pn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",un(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:bd,type:this.type}),Bt({find:xd,type:this.type})]},addPasteRules(){return[zt({find:kd,type:this.type}),zt({find:Sd,type:this.type})]}});const Cd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},wd=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Td=pn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",un(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Cd,type:this.type})]},addPasteRules(){return[zt({find:wd,type:this.type})]}}),mn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Ho(e):z.empty};var Ho=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=mn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=mn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Ho([]);var Od=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Nd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fDd&&(l=Ed(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dNd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Ed(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class ve{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Dd=20;function Ad(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(vd)&&(n=new ve(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new ve(n.done.addTransform(t,void 0,r,gn(e)),n.undone,Ko(t.mapping.maps),n.prevTime,n.prevComposition):new ve(n.done,n.undone.addTransform(t,void 0,r,gn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Id(t,n.prevRanges)),c=o?Sr(n.prevRanges,t.mapping):Ko(t.mapping.maps);return new ve(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,gn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ve(n.done.rebased(t,s),n.undone.rebased(t,s),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ve(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Sr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Id(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ko(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Sr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Rd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Go=Uo(!1,!0),Cr=Uo(!0,!0);function Bd(n,e){for(const t of n)t.seq===e&&(t.acked=!0)}function zd(n){if(!n.url||!n.hash||n.len<0)return null;const e=[...n.spans];if(!e.some(r=>!r.acked))return null;const t=e.sort((r,i)=>r.start-i.start).map(({start:r,end:i,html:s})=>({start:r,end:i,html:s}));return JSON.stringify({src_hash:n.hash,src_len:n.len,patches:t})}const Xe="data-bd-src",Fd=pn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),yn=Eu([fd.extend({content:"inline*"}),ud,yd,Md,Td,Fd]),Ld=he.fromSchema(yn),Vd=Ve.fromSchema(yn),$d={preserveWhitespace:"full"};function Yo(n){return Ld.parse(n,$d)}function Xo(n){const e=document.createElement("div");return e.appendChild(Vd.serializeFragment(n.content)),e.innerHTML}function Wd(n){try{return Xo(Yo(n))===n.innerHTML}catch{return!1}}function Qo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const bn=n=>parent.postMessage(n,"*"),wr=new WeakMap;function Zo(n){let e=wr.get(n);return e===void 0&&(e=Wd(n),wr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Tr="",Qe=!1,jd=0,Or="";const kn=new Map;function el(){return Y?Xo(Y.state.doc):null}function xn(){if(!Pe||!de)return;const n=el();if(n===null||n===Tr)return;Tr=n;const e=++jd;kn.set(de.start+","+de.end,{start:de.start,end:de.end,html:n,seq:e,acked:!1}),bn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Ft(){if(!Y)return;xn();const n=Pe,e=el();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),wr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Jd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function qd(n,e,t){if(Pe===n)return;Ft();const r=Qo(n);if(!r)return;Pe=n,de=r,Tr=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Yo(n),plugins:[Pd(),ho({"Mod-b":Gi(yn.marks.bold),"Mod-i":Gi(yn.marks.italic),"Mod-z":Go,"Mod-y":Cr,"Shift-Mod-z":Cr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Ft(),!0)}),ho(Ma)]});Y=new oo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&xn())}}),Y.focus(),e!==void 0&&t!==void 0&&Jd(Y,e,t)}function tl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=tl(n.target);if(!e){Ft();return}Zo(e)&&qd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=tl(n.target);e&&Zo(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(bn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const nl=document.createElement("style");nl.textContent=` +`):""}),cd=$o.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Wo=new WeakSet,jo=new WeakSet;function Ge(n){const e=n;return Wo.add(e),e}function Sr(n){return Array.isArray(n)&&Wo.has(n)}function Jo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&jo.has(e)&&!Sr(e)?Jo(e):[e])}function fd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!Sr(i)&&!jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(Sr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=Jo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const Ho=(n,e)=>fd(n,e),ud=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,dd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,hd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,pd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var md=mn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Ho("strong",{...dn(this.options.HTMLAttributes,n),children:Ho("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ud,type:this.type}),Bt({find:hd,type:this.type})]},addPasteRules(){return[zt({find:dd,type:this.type}),zt({find:pd,type:this.type})]}});const gd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,yd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,bd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,kd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var xd=mn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",dn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:gd,type:this.type}),Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:yd,type:this.type}),zt({find:kd,type:this.type})]}});const Sd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},Md=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Cd=mn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",dn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Sd,type:this.type})]},addPasteRules(){return[zt({find:Md,type:this.type})]}}),gn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new qo(e):z.empty};var qo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=gn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=gn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new qo([]);var wd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Td=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fNd&&(l=Od(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dTd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Od(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Nd=20;function Ed(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(Id)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new Re(n.done.addTransform(t,void 0,r,yn(e)),n.undone,Ko(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,yn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Dd(t,n.prevRanges)),c=o?Mr(n.prevRanges,t.mapping):Ko(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,yn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),Mr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Mr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Dd(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ko(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Mr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Ad(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Go=Uo(!1,!0),wr=Uo(!0,!0);function Rd(n,e){for(const t of n){const r=t.history?.get(e);r!==void 0?(t.ackedHtml=r,t.seq===e&&(t.acked=!0)):t.seq===e&&(t.ackedHtml=t.html,t.acked=!0)}}function Pd(n){const e=[...n];return e.some(t=>!t.acked)?e.sort((t,r)=>t.start-r.start).map(({start:t,end:r,html:i,ackedHtml:s})=>({start:t,end:r,html:i,...s!==void 0?{ackedHtml:s}:{}})):null}const Xe="data-bd-src",Bd=mn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),bn=Ou([ad.extend({content:"inline*"}),cd,md,xd,Cd,Bd]),zd=he.fromSchema(bn),Fd=Ve.fromSchema(bn),Ld={preserveWhitespace:"full"};function Yo(n){return zd.parse(n,Ld)}function Xo(n){const e=document.createElement("div");return e.appendChild(Fd.serializeFragment(n.content)),e.innerHTML}function Vd(n){try{return Xo(Yo(n))===n.innerHTML}catch{return!1}}function Qo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const kn=n=>parent.postMessage(n,"*"),Tr=new WeakMap;function Zo(n){let e=Tr.get(n);return e===void 0&&(e=Vd(n),Tr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Or="",Qe=!1,$d=0,xn=null;const Ft=new Map;function el(){return Y?Xo(Y.state.doc):null}function Sn(){if(!Pe||!de)return;const n=el();if(n===null||n===Or)return;Or=n;const e=++$d,t=de.start+","+de.end,r=Ft.get(t),i=r?.history??new Map;i.set(e,n),Ft.set(t,{start:de.start,end:de.end,html:n,seq:e,acked:!1,ackedHtml:r?.ackedHtml,history:i}),kn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Lt(){if(!Y)return;Sn();const n=Pe,e=el();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Tr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Wd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function jd(n,e,t){if(Pe===n)return;Lt();const r=Qo(n);if(!r)return;Pe=n,de=r,Or=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Yo(n),plugins:[vd(),ho({"Mod-b":Gi(bn.marks.bold),"Mod-i":Gi(bn.marks.italic),"Mod-z":Go,"Mod-y":wr,"Shift-Mod-z":wr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Lt(),!0)}),ho(xa)]});Y=new oo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&Sn())}}),Y.focus(),e!==void 0&&t!==void 0&&Wd(Y,e,t)}function tl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=tl(n.target);if(!e){Lt();return}Zo(e)&&jd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=tl(n.target);e&&Zo(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(kn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const nl=document.createElement("style");nl.textContent=` [${Xe}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } [${Xe}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } [${Xe}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } [${Xe}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } -`,document.head.appendChild(nl);const rl=document.currentScript??document.querySelector("script[data-src-hash]"),il=rl?.dataset.srcHash??"",sl=Number(rl?.dataset.srcLen??"-1");bn({type:"bd-edit:ready",hash:il,len:sl,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Qo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function ol(){const n=zd({url:Or,hash:il,len:sl,spans:kn.values()});if(n===null)return;for(const t of kn.values())t.acked=!0;const e=new TextEncoder().encode(n).byteLength<=6e4;fetch(Or,{method:"POST",mode:"no-cors",credentials:"omit",keepalive:e,body:n}).catch(()=>{})}window.addEventListener("beforeunload",()=>{Ft(),ol()}),window.addEventListener("pagehide",n=>{n.persisted?xn():Ft(),ol()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){Bd(kn.values(),e.seq);return}if(e.type==="bd-edit:beacon"&&typeof e.url=="string"&&e.url.startsWith("/")){try{Or=new URL(e.url,window.location.href).href}catch{}return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){xn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),bn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); +`,document.head.appendChild(nl);const rl=document.currentScript??document.querySelector("script[data-src-hash]"),Jd=rl?.dataset.srcHash??"",Hd=Number(rl?.dataset.srcLen??"-1");kn({type:"bd-edit:ready",hash:Jd,len:Hd,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Qo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function il(){if(!xn)return;const n=Pd(Ft.values());if(n!==null){for(const e of Ft.values())e.acked=!0;xn.postMessage({type:"bd-edit:exit",patches:n})}}window.addEventListener("beforeunload",()=>{Lt(),il()}),window.addEventListener("pagehide",n=>{n.persisted?Sn():Lt(),il()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){Rd(Ft.values(),e.seq);return}if(e.type==="bd-edit:port"&&n.ports[0]){xn?.close(),xn=n.ports[0],document.documentElement.setAttribute("data-bd-exit","ready");return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){Sn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),kn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); From 60d1a241c0fce187ded80b01dc61277baa7a4463 Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 02:20:32 +0900 Subject: [PATCH 20/34] fix(webapp): gate VisualEdit exit worker on trusted parent interaction and unload --- CHANGELOG.md | 2 +- .../frontend/src/components/VisualEdit.tsx | 25 ++++++-- .../frontend/src/lib/editexit.worker.ts | 62 ++++++++++++++++--- ...{Editor-CsLWwTRs.js => Editor-CeIX9UEc.js} | 2 +- .../static/assets/VisualEdit-CGKGr6GV.js | 1 - .../static/assets/VisualEdit-D6HKLJJk.js | 1 + .../static/assets/editexit.worker-CfTN8vfX.js | 11 ---- .../static/assets/editexit.worker-D_nakb5p.js | 11 ++++ .../webapp/static/assets/index-BLk9nKdF.css | 1 - .../{index-DyFnf9EY.js => index-Co6en_o0.js} | 4 +- .../webapp/static/assets/index-DeicSyxP.css | 1 + ...ile-CtVUr4nt.js => sharedfile-CR4ZqPh0.js} | 2 +- internal/webapp/static/index.html | 4 +- 13 files changed, 95 insertions(+), 32 deletions(-) rename internal/webapp/static/assets/{Editor-CsLWwTRs.js => Editor-CeIX9UEc.js} (99%) delete mode 100644 internal/webapp/static/assets/VisualEdit-CGKGr6GV.js create mode 100644 internal/webapp/static/assets/VisualEdit-D6HKLJJk.js delete mode 100644 internal/webapp/static/assets/editexit.worker-CfTN8vfX.js create mode 100644 internal/webapp/static/assets/editexit.worker-D_nakb5p.js delete mode 100644 internal/webapp/static/assets/index-BLk9nKdF.css rename internal/webapp/static/assets/{index-DyFnf9EY.js => index-Co6en_o0.js} (99%) create mode 100644 internal/webapp/static/assets/index-DeicSyxP.css rename internal/webapp/static/assets/{sharedfile-CtVUr4nt.js => sharedfile-CR4ZqPh0.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9bc4849..3fa32399 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **Concurrent text edits merge per hunk and per word.** `internal/textmerge` and its browser port `frontend/src/lib/merge3.ts` diff each side with Myers O(ND), so edits in different parts of a file merge as separate hunks (diff3). Two edits to the same line merge word by word when they change different words, and insertions at the same point are ordered by content, so `merge(base, a, b)` equals `merge(base, b, a)`. The merge now runs in four places: `PUT /api/p//upload/content` with a stale `If-Match` merges base, head and incoming bytes instead of returning `409` (text only, up to 4 MiB; `X-Bdrive-No-Merge` opts out); MCP `write` and `edit` given an outdated sha merge from that version; live room reconciliation; and `internal/syncer` before it writes a conflict copy. Two different rewrites of the same lines or words still conflict. - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. -- **`VisualEdit` saves unacknowledged iframe edits through a same-origin exit worker when the tab closes.** The editing iframe stays `sandbox="allow-scripts"` and is never given a session, token or URL. `VisualEdit` starts a dedicated Web Worker on the app's origin (`editexit.worker.ts`), keeps it current with the rendered source, the anchored ranges and what the file and document hold after every save, and hands the iframe only one end of a `MessageChannel` (`bd-edit:port`). The app acknowledges each numbered patch it applies (`bd-edit:ack`); when the iframe unloads with an unacknowledged patch, it posts its edited spans to the worker (`bd-edit:exit`). The worker splices only anchored, script-free spans onto the render, merges the result three ways with the current document, and saves it with the app's own cookie: `POST /api/p//ycollab/sync` on a hub or `bdrive desktop`, or `PUT upload/content` on the latest `If-Match` in a plain folder, so it also works after earlier auto-saves. A same-word clash parks a conflict copy, an unconfirmed sharp shrink is not sent, and delivery is still subject to the browser's teardown limits (`keepalive` up to 60,000 bytes). +- **`VisualEdit` flushes unacknowledged iframe edits through a same-origin exit worker when the tab closes.** The editing iframe stays `sandbox="allow-scripts"` and is never given a session, token or URL. `VisualEdit` starts a dedicated Web Worker on the app's origin (`editexit.worker.ts`), keeps it current with the rendered source, the anchored ranges and what the file and document hold after every save, and hands the iframe only one end of a `MessageChannel` (`bd-edit:port`). The app acknowledges each numbered patch it applies (`bd-edit:ack`); when the iframe unloads with an unacknowledged patch, it posts its edited spans to the worker (`bd-edit:exit`). This exit save is best-effort and runs only once the worker has started and been armed with the anchored render. The worker splices only anchored, script-free spans onto the render, merges the result three ways with the current document, and saves it with the app's own cookie: `POST /api/p//ycollab/sync` on a hub or `bdrive desktop`, or `PUT upload/content` on the latest `If-Match` in a plain folder, so it also works after earlier auto-saves. A same-word clash parks a conflict copy, an unconfirmed sharp shrink is not sent, and delivery is still subject to the browser's teardown limits (`keepalive` up to 60,000 bytes). ## v0.18.9 — 2026-11-11 diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index dbee4bef..a111cc74 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -193,8 +193,19 @@ export function VisualEdit({ exitWorker = null; // no worker (a CSP, an old browser): no exit save, as before } let workerDisarmed = false; + let frameInteracted = false; let latestSavedText = seed.current; let latestBaseSha: string | undefined = shaRef.current; + const noteFrameInteraction = () => { + if (frameInteracted || document.activeElement !== frame.current) return; + frameInteracted = true; + if (exitWorker && !workerDisarmed) exitWorker.postMessage({ type: "interacted" }); + }; + const onParentUnload = () => { + noteFrameInteraction(); + if (!exitWorker || workerDisarmed || !frameInteracted) return; + exitWorker.postMessage({ type: "parent-unload" }); + }; const activeDocText = () => stageDoc ? stageDoc.getText("body").toString() : (fileRef.current?.collab.text.toString() ?? ""); const syncExitWorker = () => { @@ -234,6 +245,7 @@ export function VisualEdit({ savedText: latestSavedText, baseSha: latestBaseSha, docText: renderText, + interacted: frameInteracted, }, [mc.port1], ); @@ -509,6 +521,8 @@ export function VisualEdit({ } if (msg.type !== "bd-edit:patch") return; + noteFrameInteraction(); + if (!frameInteracted) return; if (!anchored) return anchorRanges().then(() => { if (!applyPatch(msg)) return; @@ -624,18 +638,21 @@ export function VisualEdit({ file.collab.text.observe(retry); window.addEventListener("message", onMessage); + window.addEventListener("blur", noteFrameInteraction); + window.addEventListener("beforeunload", onParentUnload); + window.addEventListener("pagehide", onParentUnload); return () => { if (handle?.current === exposed) handle.current = null; + window.removeEventListener("blur", noteFrameInteraction); + window.removeEventListener("beforeunload", onParentUnload); + window.removeEventListener("pagehide", onParentUnload); + onParentUnload(); frameReady = false; channel.close(); - // The exit worker stays armed: a tab closing goes through here too, and - // the frame's last patch may yet arrive at it. Disarmed below, once the - // editor is really gone and nothing more can come. clearTimeout(retryTimer); clearTimeout(stuckTimer); clearTimeout(stageTimer); file.collab.text.unobserve(retry); - /* Torn down a beat later, so a patch already in flight still lands. Defensive, and honestly so: with the iframe's debounce gone a patch is diff --git a/internal/webapp/frontend/src/lib/editexit.worker.ts b/internal/webapp/frontend/src/lib/editexit.worker.ts index 9a212075..cbbdc6f9 100644 --- a/internal/webapp/frontend/src/lib/editexit.worker.ts +++ b/internal/webapp/frontend/src/lib/editexit.worker.ts @@ -27,24 +27,38 @@ type Arm = { savedText: string; baseSha?: string; docText: string; + interacted?: boolean; }; type Sync = { type: "sync"; savedText?: string; baseSha?: string; hasBaseSha?: boolean; docText?: string }; -type FromApp = Arm | Sync | { type: "disarm" }; +type FromApp = + | Arm + | Sync + | { type: "interacted" } + | { type: "parent-unload" } + | { type: "disarm" }; let state: ExitWorkerState | null = null; let childPort: MessagePort | null = null; let disarmed = false; let exited = false; +let interacted = false; +let parentUnloading = false; +let pendingPatches: ExitPatch[] | null = null; +let pendingTimer: ReturnType | undefined; -const onExit = (ev: MessageEvent) => { - const msg = ev.data as { type?: unknown; patches?: unknown } | null; - if (!msg || msg.type !== "bd-edit:exit" || !Array.isArray(msg.patches)) return; - if (disarmed || exited || !state) return; +/* A frame script cannot trigger a write on its own: both user interaction in + the frame (`interacted`) and a real parent unload (`parentUnloading`) must + be attested by VisualEdit on the trusted parent channel before any message + from `childPort` can produce a network request. */ +const tryFlush = () => { + if (disarmed || exited || !state || !interacted || !parentUnloading || !pendingPatches) return; + const patches = pendingPatches; + pendingPatches = null; + clearTimeout(pendingTimer); exited = true; childPort?.close(); childPort = null; - // Shapes are checked spliced (applyRenderPatches): a bad one sends nothing. - const req = buildExitSaveRequest(state, msg.patches as ExitPatch[]); + const req = buildExitSaveRequest(state, patches); if (!req) return; void fetch(req.url, { method: req.method, @@ -55,6 +69,23 @@ const onExit = (ev: MessageEvent) => { }).catch(() => {}); }; +const onExit = (ev: MessageEvent) => { + const msg = ev.data as { type?: unknown; patches?: unknown } | null; + if (!msg || msg.type !== "bd-edit:exit" || !Array.isArray(msg.patches)) return; + if (disarmed || exited || !state) return; + pendingPatches = msg.patches as ExitPatch[]; + clearTimeout(pendingTimer); + if (interacted && parentUnloading) { + tryFlush(); + return; + } + // Without a parent unload alongside it, discard shortly so a forged message + // sent while viewing cannot linger until a later close. + pendingTimer = setTimeout(() => { + pendingPatches = null; + }, 500); +}; + self.onmessage = (ev: MessageEvent) => { const msg = ev.data as FromApp | null; if (!msg || typeof msg !== "object" || disarmed) return; @@ -70,13 +101,26 @@ self.onmessage = (ev: MessageEvent) => { baseSha: msg.baseSha, docText: msg.docText, }; - // A re-arm (a new render) replaces the iframe's channel; nothing sent yet. + if (msg.interacted) interacted = true; + parentUnloading = false; + pendingPatches = null; + clearTimeout(pendingTimer); childPort?.close(); childPort = ev.ports[0] ?? null; exited = false; if (childPort) childPort.onmessage = onExit; return; } + if (msg.type === "interacted") { + interacted = true; + tryFlush(); + return; + } + if (msg.type === "parent-unload") { + parentUnloading = true; + tryFlush(); + return; + } if (msg.type === "sync") { if (!state) return; if (typeof msg.savedText === "string") state.savedText = msg.savedText; @@ -87,6 +131,8 @@ self.onmessage = (ev: MessageEvent) => { if (msg.type === "disarm") { disarmed = true; state = null; + pendingPatches = null; + clearTimeout(pendingTimer); childPort?.close(); childPort = null; self.close(); diff --git a/internal/webapp/static/assets/Editor-CsLWwTRs.js b/internal/webapp/static/assets/Editor-CeIX9UEc.js similarity index 99% rename from internal/webapp/static/assets/Editor-CsLWwTRs.js rename to internal/webapp/static/assets/Editor-CeIX9UEc.js index 38e04058..9c182452 100644 --- a/internal/webapp/static/assets/Editor-CsLWwTRs.js +++ b/internal/webapp/static/assets/Editor-CeIX9UEc.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-DyFnf9EY.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CtVUr4nt.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-Co6en_o0.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CR4ZqPh0.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js b/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js deleted file mode 100644 index 42847f13..00000000 --- a/internal/webapp/static/assets/VisualEdit-CGKGr6GV.js +++ /dev/null @@ -1 +0,0 @@ -import{r as u,j as E,w as Ce,a as Fe}from"./index-DyFnf9EY.js";import{o as Ne,D as qe,c as L,a as V,m as ge,d as we}from"./sharedfile-CtVUr4nt.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Ae=50,De=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function Ie(){let o=null;const l=new Map;let d=0,x=!1;const M=()=>o?o.then(()=>{}):Promise.resolve(),P=c=>{const f=c.catch(()=>{}).finally(()=>{o===f&&(o=null)});o=f};return{enqueue(c){if(o){P(o.then(c));return}try{const f=c();De(f)&&P(Promise.resolve(f))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,f,_=!1){if(await M(),x||f())return;const h=++d;let j;const G=new Promise(C=>{l.set(h,C),j=setInterval(()=>{!x&&!f()||(l.delete(h),C())},Ae)});try{c(_?{type:"bd-edit:flush",id:h,lock:!0}:{type:"bd-edit:flush",id:h}),await G}finally{clearInterval(j)}await M()},close(){x=!0;for(const c of l.values())c();l.clear()}}}async function _e(o,l,d){let x=!1;try{return await o(),x=await l(),x}finally{x||d()}}async function Ge(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(d=>d.toString(16).padStart(2,"0")).join("")}catch{return null}}function Xe({apiBase:o,fileURL:l,path:d,initial:x,me:M,onStateChange:P,onCollab:c,onPeers:f,onConflictCopy:_,baseSha:h,onSaved:j,onWriting:G,onRendered:C,handle:H}){const b=u.useRef(null),[te,be]=u.useState(null),[ve,ne]=u.useState(!1),[Te,re]=u.useState(!1),oe=u.useRef(0),[se,Se]=u.useState(0),y=u.useRef({onStateChange:P,onCollab:c,onPeers:f,onSaved:j,onWriting:G,onRendered:C,onConflictCopy:_});y.current={onStateChange:P,onCollab:c,onPeers:f,onSaved:j,onWriting:G,onRendered:C,onConflictCopy:_};const F=u.useRef(x),O=u.useRef(M);O.current=M;const X=u.useRef(h);X.current=h;const Y=u.useRef(null);return u.useEffect(()=>{Y.current?.rebase(h)},[h]),u.useEffect(()=>{let S=null,N=!1,r=null,v;const ke=700;ne(!1),re(!1);const Re=setTimeout(()=>{!T&&oe.current<1&&(oe.current++,k())},11e3),We=setTimeout(()=>re(!0),24e3),B=Ie();let z=!1,m=null;try{m=typeof Worker<"u"?new Worker(new URL("/assets/editexit.worker-CfTN8vfX.js",import.meta.url),{type:"module"}):null}catch{m=null}let J=!1,K=F.current,Q=X.current;const Ee=()=>r?r.getText("body").toString():Y.current?.collab.text.toString()??"",U=()=>{!m||J||m.postMessage({type:"sync",savedText:K,baseSha:Q,hasBaseSha:!0,docText:Ee()})},ae=()=>{!m||J||(J=!0,m.postMessage({type:"disarm"}),m.terminate())},k=()=>{ae(),Se(e=>e+1)},Le=e=>{const t=b.current?.contentWindow;if(!m||J||!t)return;const s=new MessageChannel;m.postMessage({type:"arm",apiBase:o,path:d,who:O.current?.name,renderText:e,renderLen:e.length,allowedRanges:[...g.keys()],savedText:K,baseSha:Q,docText:e},[s.port1]),t.postMessage({type:"bd-edit:port"},"*",[s.port2])},ie=e=>{typeof e.seq=="number"&&b.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},Me=async e=>{const t=b.current,s=t?.contentWindow;if(!t||!s)return;let a=!1;const n=()=>{a=!0};t.addEventListener("load",n);try{await B.drain(w=>s.postMessage(w,"*"),()=>!z||a||b.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(v),v=void 0},q=new Map,ce=async()=>{const e=b.current?.contentWindow;if(!e)return()=>{};q.set(e,(q.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const a=(q.get(e)??1)-1;if(a>0){q.set(e,a);return}q.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await Me(!0)}catch(a){throw s(),a}return s},i=Y.current=Ne({apiBase:o,path:d,seed:F.current,baseSha:X.current,who:O.current?.name,me:O.current,onConflictCopy:e=>y.current.onConflictCopy?.(e),onShrinkRefused:e=>Fe(d,e),onShrinkWithdrawn:Ce,beforeJoin:async()=>r?ce():()=>{},onReady:()=>{if(clearTimeout(v),v=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(T&&t===s)for(const[a,n]of g){const w=L(n.from,e),A=L(n.to,e);w&&A&&g.set(a,{from:V(i.collab.text,w.index),to:V(i.collab.text,A.index),span:n.span,orig:n.orig})}else g.clear(),T=!1,t!==s&&k();e.destroy()}N=!0,R()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,F.current),N=!0,R()},onStalled:()=>{N||r||(r=new qe,r.getText("body").insert(0,F.current),N=!0,R())},onState:e=>y.current.onStateChange?.(e),onCollab:e=>y.current.onCollab?.(e),onPeers:e=>y.current.onPeers?.(e),onSaved:e=>y.current.onSaved?.(e),onWriting:()=>y.current.onWriting?.(),onBaseChange:(e,t)=>{K=e,Q=t,U()},soloText:()=>r?r.getText("body").toString():F.current,soloApply:({from:e,to:t,insert:s})=>{r&&r.transact(()=>{const a=r.getText("body");t>e&&a.delete(e,t-e),s&&a.insert(e,s)})}});let le=null;const ue={...i,saveNow:()=>{let e=()=>{};return le??=_e(async()=>{e=await ce()},()=>i.saveNow(),()=>e()).finally(()=>{le=null})}};H&&(H.current=ue);const g=new Map,de=e=>e.start+","+e.end,R=async()=>{if(T||!S||!N)return;const e=r?r.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(S.some(n=>n.end>t.length||n.start>n.end)){S=null,k();return}const s=await Ge(t);if(s!==null?s!==fe:Z>=0&&t.length!==Z){S=null,k();return}g.clear();for(const n of S)g.set(de(n),{from:V(e,n.start),to:V(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,Le(t),ne(!0),y.current.onRendered?.()};let fe="",Z=-1,T=!1;const Pe=e=>{if(e.type==="bd-edit:flushed"){B.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){be("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return S=e.ranges,fe=e.hash,Z=e.len,z=!0,R();if(e.type==="bd-edit:patch"){if(!T)return R().then(()=>{pe(e)&&(ie(e),U())});pe(e)&&(ie(e),U())}},pe=e=>{const t=g.get(de(e));if(!t)return!1;if(r){const p=L(t.from,r),D=L(t.to,r);if(!p||!D||p.index>D.index)return!1;const I=r.getText("body"),je=D.index-p.index;if(p.index===0&&D.index===I.length&&t.spant.span*4+256)return g.clear(),T=!1,k(),!1;const ee=I.toString().slice(p.index,D.index),me=ge(t.orig,ee,e.html);return t.orig=e.html,ee===me||(r.transact(()=>{for(const W of we(ee,me))W.deleteCount>0&&I.delete(p.index+W.index,W.deleteCount),W.insertText&&I.insert(p.index+W.index,W.insertText)}),y.current.onStateChange?.("dirty"),clearTimeout(v),v=setTimeout(()=>{i.saveNow()},ke)),!0}const s=i.collab.doc,a=L(t.from,s),n=L(t.to,s);if(!a||!n||a.index>n.index)return!1;const w=i.collab.text,A=n.index-a.index;if(a.index===0&&n.index===w.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:A,stamped:t.span,docLength:w.length}),g.clear(),T=!1,k(),!1;const $=w.toString().slice(a.index,n.index),ye=ge(t.orig,$,e.html);return t.orig=e.html,$===ye||i.collab.applySplices(we($,ye).map(p=>({...p,index:p.index+a.index}))),!0},xe=e=>{if(!b.current||e.source!==b.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||B.enqueue(()=>Pe(t))},he=()=>{U(),R()};return i.collab.text.observe(he),window.addEventListener("message",xe),()=>{H?.current===ue&&(H.current=null),z=!1,B.close(),clearTimeout(Re),clearTimeout(We),clearTimeout(v),i.collab.text.unobserve(he),setTimeout(()=>{window.removeEventListener("message",xe),clearTimeout(v),i.destroy(),ae(),r?.destroy()},300)}},[o,d,se]),E.jsxs(E.Fragment,{children:[te&&E.jsx("div",{id:"edit-clobbered",className:"banner",children:te}),Te&&!ve&&E.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",E.jsx("b",{children:"Edit source"}),"."]}),E.jsx("iframe",{ref:b,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:d},se)]})}export{Xe as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js b/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js new file mode 100644 index 00000000..b44174d2 --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js @@ -0,0 +1 @@ +import{r as u,j as W,w as Ne,a as qe}from"./index-Co6en_o0.js";import{o as Ae,D as Ie,c as M,a as K,m as ve,d as Te}from"./sharedfile-CR4ZqPh0.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const _e=50,Ge=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function He(){let o=null;const l=new Map;let f=0,h=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),j=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){j(o.then(c));return}try{const p=c();Ge(p)&&j(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,O=!1){if(await P(),h||p())return;const y=++f;let C;const U=new Promise(F=>{l.set(y,F),C=setInterval(()=>{!h&&!p()||(l.delete(y),F())},_e)});try{c(O?{type:"bd-edit:flush",id:y,lock:!0}:{type:"bd-edit:flush",id:y}),await U}finally{clearInterval(C)}await P()},close(){h=!0;for(const c of l.values())c();l.clear()}}}async function Oe(o,l,f){let h=!1;try{return await o(),h=await l(),h}finally{h||f()}}async function Ue(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Qe({apiBase:o,fileURL:l,path:f,initial:h,me:P,onStateChange:j,onCollab:c,onPeers:p,onConflictCopy:O,baseSha:y,onSaved:C,onWriting:U,onRendered:F,handle:B}){const w=u.useRef(null),[oe,Se]=u.useState(null),[ke,se]=u.useState(!1),[Ee,ae]=u.useState(!1),ie=u.useRef(0),[ce,Le]=u.useState(0),m=u.useRef({onStateChange:j,onCollab:c,onPeers:p,onSaved:C,onWriting:U,onRendered:F,onConflictCopy:O});m.current={onStateChange:j,onCollab:c,onPeers:p,onSaved:C,onWriting:U,onRendered:F,onConflictCopy:O};const D=u.useRef(h),J=u.useRef(P);J.current=P;const Q=u.useRef(y);Q.current=y;const X=u.useRef(null);return u.useEffect(()=>{X.current?.rebase(y)},[y]),u.useEffect(()=>{let S=null,N=!1,r=null,v;const Re=700;se(!1),ae(!1);const We=setTimeout(()=>{!T&&ie.current<1&&(ie.current++,E())},11e3),Me=setTimeout(()=>ae(!0),24e3),V=He();let Z=!1,d=null;try{d=typeof Worker<"u"?new Worker(new URL("/assets/editexit.worker-D_nakb5p.js",import.meta.url),{type:"module"}):null}catch{d=null}let k=!1,q=!1,$=D.current,ee=Q.current;const Y=()=>{q||document.activeElement!==w.current||(q=!0,d&&!k&&d.postMessage({type:"interacted"}))},A=()=>{Y(),!(!d||k||!q)&&d.postMessage({type:"parent-unload"})},Pe=()=>r?r.getText("body").toString():X.current?.collab.text.toString()??"",z=()=>{!d||k||d.postMessage({type:"sync",savedText:$,baseSha:ee,hasBaseSha:!0,docText:Pe()})},le=()=>{!d||k||(k=!0,d.postMessage({type:"disarm"}),d.terminate())},E=()=>{le(),Le(e=>e+1)},je=e=>{const t=w.current?.contentWindow;if(!d||k||!t)return;const s=new MessageChannel;d.postMessage({type:"arm",apiBase:o,path:f,who:J.current?.name,renderText:e,renderLen:e.length,allowedRanges:[...g.keys()],savedText:$,baseSha:ee,docText:e,interacted:q},[s.port1]),t.postMessage({type:"bd-edit:port"},"*",[s.port2])},de=e=>{typeof e.seq=="number"&&w.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},Ce=async e=>{const t=w.current,s=t?.contentWindow;if(!t||!s)return;let a=!1;const n=()=>{a=!0};t.addEventListener("load",n);try{await V.drain(b=>s.postMessage(b,"*"),()=>!Z||a||w.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(v),v=void 0},I=new Map,ue=async()=>{const e=w.current?.contentWindow;if(!e)return()=>{};I.set(e,(I.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const a=(I.get(e)??1)-1;if(a>0){I.set(e,a);return}I.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await Ce(!0)}catch(a){throw s(),a}return s},i=X.current=Ae({apiBase:o,path:f,seed:D.current,baseSha:Q.current,who:J.current?.name,me:J.current,onConflictCopy:e=>m.current.onConflictCopy?.(e),onShrinkRefused:e=>qe(f,e),onShrinkWithdrawn:Ne,beforeJoin:async()=>r?ue():()=>{},onReady:()=>{if(clearTimeout(v),v=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(T&&t===s)for(const[a,n]of g){const b=M(n.from,e),_=M(n.to,e);b&&_&&g.set(a,{from:K(i.collab.text,b.index),to:K(i.collab.text,_.index),span:n.span,orig:n.orig})}else g.clear(),T=!1,t!==s&&E();e.destroy()}N=!0,L()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,D.current),N=!0,L()},onStalled:()=>{N||r||(r=new Ie,r.getText("body").insert(0,D.current),N=!0,L())},onState:e=>m.current.onStateChange?.(e),onCollab:e=>m.current.onCollab?.(e),onPeers:e=>m.current.onPeers?.(e),onSaved:e=>m.current.onSaved?.(e),onWriting:()=>m.current.onWriting?.(),onBaseChange:(e,t)=>{$=e,ee=t,z()},soloText:()=>r?r.getText("body").toString():D.current,soloApply:({from:e,to:t,insert:s})=>{r&&r.transact(()=>{const a=r.getText("body");t>e&&a.delete(e,t-e),s&&a.insert(e,s)})}});let fe=null;const pe={...i,saveNow:()=>{let e=()=>{};return fe??=Oe(async()=>{e=await ue()},()=>i.saveNow(),()=>e()).finally(()=>{fe=null})}};B&&(B.current=pe);const g=new Map,xe=e=>e.start+","+e.end,L=async()=>{if(T||!S||!N)return;const e=r?r.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(S.some(n=>n.end>t.length||n.start>n.end)){S=null,E();return}const s=await Ue(t);if(s!==null?s!==he:te>=0&&t.length!==te){S=null,E();return}g.clear();for(const n of S)g.set(xe(n),{from:K(e,n.start),to:K(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,je(t),se(!0),m.current.onRendered?.()};let he="",te=-1,T=!1;const Fe=e=>{if(e.type==="bd-edit:flushed"){V.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){Se("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return S=e.ranges,he=e.hash,te=e.len,Z=!0,L();if(e.type==="bd-edit:patch"&&(Y(),!!q)){if(!T)return L().then(()=>{ye(e)&&(de(e),z())});ye(e)&&(de(e),z())}},ye=e=>{const t=g.get(xe(e));if(!t)return!1;if(r){const x=M(t.from,r),G=M(t.to,r);if(!x||!G||x.index>G.index)return!1;const H=r.getText("body"),De=G.index-x.index;if(x.index===0&&G.index===H.length&&t.spant.span*4+256)return g.clear(),T=!1,E(),!1;const re=H.toString().slice(x.index,G.index),be=ve(t.orig,re,e.html);return t.orig=e.html,re===be||(r.transact(()=>{for(const R of Te(re,be))R.deleteCount>0&&H.delete(x.index+R.index,R.deleteCount),R.insertText&&H.insert(x.index+R.index,R.insertText)}),m.current.onStateChange?.("dirty"),clearTimeout(v),v=setTimeout(()=>{i.saveNow()},Re)),!0}const s=i.collab.doc,a=M(t.from,s),n=M(t.to,s);if(!a||!n||a.index>n.index)return!1;const b=i.collab.text,_=n.index-a.index;if(a.index===0&&n.index===b.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:_,stamped:t.span,docLength:b.length}),g.clear(),T=!1,E(),!1;const ne=b.toString().slice(a.index,n.index),ge=ve(t.orig,ne,e.html);return t.orig=e.html,ne===ge||i.collab.applySplices(Te(ne,ge).map(x=>({...x,index:x.index+a.index}))),!0},we=e=>{if(!w.current||e.source!==w.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||V.enqueue(()=>Fe(t))},me=()=>{z(),L()};return i.collab.text.observe(me),window.addEventListener("message",we),window.addEventListener("blur",Y),window.addEventListener("beforeunload",A),window.addEventListener("pagehide",A),()=>{B?.current===pe&&(B.current=null),window.removeEventListener("blur",Y),window.removeEventListener("beforeunload",A),window.removeEventListener("pagehide",A),A(),Z=!1,V.close(),clearTimeout(We),clearTimeout(Me),clearTimeout(v),i.collab.text.unobserve(me),setTimeout(()=>{window.removeEventListener("message",we),clearTimeout(v),i.destroy(),le(),r?.destroy()},300)}},[o,f,ce]),W.jsxs(W.Fragment,{children:[oe&&W.jsx("div",{id:"edit-clobbered",className:"banner",children:oe}),Ee&&!ke&&W.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",W.jsx("b",{children:"Edit source"}),"."]}),W.jsx("iframe",{ref:w,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},ce)]})}export{Qe as VisualEdit}; diff --git a/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js b/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js deleted file mode 100644 index 27eef186..00000000 --- a/internal/webapp/static/assets/editexit.worker-CfTN8vfX.js +++ /dev/null @@ -1,11 +0,0 @@ -(function(){"use strict";function H(e,t,n){const r=h=>String(h).padStart(2,"0"),s=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+s,i=e.lastIndexOf("/"),d=i<0?"":e.slice(0,i+1),x=i<0?e:e.slice(i+1);return d+x.slice(0,Math.max(0,255-l.length))+l}function K(e){return/\/p\/[^/]+\/$/.test(e)}const z=4e3;function U(e,t){let n=0;for(;n0?h[o-1]:null,p=new Int32Array(2*o+1);for(let f=-o;f<=o;f+=2){let a;o===0?a=0:f===-o||f!==o&&c[f-1+o-1]=s&&g>=l){T=o;break}}h.push(p)}if(T<0)return[{aS:n,aE:n+s,bS:n,bE:n+l}];const y=[];let b=s,S=l;for(let o=T;o>0;o--){const c=h[o-1],p=b-S,f=p===-o||p!==o&&c[p-1+o-1]m&&S>L;)b--,S--,y.push(b,S);b=a,S=g}for(;b>0&&S>0;)b--,S--,y.push(b,S);const C=[];let E=0,u=0;for(let o=y.length-2;o>=0;o-=2){const c=y[o],p=y[o+1];(c>E||p>u)&&C.push({aS:n+E,aE:n+c,bS:n+u,bE:n+p}),E=c+1,u=p+1}return(El.startsWith(i)&&(i===""||i.endsWith(` -`)||l[i.length]===` -`);return e.length>=t.length&&s(e,t)?e:t.length>e.length&&s(t,e)?t:null}return n?Y(e,t)<=0?e+t:t+e:null}function M(e,t,n,r,s=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const l=new Map,i=v(e,r),d=v(t,r),x=v(n,r),h=w(i,l),T=[...U(h,w(d,l)).map(u=>({h:u,toks:d,side:0})),...U(h,w(x,l)).map(u=>({h:u,toks:x,side:1}))];T.sort((u,o)=>u.h.aS-o.h.aS||u.h.aE-o.h.aE||u.side-o.side);const y=(u,o,c)=>u.slice(o,c).join(""),b=(u,o,c,p)=>{let f="",a=c;for(const g of u)g.side===o&&(f+=y(i,a,g.h.aS)+y(g.toks,g.h.bS,g.h.bE),a=g.h.aE);return f+y(i,a,p)};let S="",C=0,E=0;for(;Em.side)).size===1){S+=b(u,u[0].side,o,c);continue}const f=b(u,0,o,c),a=b(u,1,o,c);if(f===a){S+=f;continue}if(o===c){const m=$(f,a,r!==_,i.length===0);if(m===null){if(!s)return null;S+=a;continue}S+=m;continue}if(r===_)return null;const g=r===W?M(y(i,o,c),f,a,_):M(y(i,o,c),f,a,r+1,s);if(g===null){if(!s)return null;S+=a;continue}S+=g}return S+y(i,C,i.length)}const R=e=>e===""||e.endsWith(` -`)?e:e+` -`;function q(e,t,n,r){let s=t.endsWith(` -`);return s===e.endsWith(` -`)&&(s=n.endsWith(` -`)),r===""||s===r.endsWith(` -`)?r:s?r+` -`:r.slice(0,-1)}function J(e,t,n){const r=M(R(e),R(t),R(n),B);return r===null?{ok:!1}:{ok:!0,text:q(e,t,n,r)}}function Z(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),r=n.lastIndexOf("."),s=r>=0?n.slice(r).toLowerCase():"",l=i=>{try{return JSON.parse(i),!0}catch{return!1}};if(s===".json")return l(t);if(s===".jsonl")for(const i of t.split(` -`)){const d=i.trim();if(d.length>0&&!l(d))return!1}return!0}function V(e,t,n,r){const s=J(t,n,r);return!s.ok||n===r||n===t||r===t||Z(e,s.text)?s:{ok:!1}}const G=256;function Q(e,t){return e<=0||t>=e?!1:t===0?!0:e>=G&&t*5new TextEncoder().encode(e).length,ee=256,te=1<<20,O=6e4,X=(e,t)=>t>0&&t=56320&&e.charCodeAt(t)<=57343&&e.charCodeAt(t-1)>=55296&&e.charCodeAt(t-1)<=56319;function j(e,t,n,r){if(e.length!==t||r.length<1||r.length>ee)return null;let s="",l=0;for(const{start:i,end:d,html:x}of r){if(!Number.isInteger(i)||!Number.isInteger(d)||i<=0||i>d||d>=t||itypeof h.ackedHtml=="string").map(h=>({start:h.start,end:h.end,html:h.ackedHtml})),s=r.length>0?j(e.renderText,e.renderLen,e.allowedRanges,r):e.renderText;if(s===null)return null;const l=e.docText||e.savedText;let i=!0,d=n;if(l!==s&&l!==n){const h=V(e.path,s,l,n);h.ok?d=h.text:i=!1}if(e.savedText.length>0&&Q(I(e.savedText),I(d))||i&&d===e.savedText)return null;if(K(e.apiBase)){const h=i?{base:e.baseSha,base_text:e.savedText,text:d,park_on_conflict:!0}:{base_text:e.renderText,text:n,park_on_conflict:!0},T=JSON.stringify(h);return{url:e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path),method:"POST",headers:{"Content-Type":"application/json"},body:T,keepalive:I(T)<=O}}const x="text/plain; charset=utf-8";if(i){const h={"Content-Type":x,"X-Bdrive-Park-On-Conflict":"1"};return e.baseSha&&(h["If-Match"]=`"${e.baseSha}"`),{url:e.apiBase+"upload/content?path="+encodeURIComponent(e.path),method:"PUT",headers:h,body:d,keepalive:I(d)<=O}}return{url:e.apiBase+"upload/content?path="+encodeURIComponent(H(e.path,e.who||"browser",new Date)),method:"PUT",headers:{"Content-Type":x,"If-None-Match":"*","X-Bdrive-Park-On-Conflict":"1"},body:n,keepalive:I(n)<=O}}let A=null,k=null,P=!1,N=!1;const re=e=>{const t=e.data;if(!t||t.type!=="bd-edit:exit"||!Array.isArray(t.patches)||P||N||!A)return;N=!0,k?.close(),k=null;const n=ne(A,t.patches);n&&fetch(n.url,{method:n.method,credentials:"same-origin",headers:n.headers,body:n.body,keepalive:n.keepalive}).catch(()=>{})};self.onmessage=e=>{const t=e.data;if(!(!t||typeof t!="object"||P)){if(t.type==="arm"){A={apiBase:t.apiBase,path:t.path,who:t.who,renderText:t.renderText,renderLen:t.renderLen,allowedRanges:new Set(t.allowedRanges),savedText:t.savedText,baseSha:t.baseSha,docText:t.docText},k?.close(),k=e.ports[0]??null,N=!1,k&&(k.onmessage=re);return}if(t.type==="sync"){if(!A)return;typeof t.savedText=="string"&&(A.savedText=t.savedText),t.hasBaseSha&&(A.baseSha=t.baseSha),typeof t.docText=="string"&&(A.docText=t.docText);return}t.type==="disarm"&&(P=!0,A=null,k?.close(),k=null,self.close())}}})(); diff --git a/internal/webapp/static/assets/editexit.worker-D_nakb5p.js b/internal/webapp/static/assets/editexit.worker-D_nakb5p.js new file mode 100644 index 00000000..51b7d57a --- /dev/null +++ b/internal/webapp/static/assets/editexit.worker-D_nakb5p.js @@ -0,0 +1,11 @@ +(function(){"use strict";function Y(e,t,n){const r=h=>String(h).padStart(2,"0"),l=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",i=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+l,s=e.lastIndexOf("/"),d=s<0?"":e.slice(0,s+1),E=s<0?e:e.slice(s+1);return d+E.slice(0,Math.max(0,255-i.length))+i}function $(e){return/\/p\/[^/]+\/$/.test(e)}const q=4e3;function H(e,t){let n=0;for(;n0?h[o-1]:null,p=new Int32Array(2*o+1);for(let f=-o;f<=o;f+=2){let a;o===0?a=0:f===-o||f!==o&&c[f-1+o-1]=l&&g>=i){S=o;break}}h.push(p)}if(S<0)return[{aS:n,aE:n+l,bS:n,bE:n+i}];const x=[];let b=l,T=i;for(let o=S;o>0;o--){const c=h[o-1],p=b-T,f=p===-o||p!==o&&c[p-1+o-1]m&&T>j;)b--,T--,x.push(b,T);b=a,T=g}for(;b>0&&T>0;)b--,T--,x.push(b,T);const I=[];let y=0,u=0;for(let o=x.length-2;o>=0;o-=2){const c=x[o],p=x[o+1];(c>y||p>u)&&I.push({aS:n+y,aE:n+c,bS:n+u,bE:n+p}),y=c+1,u=p+1}return(yi.startsWith(s)&&(s===""||s.endsWith(` +`)||i[s.length]===` +`);return e.length>=t.length&&l(e,t)?e:t.length>e.length&&l(t,e)?t:null}return n?V(e,t)<=0?e+t:t+e:null}function L(e,t,n,r,l=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,s=N(e,r),d=N(t,r),E=N(n,r),h=U(s,i),S=[...H(h,U(d,i)).map(u=>({h:u,toks:d,side:0})),...H(h,U(E,i)).map(u=>({h:u,toks:E,side:1}))];S.sort((u,o)=>u.h.aS-o.h.aS||u.h.aE-o.h.aE||u.side-o.side);const x=(u,o,c)=>u.slice(o,c).join(""),b=(u,o,c,p)=>{let f="",a=c;for(const g of u)g.side===o&&(f+=x(s,a,g.h.aS)+x(g.toks,g.h.bS,g.h.bE),a=g.h.aE);return f+x(s,a,p)};let T="",I=0,y=0;for(;ym.side)).size===1){T+=b(u,u[0].side,o,c);continue}const f=b(u,0,o,c),a=b(u,1,o,c);if(f===a){T+=f;continue}if(o===c){const m=G(f,a,r!==P,s.length===0);if(m===null){if(!l)return null;T+=a;continue}T+=m;continue}if(r===P)return null;const g=r===K?L(x(s,o,c),f,a,P):L(x(s,o,c),f,a,r+1,l);if(g===null){if(!l)return null;T+=a;continue}T+=g}return T+x(s,I,s.length)}const B=e=>e===""||e.endsWith(` +`)?e:e+` +`;function Q(e,t,n,r){let l=t.endsWith(` +`);return l===e.endsWith(` +`)&&(l=n.endsWith(` +`)),r===""||l===r.endsWith(` +`)?r:l?r+` +`:r.slice(0,-1)}function ee(e,t,n){const r=L(B(e),B(t),B(n),F);return r===null?{ok:!1}:{ok:!0,text:Q(e,t,n,r)}}function te(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),r=n.lastIndexOf("."),l=r>=0?n.slice(r).toLowerCase():"",i=s=>{try{return JSON.parse(s),!0}catch{return!1}};if(l===".json")return i(t);if(l===".jsonl")for(const s of t.split(` +`)){const d=s.trim();if(d.length>0&&!i(d))return!1}return!0}function ne(e,t,n,r){const l=ee(t,n,r);return!l.ok||n===r||n===t||r===t||te(e,l.text)?l:{ok:!1}}const re=256;function oe(e,t){return e<=0||t>=e?!1:t===0?!0:e>=re&&t*5new TextEncoder().encode(e).length,le=256,se=1<<20,W=6e4,z=(e,t)=>t>0&&t=56320&&e.charCodeAt(t)<=57343&&e.charCodeAt(t-1)>=55296&&e.charCodeAt(t-1)<=56319;function D(e,t,n,r){if(e.length!==t||r.length<1||r.length>le)return null;let l="",i=0;for(const{start:s,end:d,html:E}of r){if(!Number.isInteger(s)||!Number.isInteger(d)||s<=0||s>d||d>=t||stypeof h.ackedHtml=="string").map(h=>({start:h.start,end:h.end,html:h.ackedHtml})),l=r.length>0?D(e.renderText,e.renderLen,e.allowedRanges,r):e.renderText;if(l===null)return null;const i=e.docText||e.savedText;let s=!0,d=n;if(i!==l&&i!==n){const h=ne(e.path,l,i,n);h.ok?d=h.text:s=!1}if(e.savedText.length>0&&oe(_(e.savedText),_(d))||s&&d===e.savedText)return null;if($(e.apiBase)){const h=s?{base:e.baseSha,base_text:e.savedText,text:d,park_on_conflict:!0}:{base_text:e.renderText,text:n,park_on_conflict:!0},S=JSON.stringify(h);return{url:e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path),method:"POST",headers:{"Content-Type":"application/json"},body:S,keepalive:_(S)<=W}}const E="text/plain; charset=utf-8";if(s){const h={"Content-Type":E,"X-Bdrive-Park-On-Conflict":"1"};return e.baseSha&&(h["If-Match"]=`"${e.baseSha}"`),{url:e.apiBase+"upload/content?path="+encodeURIComponent(e.path),method:"PUT",headers:h,body:d,keepalive:_(d)<=W}}return{url:e.apiBase+"upload/content?path="+encodeURIComponent(Y(e.path,e.who||"browser",new Date)),method:"PUT",headers:{"Content-Type":E,"If-None-Match":"*","X-Bdrive-Park-On-Conflict":"1"},body:n,keepalive:_(n)<=W}}let A=null,k=null,w=!1,M=!1,R=!1,O=!1,C=null,v;const X=()=>{if(w||M||!A||!R||!O||!C)return;const e=C;C=null,clearTimeout(v),M=!0,k?.close(),k=null;const t=ie(A,e);t&&fetch(t.url,{method:t.method,credentials:"same-origin",headers:t.headers,body:t.body,keepalive:t.keepalive}).catch(()=>{})},ce=e=>{const t=e.data;if(!(!t||t.type!=="bd-edit:exit"||!Array.isArray(t.patches))&&!(w||M||!A)){if(C=t.patches,clearTimeout(v),R&&O){X();return}v=setTimeout(()=>{C=null},500)}};self.onmessage=e=>{const t=e.data;if(!(!t||typeof t!="object"||w)){if(t.type==="arm"){A={apiBase:t.apiBase,path:t.path,who:t.who,renderText:t.renderText,renderLen:t.renderLen,allowedRanges:new Set(t.allowedRanges),savedText:t.savedText,baseSha:t.baseSha,docText:t.docText},t.interacted&&(R=!0),O=!1,C=null,clearTimeout(v),k?.close(),k=e.ports[0]??null,M=!1,k&&(k.onmessage=ce);return}if(t.type==="interacted"){R=!0,X();return}if(t.type==="parent-unload"){O=!0,X();return}if(t.type==="sync"){if(!A)return;typeof t.savedText=="string"&&(A.savedText=t.savedText),t.hasBaseSha&&(A.baseSha=t.baseSha),typeof t.docText=="string"&&(A.docText=t.docText);return}t.type==="disarm"&&(w=!0,A=null,C=null,clearTimeout(v),k?.close(),k=null,self.close())}}})(); diff --git a/internal/webapp/static/assets/index-BLk9nKdF.css b/internal/webapp/static/assets/index-BLk9nKdF.css deleted file mode 100644 index 4d1db26a..00000000 --- a/internal/webapp/static/assets/index-BLk9nKdF.css +++ /dev/null @@ -1 +0,0 @@ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--tracking-widest:.1em;--radius-xs:.125rem;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--color-background:#0a0b0d;--color-foreground:#eef0f3;--color-card:#15171b;--color-card-foreground:#eef0f3;--color-popover:#15171b;--color-popover-foreground:#eef0f3;--color-primary:#f5a623;--color-primary-foreground:#1a1204;--color-secondary:#ffffff08;--color-secondary-foreground:#eef0f3;--color-muted:#ffffff0f;--color-muted-foreground:#9aa0a9;--color-accent:#ffffff0f;--color-accent-foreground:#eef0f3;--color-destructive:#f26d6d;--color-border:#ffffff12;--color-input:#ffffff1c;--color-ring:#f5a623;--radius-ctl:7px}}@layer base,components;@layer utilities{.\@container\/card-header{container:card-header/inline-size}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:0}.top-4{top:calc(var(--spacing) * 4)}.top-\[50\%\]{top:50%}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.left-2{left:calc(var(--spacing) * 2)}.left-\[50\%\]{left:50%}.isolate{isolation:isolate}.z-50{z-index:50}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2/span 2}.row-start-1{grid-row-start:1}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-auto{margin-left:auto}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-row{display:table-row}.field-sizing-content{field-sizing:content}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-2\.5{width:calc(var(--spacing) * 2.5);height:calc(var(--spacing) * 2.5)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-10{width:calc(var(--spacing) * 10);height:calc(var(--spacing) * 10)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.max-h-\(--radix-context-menu-content-available-height\){max-height:var(--radix-context-menu-content-available-height)}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.max-h-\[300px\]{max-height:300px}.min-h-16{min-height:calc(var(--spacing) * 16)}.w-6{width:calc(var(--spacing) * 6)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:0}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.caption-bottom{caption-side:bottom}.origin-\(--radix-context-menu-content-transform-origin\){transform-origin:var(--radix-context-menu-content-transform-origin)}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.origin-\(--radix-tooltip-content-transform-origin\){transform-origin:var(--radix-tooltip-content-transform-origin)}.translate-x-\[-50\%\]{--tw-translate-x:-50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y:-50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[calc\(-50\%_-_2px\)\]{--tw-translate-y: calc(-50% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-45{rotate:45deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.resize{resize:both}.scroll-my-1{scroll-margin-block:var(--spacing)}.scroll-py-1{scroll-padding-block:var(--spacing)}.auto-rows-min{grid-auto-rows:min-content}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-xs{border-radius:var(--radius-xs)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-input{border-color:var(--color-input)}.bg-background{background-color:var(--color-background)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.bg-black\/5{background-color:color-mix(in oklab,var(--color-black) 5%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-border{background-color:var(--color-border)}.bg-card{background-color:var(--color-card)}.bg-destructive{background-color:var(--color-destructive)}.bg-foreground{background-color:var(--color-foreground)}.bg-muted\/50{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.bg-muted\/50{background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.bg-popover{background-color:var(--color-popover)}.bg-primary{background-color:var(--color-primary)}.bg-secondary{background-color:var(--color-secondary)}.bg-transparent{background-color:#0000}.fill-current{fill:currentColor}.fill-foreground{fill:var(--color-foreground)}.p-0{padding:0}.p-1{padding:var(--spacing)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-123{padding:calc(var(--spacing) * 123)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-6{padding-block:calc(var(--spacing) * 6)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-8{padding-left:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.whitespace-nowrap{white-space:nowrap}.text-background{color:var(--color-background)}.text-card-foreground{color:var(--color-card-foreground)}.text-destructive{color:var(--color-destructive)}.text-foreground{color:var(--color-foreground)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-popover-foreground{color:var(--color-popover-foreground)}.text-primary{color:var(--color-primary)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-secondary-foreground{color:var(--color-secondary-foreground)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-black\/10{--tw-ring-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.ring-black\/10{--tw-ring-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.ring-offset-background{--tw-ring-offset-color:var(--color-background)}.outline-hidden{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline-offset:2px;outline:2px solid #0000}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[background-color\,border-color\,color\]{transition-property:background-color,border-color,color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.fade-in-0{--tw-enter-opacity:0}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale:.95}.running{animation-play-state:running}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:.5}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:.5}.selection\:bg-primary ::selection{background-color:var(--color-primary)}.selection\:bg-primary::selection{background-color:var(--color-primary)}.selection\:text-primary-foreground ::selection{color:var(--color-primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--color-primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-transparent::file-selector-button{background-color:#0000}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--color-foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--color-muted-foreground)}@media(hover:hover){.hover\:bg-accent:hover{background-color:var(--color-accent)}.hover\:bg-destructive\/90:hover{background-color:#f26d6de6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--color-destructive) 90%,transparent)}}.hover\:bg-muted\/50:hover{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.hover\:bg-primary\/90:hover{background-color:#f5a623e6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--color-primary) 90%,transparent)}}.hover\:bg-secondary\/80:hover{background-color:#ffffff06}@supports (color:color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--color-secondary) 80%,transparent)}}.hover\:text-accent-foreground:hover{color:var(--color-accent-foreground)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:bg-accent:focus{background-color:var(--color-accent)}.focus\:text-accent-foreground:focus{color:var(--color-accent-foreground)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color:var(--color-ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus-visible\:border-ring:focus-visible{border-color:var(--color-ring)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 20%, transparent)}}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:#f5a62380}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-ring) 50%, transparent)}}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-aria-expanded\:bg-muted\/50:has([aria-expanded=true]){background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.has-aria-expanded\:bg-muted\/50:has([aria-expanded=true]){background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has([data-slot=card-action]){grid-template-columns:1fr auto}.has-\[\>svg\]\:px-1\.5:has(>svg){padding-inline:calc(var(--spacing) * 1.5)}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing) * 4)}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--color-destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 20%, transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true]{pointer-events:none}.data-\[disabled\=true\]\:opacity-50[data-disabled=true]{opacity:.5}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--color-destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing) * 8)}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--color-muted-foreground)}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:var(--color-accent)}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:var(--color-accent-foreground)}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y:var(--spacing);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x:calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:calc(2*var(--spacing))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x:var(--spacing);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y:calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:calc(2*var(--spacing))}.data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing) * 9)}.data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing) * 8)}:is(.\*\*\:data-\[slot\=command-input-wrapper\]\:h-12 *)[data-slot=command-input-wrapper]{height:calc(var(--spacing) * 12)}:is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}:is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}:is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}:is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing) * 2)}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--color-accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--color-accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--color-muted-foreground)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:var(--color-muted)}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--color-destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:#f26d6d1a}@supports (color:color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--color-destructive) 10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--color-destructive)}@media(min-width:40rem){.sm\:max-w-lg{max-width:var(--container-lg)}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}}.dark\:border-input:where([data-theme=dark],[data-theme=dark] *){border-color:var(--color-input)}.dark\:bg-destructive\/60:where([data-theme=dark],[data-theme=dark] *){background-color:#f26d6d99}@supports (color:color-mix(in lab,red,red)){.dark\:bg-destructive\/60:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-destructive) 60%,transparent)}}.dark\:bg-input\/30:where([data-theme=dark],[data-theme=dark] *){background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.dark\:bg-input\/30:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-input) 30%,transparent)}}.dark\:bg-white\/10:where([data-theme=dark],[data-theme=dark] *){background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/10:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-white) 10%,transparent)}}@media(hover:hover){.dark\:hover\:bg-accent\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:color-mix(in oklab,var(--color-accent) 50%,transparent)}}.dark\:hover\:bg-input\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:#ffffff0e}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:color-mix(in oklab,var(--color-input) 50%,transparent)}}}.dark\:focus-visible\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *):focus-visible{--tw-ring-color:#f26d6d66}@supports (color:color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *):focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 40%, transparent)}}.dark\:aria-invalid\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *)[aria-invalid=true]{--tw-ring-color:#f26d6d66}@supports (color:color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *)[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 40%, transparent)}}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:where([data-theme=dark],[data-theme=dark] *)[data-variant=destructive]:focus{background-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:where([data-theme=dark],[data-theme=dark] *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--color-destructive) 20%,transparent)}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--color-muted-foreground)}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:calc(var(--spacing) * 12)}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-block:calc(var(--spacing) * 3)}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:calc(var(--spacing) * 5)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-3 svg:not([class*=size-]){width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--color-muted-foreground)}.\[\&_tr\]\:border-b tr{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-style:var(--tw-border-style);border-width:0}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\.border-b\]\:pb-6.border-b{padding-bottom:calc(var(--spacing) * 6)}.\[\.border-t\]\:pt-6.border-t{padding-top:calc(var(--spacing) * 6)}:is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}:is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}:is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing) * 2)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:text-destructive\![data-variant=destructive]>*):is(svg){color:var(--color-destructive)!important}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y:2px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>tr\]\:last\:border-b-0>tr:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}:root[data-theme=light]{--color-bg:#fff;--color-side:#f6f7f8;--color-raise:#fff;--color-surface:#00000008;--color-hovered:#0000000d;--color-line:#00000017;--color-line-2:#00000024;--color-text:#1b1d21;--color-dim:#565c66;--color-faint:#686d76;--color-ghost:#70757e;--color-honey:#f5a623;--color-honey-bright:#a35f00;--color-honey-dim:#b86e0e;--color-glow:#f5a62329;--color-add:#17804f;--color-del:#d14343;--color-background:#fff;--color-foreground:#1b1d21;--color-card:#fff;--color-card-foreground:#1b1d21;--color-popover:#fff;--color-popover-foreground:#1b1d21;--color-primary:#f5a623;--color-primary-foreground:#1a1204;--color-secondary:#00000008;--color-secondary-foreground:#1b1d21;--color-muted:#0000000d;--color-muted-foreground:#565c66;--color-accent:#0000000d;--color-accent-foreground:#1b1d21;--color-destructive:#d14343;--color-border:#00000017;--color-input:#00000024;--color-ring:#b86e0e}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}}:root{color-scheme:dark;--bg: #0a0b0d;--bg-side: #0c0e10;--bg-raise: #15171b;--surface: rgba(255,255,255,.03);--hover: rgba(255,255,255,.06);--border: rgba(255,255,255,.07);--border-2: rgba(255,255,255,.11);--code-bg: #0d0f12;--text: #eef0f3;--text-dim: #9aa0a9;--text-faint: #868b93;--text-ghost: #666b74;--text-bright: #f4f6f9;--text-body: #c6cbd3;--code-ink: #e4d9c4;--quote-ink: #d8cdb6;--accent: #f5a623;--accent-bright: #ffcf85;--accent-dim: #d3861a;--accent-press: #e0951a;--glow: rgba(245,166,35,.13);--add: #4cc38a;--del: #f26d6d;--accent-ink: var(--accent);--accent-hover-bg: var(--accent-bright);--danger-ink: #e07070;--danger-bright: #ff8b8b;--danger-title: #d2695e;--shadow-pop: rgba(0, 0, 0, .35);--row-hover: rgba(255,255,255,.02);--row-hover-faint: rgba(255,255,255,.015);--viz-agent: #c98500;--viz-human: #5b8def;--viz-share: #d55181;--viz-fresh-1: #4cc38a;--viz-fresh-2: #3d9a6c;--viz-fresh-3: #327656;--viz-fresh-4: #285a44;--viz-flat: #969ca4;--viz-cov-0: rgba(255,255,255,.03);--viz-cov-1: #5e420a;--viz-cov-2: #7d5507;--viz-cov-3: #a06d05;--viz-cov-4: #c98500;--viz-cov-ink-1: #f4e6c8;--viz-cov-ink-2: #fff4dc;--viz-ink-dark: #0c0d10;--viz-ink-light: #eef0f3;--warn-ink: #f0883e;--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--ui: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", "Segoe UI", Roboto, sans-serif;--r-ctl: 7px;--r-card: 10px;--r-over: 14px;--page-read: 768px;--page-app: 768px;--page-wide: 1200px;--hero-top: clamp(32px, 8vh, 88px)}:root[data-theme=light]{color-scheme:light;--bg: #ffffff;--bg-side: #f6f7f8;--bg-raise: #ffffff;--surface: rgba(0,0,0,.03);--hover: rgba(0,0,0,.05);--border: rgba(0,0,0,.09);--border-2: rgba(0,0,0,.14);--code-bg: #f5f6f8;--text: #1b1d21;--text-dim: #565c66;--text-faint: #686d76;--text-ghost: #70757e;--text-bright: #0b0c0e;--text-body: #2b2f36;--code-ink: #7a4f00;--quote-ink: #4a4033;--accent: #f5a623;--accent-bright: #a35f00;--accent-dim: #b86e0e;--accent-press: #e0951a;--glow: rgba(245,166,35,.16);--add: #17804f;--del: #d14343;--accent-ink: var(--accent-bright);--accent-hover-bg: var(--accent-press);--danger-ink: #b8322a;--danger-bright: #b42318;--danger-title: #b8322a;--shadow-pop: rgba(0, 0, 0, .12);--row-hover: rgba(0,0,0,.025);--row-hover-faint: rgba(0,0,0,.02);--viz-agent: #c98500;--viz-human: #2a78d6;--viz-share: #d55181;--viz-fresh-1: #3daa78;--viz-fresh-2: #2e8a5f;--viz-fresh-3: #23704c;--viz-fresh-4: #1b573b;--viz-flat: #c8ccd2;--viz-cov-0: rgba(0,0,0,.03);--viz-cov-1: #f0ddb0;--viz-cov-2: #e3bf6e;--viz-cov-3: #d5a132;--viz-cov-4: #c98500;--viz-cov-ink-1: #4a3305;--viz-cov-ink-2: #3a2804;--warn-ink: #c4560c}@font-face{font-family:"Jersey 10";font-style:normal;font-weight:400;font-display:swap;src:url(/assets/jersey-10-COnnvJff.woff2) format("woff2")}@font-face{font-family:Logo Fallback;src:local("Helvetica Neue"),local("Arial"),local("Segoe UI"),local("Roboto");size-adjust:73%}*{box-sizing:border-box}[hidden]{display:none!important}html,body{height:100%;margin:0}#root{display:contents}body{display:flex;background:var(--bg);color:var(--text);font:13px/1.5 var(--ui);letter-spacing:-.006em;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}::selection{background:var(--glow);color:var(--accent-bright)}:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:5px}:focus-visible{outline-color:var(--accent)}.admin input:focus-visible{outline:2px solid var(--accent);outline-offset:1px}input[type=checkbox]{accent-color:var(--accent);width:20px;height:20px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}.sprite{position:absolute}.ico{width:16px;height:16px;flex:none;stroke:currentColor;stroke-width:1.6;fill:none;stroke-linecap:round;stroke-linejoin:round}button,input,a.btn{font-family:inherit}#sidebar{width:var(--sb-w, 256px);min-width:210px;max-width:min(480px,calc(100vw - 645px));position:relative;background:var(--bg-side);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden;--row-on: color-mix(in srgb, var(--text) 9%, transparent)}#vault{display:flex;align-items:center;gap:8px;flex:none;height:52px;padding:0 16px;position:relative;z-index:45}#vault-badge{flex:none;display:grid;place-items:center;color:var(--accent-ink)}#vault-name{font-family:"Jersey 10","Logo Fallback",var(--ui);font-size:18px;font-weight:400;font-synthesis:none;letter-spacing:.01em;line-height:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#vault-beta{flex:none;font-size:11px;font-weight:500;color:var(--text-faint)}.vault-actions{margin-left:auto;display:flex;align-items:center;gap:4px}#vault #signout{width:28px;height:28px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;color:var(--text-faint);background:transparent;border:none;cursor:pointer;text-decoration:none}#vault #signout:hover{color:var(--text);background:var(--hover)}#vault #signout .ico{width:16px;height:16px}#projects{flex:none;padding:0 8px}.proj-trigger{width:100%;height:32px;display:flex;align-items:center;gap:8px;padding:0 8px 0 6px;border:0;border-radius:6px;background:transparent;color:var(--text);font:inherit;font-size:13px;font-weight:500;text-align:left;cursor:pointer}.proj-trigger:hover,.proj-trigger[data-state=open]{background:var(--hover)}.proj-trigger .proj-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.proj-trigger .updown{width:16px;height:16px;color:var(--text-faint)}.proj-mark{width:20px;height:20px;border-radius:5px;flex:none;display:grid;place-items:center;background:color-mix(in srgb,var(--mk, var(--text-faint)) 18%,transparent);color:var(--mk, var(--text-faint))}.proj-mark svg{width:12px;height:12px}.proj-mark.add{background:transparent;border:1px dashed var(--border-2);color:var(--text-faint)}#projects .row,#pinned .row,#tree .row,.sb-sync{display:flex;align-items:center;gap:8px;height:28px;padding:0 8px;border-radius:6px;color:var(--text-dim);cursor:pointer;position:relative;white-space:nowrap;overflow:hidden;font-size:13px}#projects .row:hover,#pinned .row:hover,#tree .row:hover,.sb-sync:hover{background:var(--hover);color:var(--text)}#projects .row.active,#pinned .row.active,#tree .row.active,.sb-sync.active{background:var(--row-on);color:var(--text)}#projects .row.active .label,#tree .row.active .label{font-weight:500}#projects .row .label,#pinned .label,#tree .label,.sb-sync .label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#tree{flex:1;overflow-y:auto;padding:0 8px 16px}.tguide{position:absolute;top:0;bottom:0;width:1px;background:var(--border);pointer-events:none}#tree .row{gap:6px}#tree .chev{width:14px;height:14px;flex:none;color:var(--text-faint);transition:transform .12s;display:flex;align-items:center;justify-content:center}#tree .chev .ico{width:14px;height:14px}#tree .ticon{flex:none;display:flex;color:var(--text-faint)}#tree .ticon .ico{width:16px;height:16px}#tree .row:hover .ticon,#tree .row:hover .chev{color:var(--text-dim)}#tree .row.active .chev{color:var(--text)}#tree .row.active .ticon{color:var(--accent-ink)}#tree .file .chev{visibility:hidden}#tree .row.collapsed .chev{transform:rotate(-90deg)}.field-err{color:var(--del);font-size:12px;margin:6px 2px 0}.modal,#palette{translate:none}.admin-card-table{padding:0}.admin-table{width:100%;border-collapse:collapse;table-layout:fixed}.admin-table td .ai-main,.admin-table td a.ai-main,.admin-table td .ai-copy,.admin-table td .ai-tag{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.admin-table th:last-child,.admin-table td:last-child{width:186px;text-align:right}.admin-table tr:last-child td{border-bottom:none}.admin-table th{text-align:left;font-size:11px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--text-faint);padding:0;border-bottom:1px solid var(--border);-webkit-user-select:none;user-select:none}.admin-table td{padding:0;border-bottom:1px solid var(--border);overflow:hidden;text-overflow:ellipsis}.admin-table tr.admin-item{display:table-row}.admin-table tr.admin-item td{padding:8px 10px}.admin-card-table{overflow-x:auto}.shares-table .admin-table th:last-child,.shares-table .admin-table td:last-child{width:150px}.share-acts{display:inline-flex;align-items:center;gap:6px}.share-acts .ai-btn{display:inline-flex;align-items:center;justify-content:center;padding:0 8px}.share-acts .ai-btn .ico{width:15px;height:15px}.shares-table .admin-table td .ai-tag{white-space:normal;overflow:visible;text-overflow:clip}.share-banner{margin:0 0 18px;padding:12px 14px;border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:var(--r-ctl);background:var(--surface)}.share-banner .sb-head{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text)}.share-banner .sb-head .ico,.share-banner .sb-head svg{width:15px;height:15px;flex:none;color:var(--accent-ink)}.share-banner .sb-count{color:var(--text-faint);font-size:12px}.share-banner .sb-note{margin:6px 0 10px;font-size:12.5px;line-height:1.55;color:var(--text-faint);max-width:64ch}.share-banner .sb-link{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding-top:8px;border-top:1px solid var(--border)}.share-banner .sb-link+.sb-link{margin-top:8px}.share-banner .sb-url{flex:1 1 260px;min-width:0;font-size:12px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.share-banner .sb-meta{font-size:11.5px;color:var(--text-faint)}.share-banner .sb-actions{display:flex;align-items:center;gap:6px;margin-left:auto}.nav-menu{list-style:none;margin:0;padding:0}.nav-menu .row .ico{width:16px;height:16px;flex:none}.nav-count{flex:none;margin-left:auto;font-size:12px;font-weight:500;color:var(--text-faint);font-variant-numeric:tabular-nums}#accountbar{position:relative;padding:4px 8px 8px}.gh-star{display:flex;align-items:center;gap:8px;padding:4px 8px;margin-bottom:2px;border-radius:6px;color:var(--text-faint);font-size:11px;text-decoration:none}.gh-star:hover{background:var(--hover);color:var(--text)}.gh-star .gh-mark{width:12px;height:12px;flex:none}.gh-star .ext{margin-left:auto;font-size:9px}#account-btn{width:100%;display:flex;align-items:center;gap:8px;text-align:left;padding:6px 8px;border:none;border-radius:6px;background:transparent;color:var(--text-dim);cursor:pointer;font:inherit}#account-btn:hover{background:var(--hover);color:var(--text)}#account-btn .avatar{width:24px;height:24px;flex:none;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--text-dim);font-size:11px;font-weight:600}#account-btn .acct{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}#account-btn .acct b{font-size:13px;font-weight:500;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#account-btn .acct small{font-size:12px;color:var(--text-faint);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.sb-menu{min-width:248px;max-width:300px;padding:4px;border:1px solid var(--border-2);border-radius:10px;background:var(--bg-raise);box-shadow:0 12px 32px var(--shadow-pop);z-index:80;outline:none;font-size:13px;color:var(--text)}.sb-menu [role=menuitem]{display:flex;align-items:center;gap:8px;height:32px;padding:0 8px;border-radius:6px;color:var(--text);font:inherit;font-size:13px;text-decoration:none;cursor:pointer;outline:none}.sb-menu [role=menuitem][data-highlighted]{background:var(--hover)}.sb-menu [role=menuitem]>.ico{width:16px;height:16px;color:var(--text-dim)}.sb-menu [role=menuitem][aria-current=page]{background:var(--row-on, var(--hover))}.sb-menu .label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-menu .label.dim{color:var(--text-dim)}.sb-menu .meta{flex:none;margin-left:auto;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-menu .ext{flex:none;font-size:10px;color:var(--text-faint)}.sb-menu .plan-chip{margin-left:auto;color:var(--accent-ink);border-color:var(--border-2)}.sb-menu-projects{max-height:224px;overflow-y:auto}.sb-menu [role=separator]{height:1px;margin:4px -4px;background:var(--border)}.sb-menu-label{padding:6px 8px 2px;font-size:12px;font-weight:400;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-theme{display:flex;align-items:center;height:32px;padding:0 4px 0 8px}.sb-theme>.label{flex:1;color:var(--text-dim)}.sb-theme .seg{display:inline-flex;gap:2px;padding:2px;border-radius:7px;background:var(--hover)}.sb-menu .seg-item{width:26px;height:22px;padding:0;display:grid;place-items:center;border-radius:5px;color:var(--text-faint);cursor:pointer;outline:none}.sb-menu .seg-item>span:first-child{display:none}.sb-menu .seg-item .ico{width:14px;height:14px}.sb-menu .seg-item[data-highlighted]{color:var(--text)}.sb-menu .seg-item[data-state=checked]{background:var(--bg-raise);color:var(--text);box-shadow:0 0 0 1px var(--border-2)}#billing-view .plan-chip{color:var(--accent-ink)}.plan-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:700px){.plan-grid{grid-template-columns:1fr}}.usage-bar{background:var(--surface);border:1px solid var(--border);border-radius:4px;height:6px;overflow:hidden}.usage-bar>div{background:var(--accent);height:100%}.plan-price{font-size:20px;font-weight:700;margin:0 0 10px}.plan-price small{font-size:12px;color:var(--text-dim);font-weight:500}.muted-note{color:var(--text-dim);font-size:13px}#main{flex:1;display:flex;flex-direction:column;min-width:0}#topbar{position:relative;display:flex;align-items:center;gap:9px;height:52px;padding:0 16px;border-bottom:1px solid var(--border)}.icon-btn{display:none;width:34px;height:34px;border:none;background:transparent;color:var(--text-dim);cursor:pointer;border-radius:7px;align-items:center;justify-content:center}.icon-btn:hover{color:var(--text);background:var(--hover)}#menu-btn{display:inline-flex}@media(min-width:901px){body.sb-collapsed #sidebar{width:48px;min-width:48px}body.sb-collapsed #sidebar>:not(#rail){display:none}body.sb-collapsed #rail{display:flex}}#sb-resize{position:absolute;top:0;right:0;bottom:0;width:6px;z-index:50;cursor:col-resize;touch-action:none}#sb-resize:hover,#sb-resize:focus-visible,body.sb-resizing #sb-resize{background:color-mix(in srgb,var(--text) 18%,transparent);outline:none}body.sb-resizing{cursor:col-resize;-webkit-user-select:none;user-select:none}@media(max-width:900px){#sb-resize{display:none}}#nav-btns{display:inline-flex;gap:2px;flex:none}.nav-btn{display:inline-flex;width:30px;height:30px;border:none;background:transparent;color:var(--text-dim);cursor:pointer;border-radius:7px;align-items:center;justify-content:center}.nav-btn:hover{color:var(--text);background:var(--hover)}.nav-btn .ico{width:17px;height:17px}#crumb{font-size:12.5px;color:var(--text);font-weight:500;letter-spacing:-.01em;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#crumb .crumb-seg{color:var(--text-dim);cursor:pointer}#crumb .crumb-seg:hover{color:var(--accent-bright)}#crumb .crumb-sep{color:var(--text-ghost);margin:0 6px}#crumb .crumbs{display:inline-flex;align-items:baseline;min-width:0;max-width:100%;vertical-align:bottom}#crumb .crumb{display:inline-flex;align-items:baseline;min-width:0;flex:none}#crumb .crumb-mid{display:inline-block;max-width:12ch;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:bottom}#crumb .crumb:last-child{flex:0 1 auto;min-width:0;overflow:hidden}#crumb .crumb-last{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#meta{flex:1;min-width:0;font-size:12px;color:var(--text-faint);text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.meta-stale{color:var(--danger-ink)}.btn{display:inline-flex;align-items:center;gap:6px;flex:none;height:30px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text-dim);font-size:12.5px;font-weight:500;cursor:pointer;text-decoration:none}.btn:hover{background:var(--hover);color:var(--text);border-color:var(--border-2)}.btn .ico{width:15px;height:15px}.btn.ghost{color:var(--text-dim)}.tipcard{display:flex;align-items:center;gap:7px;white-space:nowrap;padding:6px 9px;border-radius:8px;border:1px solid var(--border-2);background:var(--surface-solid, var(--bg-raise));color:var(--text);font-size:12.5px;font-weight:500;box-shadow:0 8px 24px var(--shadow-pop);z-index:80}.tipcard kbd{font:11px var(--ui);color:var(--text-faint);background:var(--hover);border:1px solid var(--border-2);border-radius:5px;padding:1px 5px}#more-menu{position:absolute;right:12px;top:calc(100% - 4px);z-index:80;background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-card);box-shadow:0 18px 44px -14px #000000bf;padding:6px;min-width:168px}:root[data-theme=light] #more-menu{box-shadow:0 18px 44px -14px #0000002e}.more-item{display:block;width:100%;text-align:left;min-height:40px;padding:0 12px;background:transparent;border:none;cursor:pointer;color:var(--text);font:inherit;font-size:13.5px;border-radius:var(--r-ctl)}.more-item:hover{background:var(--hover)}#content{--content-pad-b: 110px;flex:1;overflow-y:auto;padding:44px 40px var(--content-pad-b);scroll-behavior:smooth;scrollbar-gutter:stable}@media(pointer:fine){#content::-webkit-scrollbar{width:10px}#content::-webkit-scrollbar-thumb{background:var(--border-2);border-radius:5px}#content::-webkit-scrollbar-track{background:transparent}@supports not selector(::-webkit-scrollbar){#content{scrollbar-width:thin;scrollbar-color:var(--border-2) transparent}}}.page{width:100%;max-width:var(--page-app);margin-inline:auto;min-width:0}.page.read{max-width:var(--page-read)}.page.wide{max-width:var(--page-wide)}.page.read{position:relative}.rw-handle{position:absolute;top:0;bottom:0;width:14px;z-index:5;cursor:col-resize;touch-action:none;outline:none}.rw-left{left:-26px}.rw-right{right:-26px}.rw-handle:after{content:"";position:absolute;top:0;bottom:0;left:6px;width:2px;border-radius:1px;background:var(--border-2);opacity:0;transition:opacity .12s ease}.rw-handle:hover:after,.rw-handle:focus-visible:after{opacity:1}.rw-handle.dragging:after{opacity:1;background:var(--accent)}body.rw-dragging{cursor:col-resize;-webkit-user-select:none;user-select:none}@media(max-width:900px){.rw-handle{display:none}}.empty{color:var(--text-faint);text-align:center;margin-top:var(--hero-top)}.empty-hint{display:block;margin-top:6px;font-size:12px;color:var(--text-faint)}.onboard{max-width:560px;margin:var(--hero-top) auto 0}.onboard h1{font-size:25px;font-weight:640;letter-spacing:-.02em;margin:0 0 8px;color:var(--text-bright)}.onboard>p{color:var(--text-dim);margin:0 0 28px;font-size:14px}.ob-card,.setup-card{border:1px solid var(--border);border-radius:var(--r-card)}.ob-card{background:var(--bg-side);padding:20px 22px;margin-bottom:14px}.ob-card h3{margin:0 0 6px;font-size:14.5px;font-weight:600}.ob-card p{margin:0 0 14px;font-size:13px;color:var(--text-dim)}.ob-card.ob-start{border-color:var(--border-2);box-shadow:inset 2px 0 0 var(--accent)}.ob-card.ob-start .pbtn{margin-top:2px}.ob-alt{margin:12px 0 0}.ob-alt a{color:var(--text-faint);font-size:12.5px;font-weight:600;text-decoration:none}.ob-alt a:hover{color:var(--text)}.pbtn{display:inline-flex;align-items:center;gap:6px;flex:none;height:32px;padding:0 14px;border-radius:var(--r-ctl);border:none;background:var(--accent);color:#241704;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;text-decoration:none}.pbtn:hover{background:var(--accent-hover-bg)}.pbtn .ico{width:15px;height:15px}.danger-btn{display:inline-flex;align-items:center;height:32px;padding:0 14px;border-radius:var(--r-ctl);border:none;background:#b3382e;color:#fff;font-size:13px;font-weight:600;cursor:pointer}.danger-btn:hover{background:#c94336}[data-slot=input],[data-slot=textarea]{font:inherit;color:var(--text)}[data-slot=input][aria-invalid=true]:focus-visible,[data-slot=textarea][aria-invalid=true]:focus-visible{border-color:var(--del)}[data-slot=card],[data-slot=dropdown-menu-content]{border-color:var(--border)}.project-settings{display:flex;flex-direction:column;gap:14px}.project-settings>h2{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.ps-form{display:flex;flex-direction:column;gap:18px}.ps-field{display:flex;flex-direction:column;gap:7px}.ps-field label{font-size:12.5px;color:var(--text-dim)}.ps-opt{color:var(--text-ghost);font-weight:400}.ps-icon-row{display:flex;align-items:center;gap:10px}.ps-icon-row .proj-mark{width:26px;height:26px;border-radius:7px}.ps-icon-row .proj-mark svg{width:15px;height:15px}.ps-meta{display:flex;align-items:baseline;justify-content:space-between;gap:12px}.ps-meta .field-err{flex:0 1 auto;margin:0}.ps-count{font-size:11.5px;color:var(--text-faint);font-variant-numeric:tabular-nums}.ps-actions{display:flex;justify-content:flex-end}.ps-icon-grid{display:grid;grid-template-columns:repeat(6,30px);gap:4px;padding:8px}.ps-icon-cell{display:grid;place-items:center;width:30px;height:30px;border-radius:7px;border:1px solid transparent;background:none;color:var(--text-dim);cursor:pointer}.ps-icon-cell svg{width:16px;height:16px}.ps-icon-cell:hover{background:var(--hover);color:var(--text)}.ps-icon-cell.active{border-color:var(--accent);color:var(--accent-bright)}.ps-danger [data-slot=card-title]{font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--danger-title);font-weight:600}.mcp-projects{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 14px}.mcp-projects .ps-chip{margin-left:0}.ps-chip{margin-left:10px;padding:2px 8px;border-radius:999px;border:1px solid var(--border);background:var(--surface);color:var(--text-faint);font-size:11px;font-weight:600;letter-spacing:.02em;vertical-align:middle}.ps-people h4{font-size:12.5px;font-weight:600;color:var(--text-dim);margin:0}.ps-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:13px;color:var(--text-dim);margin:0 0 10px}.ps-people select{height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px}.ps-people select:disabled{opacity:.6;cursor:default}.ps-note{color:var(--text-faint);font-size:12.5px;margin:0 0 12px;max-width:56ch;line-height:1.55}.ps-people-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:20px 0 8px}.ps-danger p{color:var(--text-dim);font-size:13px;margin:0 0 14px;max-width:52ch;line-height:1.55}.ps-facts{display:grid;grid-template-columns:auto 1fr;gap:8px 20px;margin:0;font-size:13px}.ps-facts dt{color:var(--text-faint)}.ps-facts dd{margin:0;color:var(--text-dim)}.ps-export{margin:16px 0 0;max-width:62ch}.ps-export code{font-size:12px;padding:1px 5px;border-radius:4px;background:var(--surface);border:1px solid var(--border);color:var(--text)}.ps-export a{color:var(--accent-bright);text-decoration:none}.admin h1{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright)}.admin h3{font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600;margin:30px 0 10px}.admin-lbl{flex:1 1 100%;margin:0 0 6px;font-size:12.5px;font-weight:600;color:var(--text-dim)}.admin-sub{color:var(--text-dim);font-size:13.5px;margin:-2px 0 16px;line-height:1.55}.admin-h{display:flex;align-items:center;justify-content:space-between;margin:30px 0 10px}.admin-h h3{margin:0}.admin-row{display:flex;gap:9px;margin-bottom:8px}.admin-row input{flex:1;height:34px;padding:0 12px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:13px;outline:none}.admin-row input:focus{border-color:var(--accent);background:var(--hover)}.admin-list{border:1px solid var(--border);border-radius:var(--r-card);overflow:hidden;background:var(--bg-side)}.admin-list.admin-card-table{overflow-x:auto;overflow-y:hidden}.admin-item{display:flex;align-items:center;gap:11px;padding:11px 14px;border-bottom:1px solid var(--border);font-size:13.5px}.modal-actions .ai-btn{height:32px}.empty a{color:var(--accent-ink);text-decoration:none;display:inline-block;padding:6px 10px}.empty a:hover{text-decoration:underline}.empty h3{margin:0 0 8px;font-size:16px;color:var(--text)}.ai-copy{text-align:left;background:none;border:0;padding:6px 0;cursor:pointer}.ai-copy:hover{color:var(--text)}a.ai-main{color:var(--text-dim);text-decoration:none;padding:6px 0}a.ai-main:hover{color:var(--accent-ink)}.th-sort{display:block;width:100%;text-align:left;background:none;border:0;padding:6px 10px;font:inherit;color:inherit;letter-spacing:inherit;text-transform:inherit;cursor:pointer}.th-sort:hover{color:var(--text-dim)}.role-cell{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center;justify-items:start}.admin-table td .role-static{text-align:left}.role-chip-row{margin:-6px 0 12px}.role-chip{margin-left:0;padding:2px 8px;border:1px solid var(--border-2);border-radius:99px;vertical-align:middle}.ext{margin-left:4px;color:var(--text-faint);font-size:11px}.admin-item:last-child{border-bottom:none}.admin-item:hover{background:var(--hover)}.field-err{flex:1 1 100%;margin:6px 0 0}.admin-row{flex-wrap:wrap}.admin-row input[aria-invalid=true]{border-color:var(--del)}.ai-main{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}.admin-item>.ai-main{flex:1 1 55%;min-width:22ch}.admin-item>.ai-tag{flex:0 0 auto;min-width:0;max-width:45%}@media(max-width:1000px){.admin-item{flex-wrap:wrap}.admin-item>.ai-tag{flex:1 1 100%;max-width:100%}}.admin-table td .ai-main{min-width:0}.ai-main.mono{font:12px var(--mono);color:var(--text-dim);cursor:pointer}.ai-tag{font-size:11.5px;color:var(--text-faint);flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.admin-item select{height:28px;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:0 8px;font:inherit;font-size:12.5px;cursor:pointer}.admin-item select:hover{border-color:var(--border-2)}.ai-btn,.ai-del{flex:none;height:27px;padding:0 11px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:var(--text-dim);font:inherit;font-size:12px;font-weight:500;cursor:pointer}.ai-del{color:var(--del);border-color:#f26d6d47}.ai-del:hover{background:#f26d6d1f;border-color:var(--del);color:var(--danger-bright)}.ai-btn:hover{background:var(--hover);color:var(--text);border-color:var(--border-2)}.admin-empty{padding:14px;color:var(--text-faint);font-size:13px}.admin-item.toggle{cursor:pointer;align-items:flex-start}.admin-item.toggle .ai-main{white-space:normal}.tg-label{font-size:13.5px;font-weight:550;color:var(--text)}.tg-desc{font-size:12px;color:var(--text-faint);margin-top:3px;line-height:1.5}.admin-item.toggle input{margin-top:2px;flex:none}.dl-title{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.dl-title-icon{display:flex;color:var(--accent-ink)}.dl-title-icon .ico{width:20px;height:20px}.dl-sub{color:var(--text-faint);font-size:12.5px;margin:0 0 18px}.dl-heatnote{color:var(--text-faint);font-size:12px;opacity:.8;margin:-14px 0 18px}.dl-items{border:1px solid var(--border);border-radius:var(--r-card);overflow:hidden;background:var(--bg-side)}.dl-row{display:flex;align-items:center;gap:11px;padding:10px 14px;border-bottom:1px solid var(--border);cursor:pointer}.dl-row:last-child{border-bottom:none}.dl-row:hover{background:var(--hover)}.dl-row .ticon{flex:none;display:flex;color:var(--text-ghost)}.dl-row .ticon .ico{width:16px;height:16px}.dl-row:hover .ticon{color:var(--text-faint)}.dl-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13.5px;color:var(--text)}.dl-name,#crumb,.hpath,.hnote,.hrun-note,.hdev,.ai-main,.hc-name,.hc-dir,.fe-who,.fe-path,.fe-dev,.dev-name,.ha-title,.ha-sub,.hb-label>span:first-child{unicode-bidi:isolate-override;direction:ltr}.dl-meta{flex:none;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums}.dl-conflict{flex:none;font-size:10.5px;line-height:1;letter-spacing:.02em;text-transform:uppercase;padding:3px 6px;border-radius:999px;border:1px solid var(--accent-dim);background:var(--glow);color:var(--accent-bright);white-space:nowrap}.trestricted{flex:none;display:inline-flex;align-items:center;margin-left:5px;color:var(--text-faint)}.trestricted svg{width:11px;height:11px}.dl-restricted{flex:none;font-size:10.5px;line-height:1;letter-spacing:.02em;text-transform:uppercase;padding:3px 6px;border-radius:999px;border:1px solid var(--border-2);background:var(--surface);color:var(--text-dim);white-space:nowrap}.heatdot{flex:none;width:7px;height:7px;border-radius:50%;background:var(--accent)}.heatdot.lvl1{opacity:.3}.heatdot.lvl2{opacity:.55}.heatdot.lvl3{opacity:.8}.heatdot.lvl4{opacity:1;box-shadow:0 0 6px #f5a6238c}.stalemark{flex:none;font-size:11px;line-height:1;color:var(--danger-ink)}.dl-empty{padding:24px 14px;color:var(--text-faint);font-size:13px;border:1px dashed var(--border);border-radius:var(--r-card);text-align:center}.dl-h3{margin:28px 0 8px;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600}.dl-hlist{border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);overflow:hidden;max-width:none}.dl-hlist .hentry:last-child{border-bottom:none}.hentry.clickable{cursor:pointer}.hentry.clickable:hover{background:var(--hover)}.dl-more{margin-top:10px}#vault-name.vault-link{cursor:pointer}#vault-name.vault-link:hover{color:var(--accent-bright)}.gd-body{margin-top:18px}.gd-desc{margin:2px 0 8px;color:var(--text-faint);font-size:13px;line-height:1.5}.gd-list{margin:4px 0 8px;padding-left:18px;display:grid;gap:6px}.gd-code{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:10px;margin:6px 0 10px;padding:10px 12px;background:var(--bg-raise);border:1px solid var(--border);border-radius:var(--r-card);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;line-height:1.6;color:var(--text)}.gd-code>code{display:block;min-width:0;overflow-x:auto;white-space:pre}.gd-copy{align-self:start;font:inherit;font-family:inherit;font-size:11px;font-weight:600;padding:3px 9px;border-radius:6px;border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text-faint);cursor:pointer}.gd-copy:hover{color:var(--accent-bright);border-color:var(--accent-dim)}.gd-manual{margin:10px 0 0}.gd-manual>summary{display:inline-block;font-size:12.5px;font-weight:600;color:var(--text-faint);cursor:pointer;padding:4px 0}.gd-manual>summary:before{content:"▸ ";color:var(--text-ghost)}.gd-manual[open]>summary:before{content:"▾ "}.gd-manual>summary:hover{color:var(--text)}.home-insights{margin-top:30px;padding-top:22px;border-top:1px solid var(--border)}.in-title{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.in-title .in-scope{color:var(--text-ghost);font-weight:500;font-size:15px}.gd-head{display:flex;align-items:center;gap:9px}.gd-head .proj-mark{width:22px;height:22px;border-radius:6px}.gd-head .proj-mark svg{width:13px;height:13px}.in-desc{color:var(--text-dim);font-size:13.5px;line-height:1.55;margin:0 0 10px;max-width:62ch}.in-blank{display:grid;justify-items:center;gap:10px;padding:40px 18px;margin-top:14px;max-width:760px}.in-blank p{margin:0;max-width:52ch;line-height:1.55}.in-blank p:first-child{color:var(--text);font-size:14.5px;font-weight:600}.in-blank .pbtn{margin-top:6px}.in-top{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:4px}.in-top .in-title{margin:0}.in-lens{display:inline-flex;gap:2px;padding:2px;border-radius:var(--r-ctl);background:var(--hover)}.in-lens-btn{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;border:none;background:none;color:var(--text-faint);cursor:pointer;display:inline-flex;align-items:center;gap:6px}.in-lens-btn:hover{color:var(--text)}.in-lens-btn.active{color:var(--text-bright);background:var(--bg-raise)}.in-lens-btn .in-sw{width:8px;height:8px}.in-sec{margin:30px 0 0;min-width:0}.in-sec-head{display:flex;justify-content:space-between;align-items:flex-end;gap:12px;flex-wrap:wrap;margin-bottom:10px}.in-h2{font-size:16px;font-weight:640;color:var(--text-bright);margin:0 0 3px;letter-spacing:-.01em}.in-sub{margin:0;font-size:12.5px;color:var(--text-faint)}.in-sec-tools{display:flex;align-items:center;gap:10px}.in-astable{font:inherit;font-size:11.5px;padding:3px 9px;border-radius:var(--r-ctl);border:1px solid var(--border);background:none;color:var(--text-faint);cursor:pointer}.in-astable:hover,.in-astable[aria-pressed=true]{color:var(--text);border-color:var(--border-2)}.in-table-wrap{max-height:420px;overflow:auto;border:1px solid var(--border);border-radius:var(--r-card)}.in-data-table{width:100%;border-collapse:collapse;font-size:12px}.in-data-table th,.in-data-table td{padding:5px 10px;border-bottom:1px solid var(--border);text-align:left;white-space:nowrap}.in-data-table th{position:sticky;top:0;background:var(--bg-side);color:var(--text-faint);font-weight:600}.in-data-table td{color:var(--text);font-variant-numeric:tabular-nums}.in-split{display:grid;grid-template-columns:minmax(0,680fr) minmax(0,380fr);gap:28px;align-items:start}.in-split>.in-sec{margin-top:30px}.in-sec-hot>.in-sec{margin-top:14px}.in-sec-hot>.in-sec .in-h2{font-size:13px}@media(max-width:1100px){.in-split{grid-template-columns:minmax(0,1fr)}}.in-flag{display:inline-block;font-size:12px;line-height:1;margin-right:5px}.in-flag-stale{color:var(--warn-ink)}.in-flag-empty{color:var(--del)}.in-kpis{display:grid;grid-template-columns:minmax(0,1.3fr) repeat(3,minmax(0,1fr));border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin-top:18px}.in-kpi{padding:14px 16px;border-left:1px solid var(--border);min-width:0}.in-kpi:first-child{border-left:none}.in-kpi-l{font-size:12px;color:var(--text-faint)}.in-kpi-v{font-size:26px;font-weight:660;color:var(--text-bright);letter-spacing:-.02em;display:flex;align-items:baseline;gap:8px;margin:4px 0 8px;font-variant-numeric:tabular-nums}.in-kpi-v small{font-size:12px;font-weight:500;color:var(--text-faint)}.in-kpi-bar{display:flex;gap:2px;height:5px;border-radius:3px;overflow:hidden;margin-bottom:7px}.in-kpi-bar>span{min-width:2px}.in-kpi-meter{background:var(--hover)}.in-kpi-fill{background:var(--viz-fresh-1);border-radius:3px}.in-kpi-n{font-size:11.5px;color:var(--text-faint);display:flex;flex-wrap:wrap;gap:4px 10px}.in-kpi[data-kpi=reads] .in-kpi-n{flex-wrap:nowrap;gap:8px;white-space:nowrap}.in-status{font-size:11px;font-weight:600;padding:2px 7px;border-radius:5px;letter-spacing:0}.in-status-warn{color:var(--warn-ink);background:color-mix(in srgb,var(--warn-ink) 14%,transparent)}.in-status-crit{color:var(--del);background:color-mix(in srgb,var(--del) 14%,transparent)}@media(max-width:900px){.in-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.in-kpi:nth-child(3){border-left:none}.in-kpi:nth-child(n+3){border-top:1px solid var(--border)}.in-kpi[data-kpi=reads] .in-kpi-n{flex-wrap:wrap;gap:4px 10px}}.in-thresholds{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--text);border:1px solid var(--border);border-radius:var(--r-ctl);padding:3px 10px}.in-thresholds input{width:44px;font:inherit;font-size:12px;padding:1px 4px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--text-bright);text-align:right}.in-fix-none{padding:14px;font-size:13px;color:var(--text-faint);border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side)}.in-fix-table{width:100%;border-collapse:collapse;border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);font-size:13px}.in-fix-table th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600;padding:9px 12px;border-bottom:1px solid var(--border)}.in-fix-table td{padding:8px 12px;border-bottom:1px solid var(--border);vertical-align:middle}.in-fix-row:last-child td{border-bottom:none}.in-fx-file{display:flex;align-items:center;max-width:320px}.in-fx-name{display:grid;min-width:0}.in-fx-name>span,.in-fx-name small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.in-fx-name>span{color:var(--text-bright)}.in-fx-name small{font-family:var(--mono);font-size:11px;color:var(--text-faint)}.in-fx-reads{width:30%}.in-fx-reads{display:table-cell}.in-fx-track{display:inline-flex;width:calc(100% - 44px);vertical-align:middle}.in-fx-bar{display:flex;gap:2px;height:7px;border-radius:3px;overflow:hidden}.in-fx-n{display:inline-block;width:38px;text-align:right;font-size:12px;color:var(--text);font-variant-numeric:tabular-nums}.in-fx-when{color:var(--text-dim);white-space:nowrap}.in-fx-when.empty{color:var(--del)}.in-fx-why{color:var(--text-body)}.in-fx-act{text-align:right}.in-fx-act .pbtn{height:26px;font-size:12px;padding:0 11px}.in-fx-review{font:inherit;font-size:12px;height:26px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:none;color:var(--text);cursor:pointer}.in-fx-review:hover{background:var(--hover)}@media(max-width:800px){.in-fx-why,.in-fix-table th:nth-child(4){display:none}}.in-chart{display:block;width:100%;max-width:760px;height:auto;border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin-bottom:6px}.in-axis{stroke:var(--border);stroke-width:1}.in-threshold{stroke:var(--warn-ink);stroke-opacity:.45;stroke-width:1;stroke-dasharray:4 4}.in-danger-zone{fill:var(--warn-ink);fill-opacity:.06}.in-label,.in-tick{fill:var(--text-faint);font-size:11px}.in-tick{font-size:10px;font-variant-numeric:tabular-nums}.in-quad{fill:var(--text-faint);font-size:10.5px;text-transform:uppercase;letter-spacing:.06em}.in-quad-danger{fill:var(--warn-ink);font-weight:650}.in-quad-count{fill:var(--warn-ink);font-size:10.5px;font-weight:650}.in-pt{fill:var(--text-faint);fill-opacity:.35;cursor:pointer}.in-pt:hover{fill-opacity:.9}.in-pt.danger{fill:var(--warn-ink);fill-opacity:1;stroke:var(--bg-side);stroke-width:2;paint-order:stroke}.in-pt.empty{fill:var(--del);fill-opacity:1;stroke:var(--bg-side);stroke-width:2;paint-order:stroke}.in-pt-label{fill:var(--text);font-size:11px;pointer-events:none}.in-cap{font-size:11.5px;color:var(--text-faint);font-weight:400}.in-sw-other{background:var(--text-faint);opacity:.5;border-radius:50%}.in-sw-stale{background:var(--warn-ink);border-radius:50%}.in-sw-empty{background:var(--del);border-radius:50%}.in-treemap{background:var(--bg-side)}.in-tm-cell{cursor:pointer;stroke:var(--bg-side);stroke-width:1}.in-tm-cell:hover{stroke:var(--text)}.in-tm-b1{fill:var(--viz-fresh-1);background:var(--viz-fresh-1)}.in-tm-b2{fill:var(--viz-fresh-2);background:var(--viz-fresh-2)}.in-tm-b3{fill:var(--viz-fresh-3);background:var(--viz-fresh-3)}.in-tm-b4{fill:var(--viz-fresh-4);background:var(--viz-fresh-4)}.in-tm-flat{fill:var(--viz-flat)}.in-tm-cell.flag-stale{stroke:var(--warn-ink);stroke-width:2.5}.in-tm-cell.flag-empty{stroke:var(--del);stroke-width:2.5}.in-tm-label{fill:var(--viz-ink-dark);font-size:11.5px;font-weight:620;cursor:pointer;pointer-events:none}.in-tm-label.on-dark{fill:var(--viz-ink-light)}.in-tm-sub{font-weight:450;font-size:10.5px;fill-opacity:.8}.in-tm-crumbs{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-faint);margin-bottom:8px}.in-tm-crumbs button{font:inherit;background:none;border:none;padding:0;color:var(--accent-ink);cursor:pointer}.in-tm-crumbs button.cur,.in-tm-crumbs .cur{color:var(--text)}.in-tm-crumbs .in-tm-open{margin-left:8px;color:var(--text-faint);text-decoration:underline}.in-tm-hint{margin-left:4px}.in-tm-legend{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px}.in-tm-key{display:inline-flex;align-items:center;gap:5px}.in-sw-age{display:inline-flex;gap:12px}.in-sw-flat{filter:grayscale(1);opacity:.45}.in-tm-range{color:var(--text-faint);flex-basis:100%}.in-hotpath{position:relative;display:grid;gap:2px}.in-hotpath>.in-sw{display:none}.in-hp-total{font-size:11.5px;color:var(--text-faint);font-variant-numeric:tabular-nums}.in-hp-row{display:grid;gap:4px;padding:4px 6px;border-radius:5px;cursor:pointer}.in-hp-row:hover{background:var(--hover)}.in-hp-line{display:flex;align-items:baseline;gap:8px;min-width:0}.in-hp-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12.5px;color:var(--text)}.in-hp-bar{display:flex;height:5px}.in-hp-bar>span{border-radius:3px}.in-hp-agent{background:var(--viz-agent)}.in-hp-human{background:var(--viz-human)}.in-hp-share{background:var(--viz-share)}.in-hp-none{font-size:12px;color:var(--text-faint);padding:6px}.in-hp-gone{flex:none;font-size:11.5px;color:var(--text-faint);white-space:nowrap}.in-hp-count{flex:none;text-align:right;font-size:11.5px;color:var(--text);font-variant-numeric:tabular-nums}.in-legend{margin:8px 2px 0;font-size:11.5px;color:var(--text-faint)}.in-sw{display:inline-block;width:10px;height:10px;border-radius:2px;vertical-align:-1px}.in-sw.agent{background:var(--viz-agent)}.in-sw.human{background:var(--viz-human)}.in-sw.share{background:var(--viz-share)}.in-cov{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:26px;align-items:start}@media(max-width:1000px){.in-cov{grid-template-columns:minmax(0,1fr)}}.in-matrix-wrap{overflow-x:auto}.in-matrix{border-collapse:separate;border-spacing:3px;font-size:11.5px}.in-matrix th{font-weight:500;color:var(--text-faint);padding:0 4px;white-space:nowrap}.in-matrix thead th{font-size:11px;text-align:center}.in-matrix tbody th{text-align:left;color:var(--text);max-width:170px;overflow:hidden;text-overflow:ellipsis}.in-cv{min-width:46px;height:24px;text-align:center;border-radius:4px;font-variant-numeric:tabular-nums}.in-cv-0{background:var(--viz-cov-0);color:var(--text-faint)}.in-cv-1{background:var(--viz-cov-1);color:var(--viz-cov-ink-1)}.in-cv-2{background:var(--viz-cov-2);color:var(--viz-cov-ink-2)}.in-cv-3{background:var(--viz-cov-3);color:var(--viz-ink-dark)}.in-cv-4{background:var(--viz-cov-4);color:var(--viz-ink-dark)}.in-cv-total{text-align:right;color:var(--text);padding-left:10px;font-variant-numeric:tabular-nums}.in-cv-legend{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center}.in-takeaways h3{margin:0 0 10px;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600}.in-takeaway{display:flex;gap:9px;margin-bottom:12px;font-size:12.5px}.in-takeaway b{color:var(--text-bright);font-weight:600}.in-takeaway p{margin:3px 0 0;color:var(--text-dim);line-height:1.45}.in-tk-ico{flex:none;margin-top:2px;color:var(--accent-ink)}.hfilters{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:0 0 12px;border-bottom:1px solid var(--border);margin-bottom:4px}.hf-search{position:relative;display:flex;align-items:center;flex:1 1 200px;min-width:160px}.hf-search .ico{position:absolute;left:9px;width:14px;height:14px;color:var(--text-ghost);pointer-events:none}.hf-search input{height:30px;padding-left:29px;font-size:12.5px;border-radius:var(--r-ctl);background:var(--surface)}.hf-search input::-webkit-search-cancel-button{filter:invert(.6)}.hf-user{height:30px;max-width:190px;padding:0 8px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-dates{display:flex;align-items:center;gap:6px}.hf-lbl{font-size:10px;letter-spacing:.06em;text-transform:uppercase;color:var(--text-ghost)}.hf-date{width:140px;height:30px;font-size:12.5px;border-radius:var(--r-ctl);background:var(--surface)}.hf-date::-webkit-calendar-picker-indicator{filter:invert(.6);cursor:pointer}.hf-dash{color:var(--text-ghost)}.hf-clear{height:30px;padding:0 10px;border:none;border-radius:var(--r-ctl);background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.hf-clear:hover{color:var(--text);background:var(--hover)}.hf-clear-empty{margin-top:12px}.hf-search input::placeholder{color:var(--text-faint)}.hf-seg{display:inline-flex;padding:2px;gap:2px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface)}.hf-seg button{height:24px;padding:0 10px;border:none;border-radius:5px;background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.hf-seg button:hover{color:var(--text)}.hf-seg button[aria-pressed=true]{background:var(--hover);color:var(--text-bright);font-weight:560}.hf-pick{position:relative;display:inline-flex;align-items:center}.hf-pick .ico{position:absolute;left:8px;width:14px;height:14px;color:var(--text-faint);pointer-events:none}.hf-device,.hf-range{height:30px;max-width:190px;padding:0 8px 0 27px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-chip{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 8px 0 10px;border:1px solid var(--border);border-radius:6px;background:var(--hover);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-chip .ico{width:12px;height:12px;color:var(--text-faint)}.hf-chip:hover .ico{color:var(--text)}.hsum{padding:18px 0 6px}.hsum-wait{min-height:150px}.hsum-head{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap}.hsum-total{font-size:21px;font-weight:640;letter-spacing:-.02em;color:var(--text-bright)}.hsum-sub{margin-top:2px;font-size:12.5px;color:var(--text-dim)}.hsum-range{color:var(--text-faint)}.hsum-legend{display:flex;gap:14px;font-size:12px;color:var(--text-dim)}.hsum-legend span:before{content:"";display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:2px;vertical-align:0}.hsum-legend .agent:before{background:var(--viz-agent)}.hsum-legend .human:before{background:var(--viz-human)}.hsum-bars{display:flex;gap:6px;height:104px;margin-top:14px}.hsum-bars.dense{gap:2px}.hsum-col{flex:1;display:flex;flex-direction:column;min-width:0}.hsum-stack{flex:1;display:flex;flex-direction:column-reverse;justify-content:flex-start;border-bottom:1px solid var(--border)}.hsum-stack span{display:block;min-height:0}.hsum-stack .agent{background:var(--viz-agent);border-radius:0 0 2px 2px}.hsum-stack .human{background:var(--viz-human);border-radius:3px 3px 0 0}.hsum-col.today .hsum-stack .agent{background:var(--accent)}.hsum-day{margin-top:5px;text-align:center;font-size:11px;color:var(--text-faint);white-space:nowrap}.hsum-col.today .hsum-day{color:var(--text-bright);font-weight:600}.hday{display:flex;align-items:center;gap:6px;margin:18px 0 6px;font-size:13px;color:var(--text-faint)}.hday b{color:var(--text-bright);font-weight:600}.hday:after{content:"";flex:1;height:1px;margin-left:6px;background:var(--border)}.hentry.sel{background:var(--glow);box-shadow:inset 2px 0 0 var(--accent)}.hentry.delete .hpath{text-decoration:line-through;color:var(--danger-ink)}.hgone{color:var(--text-faint)}.hstat{display:inline-flex;gap:6px;flex:none;font-family:var(--mono);font-size:11.5px;font-variant-numeric:tabular-nums}.hstat .dv-add,.hstat .dv-del{font-weight:500}.hsel-btn{flex:none;height:22px;padding:0 8px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hsel-btn{margin-left:auto}.hsel-btn:hover,.hsel-btn[aria-pressed=true]{color:var(--text);background:var(--hover);border-color:var(--border-2)}.hresolve-btn.pbtn{height:22px;padding:0 10px;font-size:12px}.havatar{display:grid;place-items:center;flex:none;width:26px;height:26px;border-radius:50%;background:var(--glow);color:var(--accent-ink)}.havatar .ico{width:14px;height:14px}.hrun-title{flex:1;display:flex;flex-direction:column;min-width:0;gap:2px}.hrun-sub{display:flex;gap:6px;min-width:0;font-size:12px;color:var(--text-faint)}.hrun-sub .hrun-meta:before{content:"· "}.hrun-what{color:var(--text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.hrun-what b{color:var(--text-bright);font-weight:600}.hrun-title .hrun-note{flex-shrink:1;min-width:0;max-width:50%;font-weight:400;color:var(--text-faint)}.hempty{display:flex;flex-direction:column;align-items:center;gap:10px;padding:48px 16px;text-align:center}.hempty b{color:var(--text-bright);font-size:15px;font-weight:600}.hempty-icon{display:grid;place-items:center;width:44px;height:44px;border-radius:var(--r-card);background:var(--hover);color:var(--text-dim)}.hempty-icon .ico{width:20px;height:20px}.herror-icon{background:#f26d6d1f;color:var(--del)}.hchips{display:flex;flex-wrap:wrap;justify-content:center;gap:6px}.hempty-hint{max-width:46ch;font-size:13px;color:var(--text-dim)}.hempty-actions{display:flex;gap:8px;margin-top:4px}.hempty-actions .hf-clear-empty{margin-top:0}.hskel-row{display:flex;align-items:center;gap:12px;padding:12px 0}.hskel-dot,.hskel-lines span,.hskel-time{background:var(--hover);border-radius:4px;animation:hskel 1.4s ease-in-out infinite}.hskel-dot{flex:none;width:28px;height:28px;border-radius:50%}.hskel-lines{flex:1;display:flex;flex-direction:column;gap:7px}.hskel-lines span{display:block;height:9px}.hskel-time{flex:none;width:40px;height:9px}.hskel-note{margin-top:10px;font-size:12.5px;color:var(--text-faint)}@keyframes hskel{50%{opacity:.45}}.fskel{display:flex;gap:40px;padding-top:8px}.fskel-main{flex:1;min-width:0;display:flex;flex-direction:column;gap:12px}.fskel-title,.fskel-meta span,.fskel-line,.fskel-rail span{display:block;background:var(--hover);border-radius:4px;animation:hskel 1.4s ease-in-out infinite}.fskel-title{width:55%;height:26px;margin-bottom:4px}.fskel-meta{display:flex;gap:12px;margin-bottom:14px}.fskel-meta span{height:10px}.fskel-line{height:11px}.fskel-rail{flex:none;width:200px;display:flex;flex-direction:column;gap:10px;padding-left:16px;border-left:1px solid var(--border)}.fskel-rail span{height:9px}@media(max-width:1399px){.fskel-rail{display:none}}@media(prefers-reduced-motion:reduce){.hskel-dot,.hskel-lines span,.hskel-time,.fskel-title,.fskel-meta span,.fskel-line,.fskel-rail span{animation:none}}.apanel{position:fixed;z-index:40;top:52px;right:0;bottom:0;width:min(460px,100vw);display:flex;flex-direction:column;border-left:1px solid var(--border);background:var(--bg-side);box-shadow:-10px 0 32px var(--shadow-pop);overflow:hidden}.ap-head{display:flex;align-items:center;gap:6px;padding:14px 14px 4px 16px}.ap-head>.ico{width:16px;height:16px;color:var(--text-dim)}.ap-name{flex:1;min-width:0;font-weight:600;font-size:14.5px;color:var(--text-bright);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ap-nav,.ap-close{display:grid;place-items:center;width:26px;height:26px;border:none;border-radius:6px;background:none;color:var(--text-faint);cursor:pointer}.ap-nav:hover:not(:disabled),.ap-close:hover{background:var(--hover);color:var(--text)}.ap-nav:disabled{opacity:.35;cursor:default}.ap-nav .ico,.ap-close .ico{width:15px;height:15px}.ap-nav:not(.down) .ico{transform:rotate(-90deg)}.ap-path{padding:0 16px;font-family:var(--mono);font-size:12px;color:var(--text-faint);overflow-wrap:anywhere}.ap-who{display:flex;align-items:center;gap:6px;padding:8px 16px 0;font-size:12.5px;color:var(--text-dim)}.ap-who .ico{width:14px;height:14px;color:var(--accent-ink)}.ap-actions{display:flex;flex-wrap:wrap;gap:8px;padding:12px 16px 14px;border-bottom:1px solid var(--border)}.dtabs{display:flex;flex-direction:column;min-height:0;flex:1}.dtabs-bar{display:flex;gap:18px;padding:0 16px;border-bottom:1px solid var(--border)}.dtabs-bar button{padding:10px 0 9px;border:none;border-bottom:2px solid transparent;background:none;color:var(--text-faint);font:inherit;font-size:13px;cursor:pointer}.dtabs-bar button[aria-selected=true]{color:var(--text-bright);border-bottom-color:var(--accent);font-weight:560}.dtabs-body{flex:1;overflow:auto;padding:8px 10px 12px}.dtabs-body .dv{margin:0}.dtabs-md{padding:4px 8px;font-size:13.5px}.dtabs-img{max-width:100%}.ap-foot{padding:9px 16px;border-top:1px solid var(--border);font-size:11.5px;color:var(--text-faint)}@media(max-width:700px){.apanel{top:0}}.apanel-empty{display:none}.activity>.history{max-width:var(--page-app);margin-inline:auto}@media(min-width:1200px){.activity.two-zone{display:grid;grid-template-columns:minmax(0,1fr) 440px;column-gap:32px;align-items:start;margin-right:-40px}.activity.two-zone>.history{min-width:0;max-width:none;margin:0}.activity.two-zone>.apanel,.activity.two-zone>.apanel-empty{position:sticky;z-index:1;top:-44px;margin-top:-44px;right:auto;bottom:auto;width:auto;height:calc(100vh - 52px);box-shadow:none}.apanel-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:32px;border-left:1px solid var(--border);background:var(--bg-side);text-align:center;color:var(--text-dim);font-size:13px}.apanel-empty>.ico{width:22px;height:22px;color:var(--text-faint)}.apanel-empty b{color:var(--text-bright);font-size:14px;font-weight:600}.apanel-empty .ap-keys{margin-top:6px;font-size:11.5px;color:var(--text-faint)}.apanel-empty kbd{padding:1px 5px;border:1px solid var(--border);border-radius:4px;font:inherit;font-size:11px}.activity.two-zone .hf-search{flex:1 1 140px;min-width:120px}.activity.two-zone .hf-seg button{padding:0 8px}.activity.two-zone .hf-device{max-width:150px}}@media(max-width:760px){.hf-search{flex-basis:100%}}.hentry{padding:11px 12px;border-bottom:1px solid var(--border);--hindent: 72px}.hentry:hover{background:var(--row-hover-faint)}.hline{display:flex;gap:10px;align-items:center}.hkind{flex:none;width:62px;white-space:nowrap;text-align:center;font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600;padding:2px 6px;border-radius:4px;color:var(--add);background:#4cc38a1f}.hentry.edit .hkind{color:var(--accent-bright);background:var(--glow)}.hentry.delete .hkind{color:var(--danger-bright);background:#f26d6d1f}.hpath{font-weight:500;cursor:pointer;color:var(--text);font-size:13px}.hpath:hover{color:var(--accent-bright)}.htime{margin-left:auto;color:var(--text-faint);font-size:12px;font-variant-numeric:tabular-nums}.hmore{display:flex;margin:14px auto}.hmore:disabled{opacity:.6;cursor:default}.hmeta{display:flex;align-items:center;gap:14px;margin-top:4px;padding-left:var(--hindent);font-size:12px;color:var(--text-dim)}.hdev,.hsize{color:var(--text-faint)}.hsize{font-variant-numeric:tabular-nums;white-space:nowrap;flex:none}.hnote{margin-top:4px;padding-left:var(--hindent);font-size:12px;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.hnote:hover{color:var(--text)}.hnote.open{white-space:normal;overflow-wrap:anywhere}.hnote:before{content:"›";display:inline-block;margin-right:5px;color:var(--text-ghost);transition:transform .12s}.hnote.open:before{transform:rotate(90deg)}.hnote a{color:var(--accent-bright);text-decoration:none}.hnote a:hover{text-decoration:underline}.hrun{border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin:10px 0;overflow:hidden}.hrun-head{display:flex;align-items:center;gap:9px;width:100%;padding:9px 12px;color:var(--text);font-size:12.5px}.hrun-toggle{display:flex;flex:none;padding:2px;border:none;border-radius:4px;background:none;color:var(--text-faint);cursor:pointer}.hrun-toggle:hover{color:var(--text);background:var(--hover)}.hrun-toggle .ico{width:13px;height:13px}.hrun-note{flex-shrink:0;font-weight:560;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:46%}.hrun-note a{color:var(--accent-bright);text-decoration:none}.hrun-note a:hover{text-decoration:underline}.hrun-meta{min-width:0;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hrun-time{margin-left:auto;flex:none;color:var(--text-faint);font-variant-numeric:tabular-nums}.hrun-undo{display:inline-flex;align-items:center;gap:4px;flex:none;padding:2px 8px 2px 5px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hrun-undo:hover{color:var(--del);border-color:#f26d6d61;background:var(--hover)}.hrun-undo:disabled{opacity:.5;cursor:default}.hrun-undo .ico{width:12px;height:12px}.undo-list{margin:10px 0;max-height:40vh;overflow-y:auto;border:1px solid var(--border);border-radius:6px}.undo-row{display:flex;align-items:baseline;gap:10px;padding:5px 9px;font-size:12.5px}.undo-row+.undo-row{border-top:1px solid var(--border)}.undo-row .undo-path{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.undo-row .undo-what{margin-left:auto;flex:none;color:var(--text-faint);font-size:11.5px}.undo-row .undo-after{flex:none;color:var(--del);font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600}.undo-warn{color:var(--del)}.hrun-body{border-top:1px solid var(--border)}.hrun-body .hentry:last-child{border-bottom:none}.hread{flex:none;padding:2px 6px;border-radius:4px;font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600;color:var(--text-dim);background:var(--hover)}.hrun-reads{border-top:1px solid var(--border);padding:4px 0 6px}.hrun-reads-head{padding:6px 14px 4px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--text-faint)}.hrun-read{display:flex;gap:10px;align-items:center;width:100%;padding:5px 14px;border:none;background:none;font:inherit;text-align:left;cursor:pointer}.hrun-read:hover{background:var(--row-hover-faint)}.hrun-read .hkind{color:var(--text-dim);background:var(--hover)}.hrun-foot{padding:8px 14px 10px;border-top:1px solid var(--border);font-size:11.5px;color:var(--text-faint)}.hrestore-btn,.hremove-btn{display:inline-flex;align-items:center;gap:4px;margin-left:auto;padding:2px 8px 2px 5px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hrestore-btn:hover{color:var(--accent-bright);border-color:var(--border-2);background:var(--hover)}.hremove-btn:hover{color:var(--del);border-color:#f26d6d61;background:var(--hover)}.hrestore-btn:disabled,.hremove-btn:disabled{opacity:.5;cursor:default}.hrestore-btn .ico,.hremove-btn .ico{width:12px;height:12px}.hactions{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:6px 0 0 23px}.hdiff-btn,.hver-btn{display:inline-flex;align-items:center;gap:4px;padding:2px 7px 2px 4px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer;text-decoration:none}.hdiff-btn:hover,.hver-btn:hover{color:var(--text);border-color:var(--border-2);background:var(--hover)}.hdiff-btn .ico,.hver-btn .ico{width:12px;height:12px}.hdiff-none{flex-basis:100%;font-size:12px;color:var(--text-ghost)}.dv{margin:8px 0 2px 23px;border:1px solid var(--border);border-radius:6px;overflow:hidden}.dv-msg{display:flex;flex-wrap:wrap;align-items:center;gap:12px;padding:9px 11px;font-size:12px;color:var(--text-faint)}.dv-dl{display:flex;gap:12px}.dv-msg a{color:var(--accent-bright);text-decoration:none}.dv-msg a:hover{text-decoration:underline}.dv-head{display:flex;align-items:center;gap:10px;padding:5px 11px;border-bottom:1px solid var(--border);font-size:11px;font-variant-numeric:tabular-nums}.dv-add{color:var(--add);font-weight:600}.dv-del{color:var(--del);font-weight:600}.dv-same{color:var(--text-ghost)}.dv-body{overflow-x:auto;padding:4px 0}.dv-line{display:flex;font-family:var(--mono);font-size:12px;line-height:1.55;white-space:pre}.dv-n{flex:none;width:34px;padding-right:8px;text-align:right;color:var(--text-ghost);-webkit-user-select:none;user-select:none;font-variant-numeric:tabular-nums}.dv-mark{flex:none;width:16px;text-align:center;-webkit-user-select:none;user-select:none}.dv-text{padding-right:12px}.dv-ins{background:#4cc38a1a;color:var(--add)}.dv-rm{background:#f26d6d1a;color:var(--danger-bright)}.dv-ctx{color:var(--text-dim)}#palette{position:fixed;top:12vh;left:50%;transform:translate(-50%);z-index:151;display:block;width:min(560px,92vw);background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-over);box-shadow:0 24px 70px -18px #000c;overflow:hidden;outline:none;padding:0}:root[data-theme=light] #palette{box-shadow:0 24px 70px -18px #00000040}#palette-inputwrap{display:flex;align-items:center;gap:11px;padding:14px 16px;border-bottom:1px solid var(--border)}#palette-inputwrap [data-slot=command-input-wrapper]{flex:1;display:flex;border-bottom:0;padding:0;height:auto}#palette-inputwrap [data-slot=command-input-wrapper]>svg:not(.ico){display:none}#palette input,#palette input:focus{flex:1;width:100%;border:none;background:transparent;box-shadow:none;color:var(--text);font:inherit;font-size:15px;letter-spacing:-.01em;outline:none;padding:0}#palette input::placeholder{color:var(--text-ghost)}#palette-inputwrap .ico{width:17px;height:17px;color:var(--text-faint)}#palette [cmdk-list]{list-style:none;margin:0;padding:8px;max-height:46vh;overflow-y:auto}#palette [cmdk-item]{display:flex;align-items:center;gap:11px;height:38px;padding:0 10px;border-radius:9px;cursor:pointer;color:var(--text-dim);font-size:13.5px}#palette [cmdk-item][data-selected=true]{background:var(--glow)}#palette [cmdk-item][data-selected=true] .picon{color:var(--accent-ink)}#palette [cmdk-item][data-selected=true] .plabel,#palette [cmdk-item][data-selected=true] .plabel b{color:var(--accent-bright)}#palette [cmdk-item] .picon{width:18px;flex:none;display:flex;justify-content:center;color:var(--text-faint)}#palette [cmdk-item] .picon .ico{width:15px;height:15px}#palette [cmdk-item] .ptext{flex:1;min-width:0;display:flex;align-items:baseline;gap:8px;overflow:hidden}#palette [cmdk-item] .plabel{flex:0 1 auto;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--text)}#palette [cmdk-item] .ploc{flex:1 1 0%;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px;color:var(--text-faint)}#palette [cmdk-item] .ploc b{color:var(--text-dim);font-weight:600}#palette [cmdk-item] .plabel b{color:var(--accent-bright);font-weight:600}#palette [cmdk-group-heading]{padding:10px 10px 5px;font-size:11.5px;font-weight:500;color:var(--text-faint)}#palette [cmdk-group]:first-child [cmdk-group-heading]{padding-top:4px}#palette [cmdk-item] .pkind{flex:none;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--text-ghost)}#palette [cmdk-list] .pempty{color:var(--text-faint);cursor:default;justify-content:center;height:auto;padding:14px}#palette-hint{padding:9px 16px;border-top:1px solid var(--border);font-size:11px;color:var(--text-ghost)}[data-slot=dialog-overlay]{position:fixed;inset:0;background:#06070999;-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px);z-index:150}:root[data-theme=light] [data-slot=dialog-overlay]{background:#0f111559}.modal{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:151;display:block;background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-over);padding:22px 24px;width:min(460px,calc(100vw - 40px));box-shadow:0 24px 70px -18px #000c;outline:none}:root[data-theme=light] .modal{box-shadow:0 24px 70px -18px #00000040}.modal h3{margin:0 0 10px;font-size:16px;font-weight:620;letter-spacing:-.01em}.modal p{margin:0 0 16px;font-size:13.5px;color:var(--text-dim);line-height:1.55}.modal p b{color:var(--text)}.modal-url{font:12px var(--mono);background:var(--surface);border:1px solid var(--border);border-radius:var(--r-ctl);padding:9px 11px;color:var(--text-dim);word-break:break-all;margin-bottom:16px}.modal-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.modal-expiry{display:flex;align-items:center;gap:8px;margin-bottom:16px;font-size:12.5px;color:var(--text-dim)}.modal-expiry select{height:28px;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:0 8px;font:inherit;font-size:12.5px;cursor:pointer}.modal-expiry select:disabled{opacity:.6;cursor:default}.modal-expiry-note{margin-left:auto;color:var(--text-dim)}.modal-label{display:block;font-size:12.5px;color:var(--text-dim);margin:0 0 6px}.modal-msg{margin:0 0 16px;font-size:13.5px;color:var(--text-dim);line-height:1.55}.modal-input{width:100%;height:36px;padding:0 12px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:14px;margin-bottom:16px;outline:none}.modal-input:focus{border-color:var(--accent);background:var(--hover)}.start-points{border:0;margin:0 0 18px;padding:0}.start-points legend{padding:0}.start-point{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface);cursor:pointer;margin-bottom:6px}.start-point:hover{background:var(--hover)}.start-point.on{border-color:var(--accent);background:var(--hover)}.start-point input{accent-color:var(--accent);margin:2px 0 0;flex:none}.sp-text{display:flex;flex-direction:column;gap:2px;min-width:0}.sp-title{font-size:13.5px;color:var(--text);display:flex;align-items:center;gap:8px}.sp-rec{font-size:10.5px;letter-spacing:.02em;text-transform:uppercase;color:var(--accent-ink);border:1px solid var(--accent);border-radius:999px;padding:0 6px;line-height:15px}.sp-blurb{font-size:12px;color:var(--text-dim);overflow-wrap:anywhere}.start-point.sp-rule{margin-top:16px}.modal{max-height:calc(100vh - 32px);overflow-y:auto}.gd-note{margin:-4px 0 16px;font-size:13px;color:var(--text-dim);border-left:2px solid var(--accent);padding-left:11px;line-height:1.55}[data-sonner-toast]{background:var(--bg-raise)!important;color:var(--text)!important;border:1px solid var(--border-2)!important;border-radius:10px!important;font-size:13.5px!important;box-shadow:0 18px 44px -12px #000000b3!important}[data-sonner-toast][data-type=error]{border-color:#f26d6d80!important;color:#ffb0aa!important}:root[data-theme=light] [data-sonner-toast]{box-shadow:0 18px 44px -12px #0000002e!important}:root[data-theme=light] [data-sonner-toast][data-type=error]{color:var(--danger-bright)!important}#sb-backdrop{display:none}@media(max-width:900px){#sidebar{width:256px;max-width:calc(100vw - 48px)}#sidebar{position:fixed;z-index:60;top:0;left:0;height:100%;transform:translate(-100%);transition:transform .2s ease;box-shadow:0 0 40px #0009}body.sb-open #sidebar{transform:translate(0)}body.sb-open #sb-backdrop{display:block;position:fixed;inset:0;background:#0000008c;z-index:50}:root[data-theme=light] #sidebar{box-shadow:0 0 40px #0000002e}:root[data-theme=light] body.sb-open #sb-backdrop{background:#0f111559}.icon-btn{display:inline-flex;width:44px;height:44px}#sb-search .sb-kbd{display:none}#content{--content-pad-b: 70px;padding:24px 18px var(--content-pad-b)}#topbar{padding:0 8px;gap:4px}.btn .lbl{display:none}#topbar .btn{min-width:44px;min-height:44px;padding:0;justify-content:center;gap:0}#topbar .btn .ico{width:18px;height:18px}#more-btn:not([hidden]){display:inline-flex}#history-btn,#upload-btn,#download{display:none!important}#topbar{flex-wrap:wrap;height:auto;min-height:52px}#meta{order:1;flex:1 1 100%;text-align:left;white-space:normal;overflow:visible;padding:0 0 8px}#meta:empty{display:none}#crumb{flex:1}#vault{padding:0 8px 0 12px}#signout,#tree .row,#projects .row,#pinned .row,.sb-sync,#sb-search,.sb-menu [role=menuitem],.sb-theme{height:44px}#account-btn{min-height:44px}#project-select{height:44px}.markdown table,pre.plain{display:block;overflow-x:auto;max-width:100%}.admin-item{flex-wrap:wrap;row-gap:8px;padding:12px 14px}.admin-item select,.hf-search input,.hf-user,.hf-date,.hf-clear{height:44px}.hf-dates{flex:1 1 100%}.hf-date{flex:1;width:auto;min-width:0}.hrun-head{flex-wrap:wrap;row-gap:4px}.hrun-note{flex-shrink:1;max-width:none;white-space:normal;overflow:visible}.hrun-meta{order:1;flex:1 1 100%;white-space:normal;overflow:visible}.hrun-sub{flex-wrap:wrap}.hrun-title .hrun-note{max-width:none}.hrun-sub .hrun-meta:before{content:none}.hrun-what{white-space:normal}.hf-device,.hf-range,.hf-seg button{height:44px}.hrun-undo{order:2;margin-left:auto;min-height:32px}.ai-btn,.ai-del{height:auto;min-height:44px;padding:0 12px}.admin-table thead{display:none}.admin-table,.admin-table tbody,.admin-table td{display:block;width:auto}.admin-table tr.admin-item{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.admin-table tr.admin-item td{padding:0;border-bottom:none}.admin-table tr.admin-item td:first-child{flex:1 1 100%;width:auto}.admin-table tr.admin-item td:last-child{width:auto;text-align:left}[data-slot=dropdown-menu-item]{min-height:44px}#projects{flex:0 1 auto;max-height:none}.admin-row{flex-wrap:wrap}.admin-row input{flex:1 1 100%;min-height:44px}.admin-row button{flex:0 0 auto;align-self:flex-start;min-height:44px}.admin-item .ai-main{flex:1 1 100%;white-space:normal;overflow-wrap:anywhere}.admin-table td{white-space:normal}.admin-table td .ai-main,.admin-table td a.ai-main,.admin-table td .ai-copy,.admin-table td .ai-tag{white-space:normal;overflow-wrap:anywhere}.admin-item .ai-tag{flex:1 1 100%;max-width:100%;white-space:normal;overflow-wrap:anywhere}.ai-copy{min-height:44px;display:block;padding:12px 0;white-space:normal;overflow-wrap:anywhere;text-overflow:clip}a.ai-main{min-height:44px;display:flex;align-items:center}.gd-code{min-height:62px;padding-top:12px;padding-bottom:12px}.gd-copy{min-height:44px;padding:0 14px}.gd-tab{min-height:44px}.in-lens-btn{min-height:44px;padding:0 14px}.modal-input{height:44px}.modal-actions button{height:auto;min-height:44px}.modal-expiry select{height:44px}.pbtn,#palette [cmdk-item]{height:auto;min-height:44px}.more-item{min-height:44px}}.modal-actions .ai-del{margin-right:auto}@media(max-width:430px){.dl-row{flex-wrap:wrap;row-gap:2px}.dl-meta{flex:1 1 100%;padding-left:27px}.ai-tag{font-size:11px}.htime{white-space:nowrap;font-size:12px}.hline{flex-wrap:wrap}.hentry{--hindent: 0px}.modal-actions .ai-del{flex:0 0 100%;justify-content:center;text-align:center}}.markdown h1,.markdown h2,.markdown h3,.markdown h4{color:var(--text-bright);line-height:1.25;letter-spacing:-.018em;margin:1.5em 0 .5em;text-wrap:balance}.markdown h1:first-child{margin-top:0}.markdown h1{font-size:1.85em;font-weight:660;letter-spacing:-.024em}.markdown h2{font-size:1.32em;font-weight:620;margin-top:1.7em}.markdown h3{font-size:1.08em;font-weight:620}.markdown p,.markdown li{color:var(--text-body);font-size:14.5px;line-height:1.72}.markdown p{margin:0 0 1em}.markdown strong{color:var(--text);font-weight:620}.markdown a{color:var(--accent-bright);text-decoration:none;border-bottom:1px solid rgba(245,166,35,.28)}.markdown a:hover{border-bottom-color:var(--accent)}.markdown a.wiki-missing{color:var(--text-faint);border-bottom:none;text-decoration:underline dotted;cursor:help}.markdown ul,.markdown ol{margin:0 0 1em;padding-left:1.4em}.markdown li{margin-bottom:.4em}.markdown li::marker{color:var(--text-ghost)}.markdown code{background:var(--hover);border:1px solid var(--border);padding:.1em .4em;border-radius:5px;font:12.5px/1.5 var(--mono);color:var(--code-ink)}.markdown pre{background:var(--code-bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;overflow-x:auto;margin:1.3em 0}.markdown pre code{background:none;border:none;padding:0;color:var(--text-body)}.markdown blockquote{margin:1.3em 0;padding:.3em 1em;border-left:2px solid var(--accent);background:linear-gradient(90deg,var(--glow),transparent);border-radius:0 8px 8px 0;color:var(--quote-ink)}.markdown blockquote p{margin:.3em 0;color:var(--quote-ink)}.markdown table{border-collapse:collapse;margin:1.3em 0;font-size:13.5px}.markdown th,.markdown td{border-bottom:1px solid var(--border);padding:9px 13px;text-align:left}.markdown th{color:var(--text-faint);font-size:11px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;border-bottom-color:var(--border-2)}.markdown tr:hover td{background:var(--row-hover)}.markdown img{max-width:100%;border-radius:8px;border:1px solid var(--border)}.markdown hr{border:none;border-top:1px solid var(--border);margin:2.2em 0}.markdown .mermaid-diagram{margin:1.3em 0;overflow-x:auto}.markdown .mermaid-diagram svg{max-width:100%;height:auto}.markdown .mermaid-err{margin:-.9em 0 .4em;font-size:12px;color:var(--text-faint)}.markdown .mermaid-err-detail{margin:0 0 1.3em;font:11.5px/1.5 var(--mono);color:var(--text-faint);white-space:pre;overflow:auto;max-height:12em}.fv-head{margin:0 0 22px}.fv-chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}.fv-chip{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 8px;border-radius:6px;background:var(--hover);color:var(--text-dim);font-size:11.5px;font-weight:500;white-space:nowrap}.fv-chip .ico{width:12px;height:12px}.fv-chip.accent{background:var(--glow);color:var(--accent-ink)}.fv-meta{display:flex;flex-wrap:wrap;align-items:center;gap:6px 16px;font-size:12.5px;color:var(--text-faint)}.fv-meta>span{display:inline-flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere}.fv-meta .ico{width:13px;height:13px;flex:none}.fv-who{color:var(--text-dim)}.fv-avatar{display:inline-flex;align-items:center;justify-content:center;flex:none;width:20px;height:20px;border-radius:50%;background:var(--viz-human);color:var(--bg);font-size:10.5px;font-weight:650}.fv-rail{font-size:12.5px}.fv-sec .fv-sec-h{display:flex;align-items:baseline;margin:0 0 10px;color:var(--text-faint);font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.07em}.fv-rail .fv-sec-link{border-bottom:none;margin-left:auto;text-transform:none;letter-spacing:0;font-size:12px;font-weight:500;color:var(--accent-ink);text-decoration:none}.fv-rail .fv-sec-link:hover{color:var(--accent-bright)}.fv-rail-in{display:flex;flex-direction:column;gap:28px}.fv-rail .fv-toc ul{list-style:none;margin:0;padding:0;border-left:1px solid var(--border)}.fv-rail .fv-toc li{margin:0;font-size:12.5px;color:inherit}.fv-rail .fv-toc li a{border-bottom:none;display:block;margin-left:-1px;padding:4px 0 4px 14px;border-left:2px solid transparent;color:var(--text-dim);text-decoration:none;line-height:1.35;overflow-wrap:anywhere}.fv-rail .fv-toc li.sub a{padding-left:26px;font-size:12px;color:var(--text-faint)}.fv-rail .fv-toc li a:hover{color:var(--text)}.fv-rail .fv-toc li.on a{border-left-color:var(--accent);color:var(--accent-ink)}.fv-big{font-size:28px;font-weight:650;color:var(--text-bright);letter-spacing:-.02em;line-height:1;margin-bottom:12px;font-variant-numeric:tabular-nums}.fv-split{display:flex;gap:2px;height:6px;border-radius:3px;overflow:hidden}.fv-split-agent{background:var(--viz-agent)}.fv-split-human{background:var(--viz-human)}.fv-split-share{background:var(--viz-share)}.fv-legend{display:flex;flex-wrap:wrap;justify-content:space-between;gap:4px 12px;margin-top:8px;color:var(--text-dim)}.fv-sw{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.fv-rail .fv-readnote{margin:8px 0 0;color:var(--text-faint);font-size:12px}.fv-rail .fv-props dl{margin:0}.fv-rail .fv-props dl>div{display:flex;gap:10px;padding:4px 0}.fv-rail .fv-props dt{flex:0 0 96px;min-width:0;color:var(--text-faint);font:11.5px/1.6 var(--mono);overflow-wrap:anywhere}.fv-rail .fv-props dd{margin:0;min-width:0;color:var(--text-body);overflow-wrap:anywhere}.fv-rail .fv-props code{white-space:pre-wrap;font:11px/1.5 var(--mono);color:var(--code-ink)}.fv-rail.narrow{margin:0 0 22px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card)}.fv-rail.narrow>summary{list-style:none;cursor:pointer;padding:8px 12px;color:var(--text-faint);font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:6px;-webkit-user-select:none;user-select:none}.fv-rail.narrow>summary::-webkit-details-marker{display:none}.fv-rail.narrow>summary:before{content:"";border:4px solid transparent;border-left-color:currentColor;transition:transform .12s ease}.fv-rail.narrow[open]>summary:before{transform:rotate(90deg) translate(-1px)}.fv-rail.narrow>summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--r-card)}.fv-rail.narrow .fv-rail-in{padding:6px 12px 14px;gap:20px;border-top:1px solid var(--border)}@media(min-width:1400px){.page.read:has(>aside.fv-rail){max-width:min(var(--page-read),calc(100% - 300px));margin-left:max(0px,calc((100% - var(--page-read) - 300px) / 2));margin-right:auto}aside.fv-rail{position:absolute;top:0;bottom:0;left:calc(100% + 40px);width:260px}.page.read:has(>aside.fv-rail) .fv-prose table,.page.read:has(>aside.fv-rail) .fv-prose pre{display:block;overflow-x:auto;max-width:100%}aside.fv-rail .fv-rail-in{position:sticky;top:0;max-height:calc(100vh - 140px);overflow-y:auto;padding-left:20px;border-left:1px solid var(--border)}}.markdown .admin input:focus-visible{outline:2px solid var(--accent);outline-offset:1px}.admin input[aria-invalid=true]:focus-visible{outline-color:var(--del)}[role=dialog] input[aria-invalid=true]{border-color:var(--del)}[role=dialog] input[aria-invalid=true]:focus-visible{outline-color:var(--del)}button:disabled,.btn:disabled{cursor:default}input[type=checkbox]{accent-color:var(--accent)}.htmlview,.pdfview{display:block;width:100%;height:calc(100vh - 150px);border:1px solid var(--border);border-radius:var(--r-card);background:#fff}.notfound{margin-top:var(--hero-top);text-align:center;color:var(--text-dim)}.notfound h1{color:var(--text);font-size:1.4em;margin-bottom:.5em}.notfound code{background:var(--hover);border:1px solid var(--border);padding:.15em .5em;border-radius:6px}.notfound .nf-sub{max-width:440px;margin:12px auto 20px;font-size:13px;color:var(--text-faint);line-height:1.6}.vbanner{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:0 0 22px;padding:11px 14px;border:1px solid var(--accent-dim);border-radius:var(--r-card);background:var(--glow)}.vbanner .vb-icon{flex:none;display:flex;color:var(--accent-bright)}.vbanner .vb-text{flex:1 1 220px;min-width:0;display:flex;flex-direction:column;gap:1px;font-size:12.5px;line-height:1.45}.vbanner .vb-text b{color:var(--accent-bright);font-weight:600}.vbanner .vb-text span{color:var(--text-dim)}.vbanner .vb-actions{flex:none;display:flex;gap:8px}.vbanner .vb-actions .ai-btn{display:inline-flex;align-items:center;text-decoration:none}.sbadge{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:0 0 22px;padding:11px 14px;border:1px solid rgba(242,109,109,.32);border-radius:var(--r-card);background:#f26d6d14}.sbadge .sb-icon{flex:none;display:flex;color:var(--danger-ink)}.sbadge .sb-text{flex:1 1 220px;min-width:0;display:flex;flex-direction:column;gap:1px;font-size:12.5px;line-height:1.45}.sbadge .sb-text b{color:var(--danger-ink);font-weight:600}.sbadge .sb-text span{color:var(--text-dim)}pre.plain{background:var(--code-bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;overflow-x:auto;font:12.5px/1.6 var(--mono);color:var(--text-body);white-space:pre-wrap;overflow-wrap:anywhere}.csvbox{overflow-x:auto;width:fit-content;max-width:100%;border:1px solid var(--border);border-radius:var(--r-card);background:var(--code-bg)}.csvbox .csvview{display:table;max-width:none;overflow:visible;margin:0;border-collapse:collapse;font:12.5px/1.5 var(--mono);font-variant-numeric:tabular-nums}.csvbox .csvview th,.csvbox .csvview td{border-bottom:1px solid var(--border);padding:8px 14px;text-align:left;white-space:pre;vertical-align:top;color:var(--text-body);font-size:12.5px}.csvbox .csvview th{background:var(--surface);color:var(--text-faint);font-size:11px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;border-bottom-color:var(--border-2)}.csvbox .csvview tr:last-child td{border-bottom:none}.csvbox .csvview tbody tr:hover td{background:var(--row-hover)}.csvnote{color:var(--text-faint);font-size:12px;margin:10px 2px 0}.filecard{margin-top:var(--hero-top);text-align:center;color:var(--text-dim)}.filecard .name{font-size:1.2em;color:var(--text);margin-bottom:.3em}.filecard .btn{margin-top:14px}body.full-view #sidebar,body.full-view #topbar,body.full-view #sb-backdrop{display:none}body.full-view #content{padding-top:58px}body.full-view .page.bleed{max-width:none}body.full-view #content:has(.page.bleed){padding:58px 14px 14px}body.full-view .htmlview,body.full-view .pdfview{height:calc(100vh - 72px)}#exit-full{position:fixed;z-index:80;top:12px;right:16px;display:inline-flex;align-items:center;gap:7px;height:32px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text);font-size:12.5px;font-family:inherit;cursor:pointer;box-shadow:0 8px 24px -8px #000000b3}:root[data-theme=light] #exit-full{box-shadow:0 8px 24px -8px #0000002e}#exit-full:hover{background:var(--hover);border-color:var(--accent)}#exit-full kbd{font:inherit;font-size:10.5px;color:var(--text-faint);border:1px solid var(--border-2);border-radius:4px;padding:1px 4px}@media(max-width:900px){#exit-full{top:8px;right:8px;height:40px}#exit-full .lbl{display:none}}.modal-wide{width:min(600px,calc(100vw - 40px))}.sd-head{font-size:12.5px;font-weight:600;color:var(--text-dim);margin:18px 0 8px;letter-spacing:.01em}.sd-head:first-of-type{margin-top:4px}.modal .admin-list{max-height:220px;overflow-y:auto}.sd-avatar{width:22px;height:22px;flex:none;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10.5px;font-weight:700}.sd-add{gap:8px}.sd-add-input{flex:1;min-width:0;height:28px;padding:0 9px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font:inherit;font-size:12.5px}.sd-warn{margin:14px 0 6px;font-size:13.5px;color:var(--text)}.modal .ps-row{margin-bottom:10px}.modal .ps-note{margin-bottom:12px}@media(max-width:640px){.sd-add{flex-wrap:wrap}.sd-add-input{flex:0 0 100%;height:44px}}.setup{max-width:760px;margin:var(--hero-top) auto 0}.setup-welcome{text-align:left}.setup-foot{color:var(--text-ghost);font-size:12px;margin:10px 0 0}.setup-connect header h2{font-size:20px;font-weight:640;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright);display:flex;align-items:center;gap:8px}.setup-badge{background:var(--glow);border:1px solid rgba(245,166,35,.4);color:var(--accent-bright);font-size:10px;font-weight:600;border-radius:999px;padding:2px 8px;letter-spacing:.04em}.setup-connect header p{color:var(--text-dim);font-size:13px;margin:0 0 18px}.setup-why{color:var(--text-dim);font-size:12.5px;line-height:1.6;margin:0 0 18px;padding-left:18px}.setup-body{display:flex;gap:22px;align-items:flex-start}.setup-form{flex:1;display:flex;flex-direction:column;gap:14px;min-width:0}.setup-field{display:flex;flex-direction:column;gap:6px}.setup-field>span{color:var(--text-dim);font-size:12px}.setup-field input,.setup-root input{background:var(--bg);border:1px solid var(--border-2);border-radius:var(--r-ctl);padding:9px 12px;color:var(--text);font-size:13.5px;font-family:var(--mono);width:100%;box-sizing:border-box}.setup-field input:focus,.setup-root input:focus{outline:none;border-color:var(--accent)}.setup-root{display:flex;gap:8px}.setup-root button{background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-ctl);color:var(--text);font-size:13px;padding:0 14px;cursor:pointer;white-space:nowrap}.setup-root button:hover{background:var(--hover)}.setup-toggle{display:flex;align-items:center;gap:8px;color:var(--text);font-size:13px}.setup-ok{color:var(--add);font-size:12.5px;margin:0}.setup-err{color:var(--del);font-size:12.5px;margin:0}.setup-warn{color:var(--accent-bright);font-size:12.5px;line-height:1.5;display:flex;flex-direction:column;gap:6px}.setup-warn p{margin:0}.setup-helper{color:var(--text-dim);display:flex;flex-wrap:wrap;align-items:center;gap:6px}.setup-helper code{font-family:var(--mono);font-size:11.5px;color:var(--text);background:var(--surface);border:1px solid var(--border);border-radius:5px;padding:2px 6px;word-break:break-all}.setup-helper button{font:inherit;font-size:11.5px;color:var(--accent-ink);background:none;border:1px solid var(--border-2);border-radius:5px;padding:2px 8px;cursor:pointer}.setup-helper button:hover{background:var(--hover)}.setup-tree{width:290px;flex:none;background:var(--bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;font-family:var(--mono);font-size:12px}.setup-tree-head{font-family:inherit;color:var(--text-ghost);font-size:10.5px;letter-spacing:.06em;margin-bottom:8px}.setup-tree-root{color:var(--text)}.setup-dim{color:var(--text-dim)}.setup-tree-shared{color:var(--accent-bright);background:var(--glow);border:1px solid rgba(245,166,35,.4);border-radius:5px;padding:2px 6px;margin:3px 0;display:inline-block}.setup-shared-tag{color:var(--accent-ink);font-size:10px}.setup-tree-foot{color:var(--text-ghost);font-size:10.5px;line-height:1.5;margin:10px 0 0;font-family:-apple-system,BlinkMacSystemFont,SF Pro Text,sans-serif}.setup-syncing h2,.setup-done h2{font-size:20px;font-weight:640;margin:0 0 10px;color:var(--text-bright)}.setup-bar{height:8px;border-radius:4px;background:var(--hover);overflow:hidden;margin:14px 0}.setup-bar>div{height:100%;background:linear-gradient(90deg,var(--accent-dim),var(--accent));border-radius:4px;transition:width .3s ease}.setup-log{list-style:none;padding:0;margin:0 0 14px;font-family:var(--mono);font-size:12px;color:var(--text-ghost);display:flex;flex-direction:column;gap:5px}.setup-log li.ok{color:var(--add)}.setup-log li.ok:before{content:"✓ "}.setup-cards{display:flex;gap:12px;margin-top:18px;align-items:stretch}.setup-card{flex:1;background:var(--bg-raise);padding:16px;display:flex;flex-direction:column;gap:8px;min-width:0}.setup-card-lead{flex:1.4;border-color:#f5a62366;box-shadow:0 0 0 3px var(--glow)}.setup-card h3{font-size:14px;font-weight:600;margin:0;color:var(--text)}.setup-card p{color:var(--text-dim);font-size:12px;line-height:1.5;margin:0;flex:1}@media(max-width:720px){.setup-body,.setup-cards{flex-direction:column}.setup-tree{width:100%}}.cm-host{height:100%}.cm-preview{margin:0;padding:12px 2px 0 6px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--text);font:13px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace}.cm-preview.cm-mode-write{font-family:var(--ui);font-size:15px;line-height:1.75}.cm-host .cm-editor{height:100%;background:transparent;color:var(--text)}.cm-host .cm-editor.cm-focused{outline:none}.cm-host .cm-scroller{font:13px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace;padding:8px 0 40vh}.cm-host .cm-gutters{background:transparent;border-right:1px solid var(--line);color:var(--text-faint)}.cm-host .cm-activeLine{background:color-mix(in srgb,var(--accent) 6%,transparent)}.cm-host .cm-activeLineGutter{background:transparent;color:var(--text)}.cm-host .cm-content{caret-color:var(--text)}.cm-host .cm-cursor{border-left-color:var(--text)}.cm-host .cm-selectionBackground,.cm-host .cm-content ::selection{background:color-mix(in srgb,var(--accent) 26%,transparent)}#editor-state{color:var(--text-faint)}#editor-state[data-state=saving]{color:var(--accent-ink)}#editor-state[data-state=error]{color:var(--del)}#peer-wrote{margin:0 0 10px;padding:8px 12px;border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:6px;color:var(--text-dim);font-size:13px}.cm-host .cm-ySelection{opacity:.35}.cm-host .cm-ySelectionCaret{position:relative;border-left:1px solid currentColor;border-right:1px solid currentColor;margin-left:-1px;margin-right:-1px;box-sizing:border-box}.cm-host .cm-ySelectionInfo{position:absolute;top:-1.05em;left:-1px;font-size:11px;line-height:1.4;padding:0 4px;border-radius:3px 3px 3px 0;color:#fff;white-space:nowrap;opacity:0;transition:opacity .12s;pointer-events:none;-webkit-user-select:none;user-select:none}.cm-host .cm-ySelectionCaret:hover .cm-ySelectionInfo{opacity:1}::highlight(bd-comment){background-color:#f5a6233d}::highlight(bd-comment-active){background-color:#f5a6238c}.cm-pin{position:absolute;z-index:6;transform:translateY(-50%) translateY(calc(var(--k, 0) * 22px));min-width:20px;height:20px;padding:0 5px;border:none;border-radius:10px 10px 10px 2px;background:var(--accent);color:#241704;font:600 11px/20px var(--ui);cursor:pointer;box-shadow:0 2px 6px #00000059}.cm-pin.active{outline:2px solid var(--text);outline-offset:1px}.cm-float{position:fixed;z-index:90;display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border-radius:15px;border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text);font:500 12.5px var(--ui);cursor:pointer;box-shadow:0 8px 24px -8px #0009}.cm-float:hover{border-color:var(--accent)}.cm-float .ico{width:14px;height:14px;color:var(--accent)}.cm-compose{position:fixed;z-index:90;width:320px;padding:10px;border-radius:var(--r-card);background:var(--bg-raise);border:1px solid var(--border-2);box-shadow:0 18px 44px -14px #000000bf}:root[data-theme=light] .cm-compose,:root[data-theme=light] .cm-float{box-shadow:0 18px 44px -14px #0003}.cm-compose textarea,.cm-panel textarea{display:block;width:100%;min-height:64px;resize:vertical;box-sizing:border-box;padding:7px 9px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:var(--surface);color:var(--text);font:13px/1.45 var(--ui)}.cm-compose textarea:focus-visible,.cm-panel textarea:focus-visible{outline:2px solid var(--accent);outline-offset:-1px}.cm-row{display:flex;align-items:center;justify-content:flex-end;gap:6px;margin-top:8px}.cm-spacer{flex:1}.cm-quote{margin:0 0 8px;padding:2px 0 2px 8px;border-left:2px solid var(--accent);color:var(--text-dim);font-size:12.5px;line-height:1.4;overflow-wrap:anywhere}.cm-quote.cm-el{font-family:var(--mono);font-size:11.5px}.cm-anchor{flex:1;min-width:0}.cm-anchor .cm-quote{max-height:7.5em;overflow-y:auto;white-space:pre-wrap}.cm-anchor .cm-quote+.cm-quote{margin-top:-4px}.cm-q{color:var(--text)}.cm-ctx{color:var(--text-faint)}#comments-btn .cm-count{margin-left:2px;font-size:12px;font-weight:600;color:var(--accent)}#comments-btn[aria-pressed=true]{background:var(--hover);color:var(--text)}.cm-panel{position:fixed;z-index:70;top:53px;right:0;bottom:0;width:360px;max-width:100vw;display:flex;flex-direction:column;background:var(--bg-side);border-left:1px solid var(--border)}body.full-view .cm-panel{top:0}@media(min-width:1200px){body:has(.cm-panel) #content{padding-right:400px}}.cm-head{display:flex;align-items:center;gap:10px;height:46px;padding:0 8px 0 14px;border-bottom:1px solid var(--border);flex:none}.cm-head>b{font-size:13.5px}.cm-tabs{display:flex;gap:2px;flex:1}.cm-tabs button{height:26px;padding:0 9px;border:none;border-radius:6px;background:transparent;color:var(--text-faint);font:500 12px var(--ui);cursor:pointer}.cm-tabs button[aria-selected=true]{background:var(--hover);color:var(--text)}.cm-tabs button span{margin-left:3px;color:var(--accent)}.cm-x{width:30px;height:30px;border:none;border-radius:7px;background:transparent;color:var(--text-dim);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.cm-x:hover{background:var(--hover);color:var(--text)}.cm-x .ico{width:16px;height:16px}.cm-pickbar{padding:8px 12px;border-bottom:1px solid var(--border);flex:none}.cm-pickbar .btn{width:100%;justify-content:center}.cm-pickbar .btn[aria-pressed=true]{border-color:var(--accent);color:var(--text)}.cm-list{flex:1;overflow-y:auto;padding:10px 12px;display:flex;flex-direction:column;gap:10px}.cm-empty{color:var(--text-faint);font-size:13px;line-height:1.5;margin:18px 4px}.cm-card{padding:10px 11px;border-radius:var(--r-card);border:1px solid var(--border);background:var(--surface);font-size:13px}.cm-card.active{border-color:var(--accent)}.cm-card.resolved{opacity:.85}.cm-card-top{display:flex;gap:8px;align-items:flex-start;cursor:pointer}.cm-card-top .cm-quote{flex:1}.cm-n{flex:none;min-width:18px;height:18px;padding:0 4px;border-radius:9px 9px 9px 2px;background:var(--accent);color:#241704;font:600 10.5px/18px var(--ui);text-align:center}.cm-card.resolved .cm-n{background:var(--text-faint)}.cm-flag{margin:0 0 8px;font-size:11.5px;color:var(--accent)}.cm-msg{margin:6px 0 8px}.cm-who{font-size:12px;color:var(--text-faint)}.cm-who b{color:var(--text);font-weight:600;margin-right:4px}.cm-body{margin-top:2px;color:var(--text-body);line-height:1.45;white-space:pre-wrap;overflow-wrap:anywhere}.cm-resolved{display:flex;align-items:center;gap:5px;margin:4px 0 8px;font-size:12px;color:var(--add)}.cm-resolved .ico{width:13px;height:13px}.cm-panel textarea.cm-reply{min-height:0;margin-top:6px}.cm-del{width:28px;height:27px;border:none;border-radius:6px;background:transparent;color:var(--text-faint);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.cm-del:hover{color:var(--del);background:var(--hover)}.cm-del .ico{width:14px;height:14px}.cm-foot{flex:none;padding:10px 12px 12px;border-top:1px solid var(--border)}.cm-hint{flex:1;font-size:11.5px;color:var(--text-faint)}.cm-hint code{font-family:var(--mono);font-size:11px}@media print{.fv-rail{display:none!important}:root,:root[data-theme=light]{color-scheme:light!important;--bg: #fff;--bg-side: #fff;--bg-raise: #fff;--surface: #f6f6f7;--hover: transparent;--border: #d9dade;--border-2: #c3c5ca;--code-bg: #f6f6f7;--text: #14161a;--text-bright: #000;--text-body: #1c1f24;--code-ink: #4a3a12;--quote-ink: #3a3226;--text-dim: #444851;--text-faint: #5c6069;--text-ghost: #767b84;--accent: #8a5a00;--accent-bright: #8a5a00;--glow: transparent}#sidebar,#sb-backdrop,#topbar,#palette,.modal,#more-menu,#presence,#exit-full,.rw-handle,[data-slot=dialog-overlay],[data-sonner-toaster],.cm-panel,.cm-pin,.cm-float,.cm-compose{display:none!important}body.full-view #content,body.full-view #content:has(.page.bleed){padding:0}html,body{height:auto}body{display:block;background:#fff}#main{display:block}#content{overflow:visible;padding:0}.page,.page.read,.page.wide{max-width:none}a[href]{text-decoration:underline}h1,h2,h3,h4{break-after:avoid}pre,tr,img,blockquote{break-inside:avoid}}#sb-search{display:flex;align-items:center;gap:8px;height:28px;margin:4px 0 0;padding:0 6px 0 7px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--text-dim);cursor:text}#sb-search:hover{background:var(--hover)}#sb-search:focus-within{border-color:var(--border-2);background:var(--surface)}#sb-search.filtering{border-color:var(--accent)}#sb-search .ico{width:16px;height:16px;flex:none}#sb-search input{flex:1;min-width:0;padding:0;border:0;outline:0;background:transparent;color:var(--text);font:inherit;font-size:13px;cursor:inherit}#sb-search input::placeholder{color:var(--text-dim)}.sb-kbd{flex:none;font:11px var(--ui);color:var(--text-faint);cursor:pointer;background:none;border:0;padding:0 2px}.sb-kbd:hover{color:var(--text)}#sidebar>#sb-search{margin:4px 8px 0}.sb-section{display:flex;align-items:center;flex:none;gap:2px;height:28px;margin-top:16px;padding:0 8px;font-size:12px;font-weight:500;color:var(--text-faint)}.sb-section>span{flex:1}#pinned{flex:none;max-height:30%;overflow-y:auto;padding:0 8px}#pinned .row.gone{opacity:.55;cursor:default}#pinned .row>.ico{width:16px;height:16px;flex:none;color:var(--text-faint)}.pin-badge{flex:none;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums}.pin-badge.danger{color:var(--danger-ink)}#pinned .pin-x{display:none}#pinned .row:hover .pin-x,#pinned .row:focus-within .pin-x{display:inline-flex}.files-head{margin-left:8px;margin-right:8px;padding-right:2px}.sb-foot{flex:none;padding:8px}.sb-sync{width:100%;border:0;background:transparent;font:inherit;font-size:12px;color:var(--text-faint);text-align:left}.sb-sync .ico{width:16px;height:16px;flex:none}.sync-dot{width:6px;height:6px;margin:0 5px;border-radius:999px;background:var(--add);flex:none}#tree .tmeta{flex:none;font-size:11px;color:var(--text-faint);padding-right:2px}#tree .tnew{color:var(--accent-ink)}#tree .tconflicts{flex:none;font-size:11px;color:var(--danger-ink);white-space:nowrap}#tree .tmore .label{font-size:12px;color:var(--text-faint);padding-left:21px}#tree .tmore:hover .label{color:var(--text)}.thover{position:absolute;right:4px;top:50%;transform:translateY(-50%);display:flex;gap:2px;opacity:0;pointer-events:none;background:var(--bg-side);border-radius:5px}#tree .row:hover .thover,#tree .row:focus-within .thover,#tree .row.menu-open .thover{opacity:1;pointer-events:auto}#tree .row.active .thover{background:transparent}.tact{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border:0;border-radius:4px;background:var(--hover);color:var(--text-dim);cursor:pointer;padding:0}.tact:hover{color:var(--text);background:var(--border-2)}.tact .ico{width:12px;height:12px}.files-head .tact{width:22px;height:22px;border-radius:5px;background:transparent;color:var(--text-faint)}.files-head .tact .ico{width:14px;height:14px}.files-head .tact:hover{background:var(--hover);color:var(--text)}.files-head .tact.on{color:var(--text);background:var(--hover)}.files-head #tree-sort-btn:not(.on){opacity:0}.files-head:hover #tree-sort-btn,.files-head:focus-within #tree-sort-btn{opacity:1}.row-menu{min-width:220px}.row-menu .ico{width:13px;height:13px}#tree-filter{flex:1;overflow-y:auto;padding:4px 8px 24px}.fgroup{padding:12px 8px 4px;font-size:12px;font-weight:500;color:var(--text-faint)}.fhit{display:flex;align-items:flex-start;gap:7px;padding:6px 8px;border-radius:7px;color:var(--text-dim);cursor:pointer}.fhit .ticon{display:flex;padding-top:1px;color:var(--text-ghost)}.fhit .ticon .ico{width:14px;height:14px}.fhit.sel{background:var(--glow);color:var(--text)}.fhit-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}.fhit-name{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fhit-name mark{background:var(--glow);color:var(--accent-bright);border-radius:3px;padding:0 1px}.fhit-path{font:11px var(--mono);color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fhit-enter{flex:none;font-size:11px;color:var(--accent-ink)}.fcontents{margin-top:8px;border:1px solid var(--border);align-items:center}.fcontents .fhit-name{flex:1}.fcontents kbd{font:10.5px var(--ui);color:var(--text-faint)}.fmore,.fempty{display:block;padding:6px 8px;font-size:12px;color:var(--text-faint);background:none;border:0;cursor:pointer;text-align:left}.fmore:hover{color:var(--text)}.fempty{cursor:default}#rail{display:none;flex:1;flex-direction:column;align-items:center;gap:2px;padding:10px 0;overflow-y:auto;overflow-x:hidden}.rail-mark{color:var(--accent-ink);display:grid;place-items:center;height:32px;margin-bottom:4px}.rail-sep{width:20px;height:1px;background:var(--border);margin:6px 0;flex:none}.rail-btn{position:relative;flex:none;width:32px;height:32px;display:grid;place-items:center;border:0;border-radius:6px;background:transparent;color:var(--text-dim);cursor:pointer}.rail-btn:hover{background:var(--hover);color:var(--text)}.rail-btn.active{background:var(--row-on);color:var(--text)}.rail-btn .ico{width:16px;height:16px}.rail-proj{margin-bottom:8px}.rail-proj:hover,.rail-proj[data-state=open]{background:var(--hover)}.rail-proj .proj-mark{width:24px;height:24px;border-radius:6px}.rail-proj .proj-mark svg{width:14px;height:14px}.rail-badge{position:absolute;top:2px;right:0;min-width:16px;height:15px;padding:0 4px;border-radius:999px;font-size:9.5px;font-weight:700;line-height:15px;text-align:center;background:var(--accent);color:var(--bg)}.rail-badge.danger{background:var(--del);color:var(--bg)}.tip-hint{color:var(--text-faint);font-weight:400}.sync-pill{display:inline-flex;align-items:center;gap:5px;margin-left:10px;height:20px;padding:0 8px;border-radius:10px;background:color-mix(in srgb,var(--add) 14%,transparent);color:var(--add);font-size:11.5px;font-weight:500;vertical-align:1px}.sync-pill:before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor}#topbar .btn.ghost{background:transparent;border-color:transparent}#topbar .btn.ghost:hover{background:var(--hover);color:var(--text)}#topbar .btn.ghost[aria-pressed=true]{background:var(--hover);color:var(--text);border-color:var(--border)}#comments-btn .cm-count{min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--glow);color:var(--accent-ink);font-size:11px;line-height:18px;text-align:center}#topbar .pbtn{height:30px;padding:0 12px;font-size:12.5px}.presence-count{margin:0 6px 0 4px;font-size:12.5px;color:var(--text-faint);white-space:nowrap}@media(max-width:900px){#topbar .pbtn{min-width:44px;min-height:44px;padding:0;justify-content:center;gap:0}#topbar .pbtn .lbl,.presence-count,.sync-pill{display:none}}.cm-msg{display:flex;gap:9px;align-items:flex-start}.cm-msg-main{flex:1;min-width:0}.cm-av{flex:none;width:24px;height:24px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:var(--hover);border:1px solid var(--border-2);color:var(--text-dim);font-size:9.5px;font-weight:650}.cm-queued{display:flex;align-items:center;gap:6px;margin:4px 0 8px;padding:6px 9px;border-radius:var(--r-ctl);background:var(--glow);color:var(--accent-ink);font-size:12px}.cm-queued .ico{width:13px;height:13px;flex:none}.cm-queued code{font:11px var(--mono)}.cm-row .btn.cm-act{height:26px;padding:0 7px;gap:5px;background:transparent;border-color:transparent;font-size:12px}.cm-row .btn.cm-act:hover{background:var(--hover)}.cm-row .btn.cm-act .ico{width:13px;height:13px}.cm-card .cm-row{justify-content:flex-start;gap:2px}.cm-pin{display:inline-flex;align-items:center;gap:3px;padding:0 6px;border-radius:10px}.cm-pin .ico{width:11px;height:11px}@media(max-width:900px){#edit-btn .ico{display:none}}@media(min-width:1400px){body:has(.cm-panel) .page.read:has(>aside.fv-rail){max-width:var(--page-read);margin-inline:auto}body:has(.cm-panel) aside.fv-rail{display:none}}@media(max-width:900px){.cm-pin{left:-19px!important;padding:0 5px}.cm-pin .ico{display:none}}@media(max-width:1200px){#topbar #comments-btn .lbl,#topbar #history-btn .lbl,.presence-count,.sync-pill{display:none}}.home{padding-bottom:40px}.home-head{margin:4px 0 26px}.home-greet{font-size:26px;font-weight:660;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright)}.home-since{margin:0;color:var(--text-dim);font-size:14px;line-height:1.5;min-height:1.5em}.home-sec{margin-bottom:28px}.home-eyebrow{margin:0 0 10px;font-size:11.5px;font-weight:640;letter-spacing:.08em;text-transform:uppercase;color:var(--text-faint)}.home-h{display:flex;align-items:center;gap:8px;margin:0 0 12px;font-size:15.5px;font-weight:620;color:var(--text-bright)}.home-h .ico{width:15px;height:15px;color:var(--accent)}.home-count{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:18px;padding:0 6px;border-radius:999px;background:var(--hover);border:1px solid var(--accent-dim);color:var(--accent-ink);font-size:11.5px;font-weight:640}.home-row{display:flex;align-items:baseline;justify-content:space-between;gap:12px}.home-more{font-size:12.5px;color:var(--accent-bright);text-decoration:none;white-space:nowrap}.home-more:hover{text-decoration:underline}.home-none{margin:0;color:var(--text-faint);font-size:13px}.home-cards{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.home-card{display:grid;gap:4px;padding:12px 14px;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);color:var(--text);text-decoration:none;min-width:0}.home-card:hover{border-color:var(--border-2);background:var(--hover)}.hc-name{display:flex;align-items:center;gap:7px;font-weight:600;color:var(--text-bright);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hc-name .ico{width:14px;height:14px;flex:none;color:var(--text-faint)}.hc-dir{font-family:var(--mono);font-size:11.5px;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hc-when{font-size:12px;color:var(--text-dim)}.home-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:36px;align-items:start}.home-list{list-style:none;margin:0;padding:0;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface)}.home-attn-row{display:flex;align-items:center;gap:12px;padding:12px 14px}.home-attn-row+.home-attn-row{border-top:1px solid var(--border)}.ha-icon{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;flex:none;border-radius:8px;background:var(--hover);color:var(--text-dim)}.ha-icon .ico{width:15px;height:15px}.home-attn-row.conflict .ha-icon{color:var(--danger-bright)}.home-attn-row.comments .ha-icon,.home-attn-row.stale .ha-icon{color:var(--accent-bright)}.ha-text{display:grid;gap:2px;min-width:0;flex:1}.ha-title{color:var(--text);font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ha-title b{font-weight:600;color:var(--text-bright)}.ha-sub{color:var(--text-faint);font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.home-activity .hf-seg{margin-bottom:8px}.home-feed{list-style:none;margin:0;padding:0}.home-fe{display:flex;gap:12px;padding:11px 0;border-bottom:1px solid var(--border)}.fe-avatar{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;flex:none;border-radius:999px;background:var(--hover)}.fe-avatar .ico{width:14px;height:14px}.fe-avatar.agent{color:var(--viz-agent)}.fe-avatar.human{color:var(--viz-human)}.fe-body{display:grid;gap:2px;min-width:0;flex:1;font-size:13.5px;color:var(--text)}.fe-body b{font-weight:600;color:var(--text-bright)}.fe-what{color:var(--text-dim)}.fe-path{font-family:var(--mono);font-size:12px;color:var(--text);text-decoration:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}a.fe-path:hover{color:var(--accent-bright)}.fe-path.del{text-decoration:line-through;color:var(--text-faint)}.fe-dev{font-size:12px;color:var(--text-faint)}.fe-when{flex:none;font-size:12px;color:var(--text-faint)}.home-devlist{list-style:none;margin:0;padding:0;display:grid;gap:10px}.home-devlist li{display:flex;align-items:center;gap:10px}.dev-dot{width:7px;height:7px;flex:none;border-radius:999px;background:var(--text-ghost)}.dev-dot.on{background:var(--add)}.dev-text{display:grid;min-width:0;flex:1}.dev-name{font-size:13.5px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dev-sub{font-size:12px;color:var(--text-faint)}.dev-agent{font-size:12px;color:var(--text-dim);white-space:nowrap}.home-connect{padding:14px 16px;border:1px solid var(--accent-dim);border-radius:var(--r-card);background:var(--surface)}.home-connect .home-h{font-size:14px;margin-bottom:6px}.home-connect .gd-code>code{white-space:pre-wrap;max-height:5.2em;overflow:hidden}.home-bars{list-style:none;margin:0 0 10px;padding:0;display:grid;gap:10px}.hb-label{display:flex;justify-content:space-between;font-size:13px;color:var(--text);text-decoration:none}.hb-label:hover{color:var(--accent-bright)}.hb-n{font-variant-numeric:tabular-nums;color:var(--text-dim)}.hb-track{display:block;height:4px;margin-top:4px;border-radius:2px;background:var(--hover)}.hb-fill{display:block;height:100%;min-width:4px;border-radius:2px}.fresh-fresh .hb-fill{background:var(--add)}.fresh-aging .hb-fill{background:var(--accent)}.fresh-stale .hb-fill{background:var(--danger-bright)}.home-legend{display:flex;gap:14px;font-size:12px;color:var(--text-dim)}.home-legend span:before{content:"";display:inline-block;width:10px;height:4px;margin-right:6px;border-radius:2px;vertical-align:2px}.home-legend .fresh-fresh:before{background:var(--add)}.home-legend .fresh-aging:before{background:var(--accent)}.home-legend .fresh-stale:before{background:var(--danger-bright)}.home-files{margin-top:8px;padding-top:22px;border-top:1px solid var(--border)}@media(max-width:1100px){.home-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.home-grid{grid-template-columns:minmax(0,1fr)}}.pavatar{display:inline-flex;align-items:center;justify-content:center;flex:none;width:20px;height:20px;border-radius:50%;background:hsl(var(--ph) 70% 88%);color:hsl(var(--ph) 60% 28%);font-size:9.5px;font-weight:650;line-height:1;letter-spacing:0}.ed-state{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 9px;border-radius:999px;background:var(--hover);color:var(--text-dim);font-size:12px;white-space:nowrap}.ed-state>i{width:6px;height:6px;border-radius:50%;background:var(--text-faint)}.ed-state[data-collab=live]{color:var(--add);background:color-mix(in srgb,var(--add) 12%,transparent)}.ed-state[data-collab=live]>i{background:var(--add)}.ed-state[data-state=saving]{color:var(--accent-ink)}.ed-state[data-state=error],.ed-state[data-collab=offline]{color:var(--accent-ink);background:var(--glow)}.ed-state[data-state=error]>i,.ed-state[data-collab=offline]>i{background:var(--accent)}.ed-editors{display:inline-flex;align-items:center;margin-left:10px}.ed-editors .pavatar{width:22px;height:22px;margin-left:-5px;box-shadow:0 0 0 2px var(--bg)}.ed-editors .pavatar:first-child{margin-left:0}.ed-more{margin-left:4px;font-size:11.5px;color:var(--text-faint)}.ed-modes{display:inline-flex;gap:2px;padding:3px;margin:0 0 16px;border-radius:var(--r-ctl);background:var(--hover)}.ed-modes button{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 11px;border:0;border-radius:5px;background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.ed-modes button .ico{width:13px;height:13px}.ed-modes button:hover{color:var(--text)}.ed-modes button.on{background:var(--bg-raise);color:var(--text-bright);box-shadow:0 0 0 1px var(--border)}.ed-offline{margin:0 0 12px;padding:10px 14px;border:1px solid color-mix(in srgb,var(--accent) 40%,transparent);border-radius:var(--r-card);background:var(--glow);color:var(--text-body);font-size:13px;line-height:1.5}.ed-offline b{color:var(--accent-ink)}.ed-statusbar{position:sticky;bottom:calc(-1 * var(--content-pad-b, 0px));z-index:2;display:flex;flex-wrap:wrap;gap:4px 18px;align-items:center;margin-top:12px;padding:7px 2px;border-top:1px solid var(--border);background:var(--bg);color:var(--text-faint);font-size:12px}.ed-statusbar .ico{width:12px;height:12px}.ed-guard{display:inline-flex;align-items:center;gap:5px;color:var(--add)}.ed-pos{margin-left:auto;font-family:var(--mono)}.cm-host.cm-mode-write .cm-scroller{font-family:var(--ui);font-size:15px;line-height:1.75}.cm-host.cm-mode-write .cm-line span{text-decoration:none}.cm-host.cm-mode-write .cm-activeLine{background:transparent}.cm-host .ms-line{padding-top:10px;font-weight:620;color:var(--text-bright)}.cm-host .ms-head{display:inline-flex;align-items:center;gap:6px;margin-right:8px;vertical-align:middle}.cm-host .ms-toggle{position:relative;width:18px;height:18px;padding:0;border:0;border-radius:4px;background:none;color:var(--text-faint);font-size:0;cursor:pointer}.cm-host .ms-toggle:before{content:"";position:absolute;left:6px;top:5px;border:4px solid transparent;border-left:5px solid currentColor;transform:rotate(90deg);transform-origin:2px 4px;transition:transform .12s ease}.cm-host .ms-toggle[aria-expanded=false]:before{transform:none}.cm-host .ms-toggle:hover{background:var(--hover);color:var(--text)}.cm-host .ms-toggle:disabled{opacity:.35;cursor:default}.cm-host .ms-status{float:right;margin-left:12px;font-size:12px;font-weight:400;color:var(--text-faint)}.cm-host .ms-typing{color:hsl(var(--ph, 210) 65% 62%)}.cm-host .ms-empty{color:var(--del)}.cm-host .ms-you{color:var(--accent-ink)}.cm-host .ms-summary{margin-left:8px;padding:1px 8px;border-radius:5px;background:var(--hover);color:var(--text-dim);font-size:12.5px;font-weight:400;cursor:pointer}.cm-host .cm-foldPlaceholder{background:none;border:0;padding:0;margin:0}.cm-host .cm-ySelectionInfo{font-family:var(--ui);font-size:10.5px;font-weight:600;padding:1px 5px;border-radius:4px;opacity:1!important}.cm-tooltip.cm-tooltip-autocomplete{background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-card);padding:4px;box-shadow:0 18px 50px -16px #0009}.cm-tooltip.cm-tooltip-autocomplete>ul{font-family:var(--ui)!important;font-size:13px;max-height:18em}.cm-tooltip.cm-tooltip-autocomplete>ul>li{padding:6px 10px;border-radius:6px;color:var(--text)}.cm-tooltip.cm-tooltip-autocomplete>ul>li[aria-selected]{background:var(--hover);color:var(--text-bright)}.cm-tooltip.cm-tooltip-autocomplete completion-section{display:block;padding:6px 10px 2px;color:var(--text-faint);font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;border:0}.cm-tooltip-autocomplete .cm-completionDetail{margin-left:10px;color:var(--text-faint);font-style:normal;font-size:12px}.cm-tooltip-autocomplete .cm-completionMatchedText{text-decoration:none;color:var(--accent-ink)}.er-rail button.fv-sec-link{background:none;border:0;padding:0;cursor:pointer;font:inherit;font-size:12px}.fv-rail .er-empty,.fv-rail .er-note{margin:0;color:var(--text-faint);font-size:12px;line-height:1.5}.fv-rail .er-note{margin-top:8px}.er-list,.er-people,.er-vlist{list-style:none;margin:0;padding:0}.er-list li{display:flex;gap:9px;padding:5px 0;color:var(--text-body)}.er-list li.done .er-text{color:var(--text-faint);text-decoration:line-through}.er-box{flex:none;width:15px;height:15px;margin-top:2px;border:1.5px solid var(--text-faint);border-radius:4px;font-size:10px;line-height:12px;text-align:center;color:var(--bg)}.er-list li.done .er-box{background:var(--accent);border-color:var(--accent)}.er-text{display:flex;flex-direction:column;gap:1px;min-width:0;overflow-wrap:anywhere}.er-text small{color:var(--text-faint);font-size:11.5px}.er-bar{height:3px;margin:-2px 0 10px;border-radius:2px;background:var(--hover);overflow:hidden}.er-bar>span{display:block;height:100%;background:var(--add)}.er-people li{display:flex;align-items:center;gap:9px;padding:5px 0}.er-name{color:var(--text);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.er-state{margin-left:auto;font-size:12px;color:var(--text-faint);white-space:nowrap}.er-state.none{color:var(--del)}.er-state.typing{color:var(--viz-human)}.er-vlist li{display:grid;grid-template-columns:10px auto 1fr auto;align-items:center;gap:4px 8px;padding:5px 0;font-size:12px}.er-dot{width:7px;height:7px;border-radius:50%;background:var(--text-faint)}.er-dot.live{background:var(--add)}.er-dot.bad{background:var(--del)}.er-vtime{font-family:var(--mono);color:var(--text);white-space:nowrap}.er-vwho{color:var(--text-dim);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.er-vsize{font-family:var(--mono);color:var(--text-faint);text-align:right}.er-vlist li.empty .er-vsize{color:var(--del)}.er-restore{grid-column:2 / -1;justify-self:start;height:22px;padding:0 8px;border:1px solid var(--border-2);border-radius:6px;background:var(--surface);color:var(--accent-ink);font:inherit;font-size:11.5px;cursor:pointer}.er-restore:hover{background:var(--hover)}.shrink-dialog .sd-head{display:flex;align-items:center;gap:12px;margin-bottom:12px}.shrink-dialog .sd-head h3{margin:0}.sd-icon{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:color-mix(in srgb,var(--del) 14%,transparent);color:var(--del)}.sd-compare{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:0 0 18px}.sd-compare>div{display:flex;flex-direction:column;gap:3px;padding:9px 12px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface);font-size:12px;color:var(--text-faint)}.sd-compare b{font-size:14px;font-weight:600}.sd-ok{color:var(--add)}.sd-bad{color:var(--del)}.sd-actions{justify-content:space-between} diff --git a/internal/webapp/static/assets/index-DyFnf9EY.js b/internal/webapp/static/assets/index-Co6en_o0.js similarity index 99% rename from internal/webapp/static/assets/index-DyFnf9EY.js rename to internal/webapp/static/assets/index-Co6en_o0.js index 9a0c40ab..929981a7 100644 --- a/internal/webapp/static/assets/index-DyFnf9EY.js +++ b/internal/webapp/static/assets/index-Co6en_o0.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CsLWwTRs.js","assets/sharedfile-CtVUr4nt.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-CGKGr6GV.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CeIX9UEc.js","assets/sharedfile-CR4ZqPh0.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-D6HKLJJk.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CsLWwTRs.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-CGKGr6GV.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CeIX9UEc.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-D6HKLJJk.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w}; diff --git a/internal/webapp/static/assets/index-DeicSyxP.css b/internal/webapp/static/assets/index-DeicSyxP.css new file mode 100644 index 00000000..c724eb1c --- /dev/null +++ b/internal/webapp/static/assets/index-DeicSyxP.css @@ -0,0 +1 @@ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--tracking-widest:.1em;--radius-xs:.125rem;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--color-background:#0a0b0d;--color-foreground:#eef0f3;--color-card:#15171b;--color-card-foreground:#eef0f3;--color-popover:#15171b;--color-popover-foreground:#eef0f3;--color-primary:#f5a623;--color-primary-foreground:#1a1204;--color-secondary:#ffffff08;--color-secondary-foreground:#eef0f3;--color-muted:#ffffff0f;--color-muted-foreground:#9aa0a9;--color-accent:#ffffff0f;--color-accent-foreground:#eef0f3;--color-destructive:#f26d6d;--color-border:#ffffff12;--color-input:#ffffff1c;--color-ring:#f5a623;--radius-ctl:7px}}@layer base,components;@layer utilities{.\@container\/card-header{container:card-header/inline-size}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:0}.top-4{top:calc(var(--spacing) * 4)}.top-\[50\%\]{top:50%}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.left-2{left:calc(var(--spacing) * 2)}.left-\[50\%\]{left:50%}.isolate{isolation:isolate}.z-50{z-index:50}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2/span 2}.row-start-1{grid-row-start:1}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-auto{margin-left:auto}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-row{display:table-row}.field-sizing-content{field-sizing:content}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-2\.5{width:calc(var(--spacing) * 2.5);height:calc(var(--spacing) * 2.5)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-10{width:calc(var(--spacing) * 10);height:calc(var(--spacing) * 10)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.max-h-\(--radix-context-menu-content-available-height\){max-height:var(--radix-context-menu-content-available-height)}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.max-h-\[300px\]{max-height:300px}.min-h-16{min-height:calc(var(--spacing) * 16)}.w-6{width:calc(var(--spacing) * 6)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:0}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.caption-bottom{caption-side:bottom}.origin-\(--radix-context-menu-content-transform-origin\){transform-origin:var(--radix-context-menu-content-transform-origin)}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.origin-\(--radix-tooltip-content-transform-origin\){transform-origin:var(--radix-tooltip-content-transform-origin)}.translate-x-\[-50\%\]{--tw-translate-x:-50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y:-50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[calc\(-50\%_-_2px\)\]{--tw-translate-y: calc(-50% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-45{rotate:45deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.resize{resize:both}.scroll-my-1{scroll-margin-block:var(--spacing)}.scroll-py-1{scroll-padding-block:var(--spacing)}.auto-rows-min{grid-auto-rows:min-content}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-xs{border-radius:var(--radius-xs)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-input{border-color:var(--color-input)}.bg-background{background-color:var(--color-background)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab,red,red)){.bg-black\/5{background-color:color-mix(in oklab,var(--color-black) 5%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-border{background-color:var(--color-border)}.bg-card{background-color:var(--color-card)}.bg-destructive{background-color:var(--color-destructive)}.bg-foreground{background-color:var(--color-foreground)}.bg-muted\/50{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.bg-muted\/50{background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.bg-popover{background-color:var(--color-popover)}.bg-primary{background-color:var(--color-primary)}.bg-secondary{background-color:var(--color-secondary)}.bg-transparent{background-color:#0000}.fill-current{fill:currentColor}.fill-foreground{fill:var(--color-foreground)}.p-0{padding:0}.p-1{padding:var(--spacing)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-123{padding:calc(var(--spacing) * 123)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-6{padding-block:calc(var(--spacing) * 6)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-8{padding-left:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.whitespace-nowrap{white-space:nowrap}.text-background{color:var(--color-background)}.text-card-foreground{color:var(--color-card-foreground)}.text-destructive{color:var(--color-destructive)}.text-foreground{color:var(--color-foreground)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-popover-foreground{color:var(--color-popover-foreground)}.text-primary{color:var(--color-primary)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-secondary-foreground{color:var(--color-secondary-foreground)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-black\/10{--tw-ring-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.ring-black\/10{--tw-ring-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.ring-offset-background{--tw-ring-offset-color:var(--color-background)}.outline-hidden{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline-offset:2px;outline:2px solid #0000}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[background-color\,border-color\,color\]{transition-property:background-color,border-color,color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.fade-in-0{--tw-enter-opacity:0}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale:.95}.running{animation-play-state:running}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:.5}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:.5}.selection\:bg-primary ::selection{background-color:var(--color-primary)}.selection\:bg-primary::selection{background-color:var(--color-primary)}.selection\:text-primary-foreground ::selection{color:var(--color-primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--color-primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-transparent::file-selector-button{background-color:#0000}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--color-foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--color-muted-foreground)}@media(hover:hover){.hover\:bg-accent:hover{background-color:var(--color-accent)}.hover\:bg-destructive\/90:hover{background-color:#f26d6de6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--color-destructive) 90%,transparent)}}.hover\:bg-muted\/50:hover{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.hover\:bg-primary\/90:hover{background-color:#f5a623e6}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--color-primary) 90%,transparent)}}.hover\:bg-secondary\/80:hover{background-color:#ffffff06}@supports (color:color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--color-secondary) 80%,transparent)}}.hover\:text-accent-foreground:hover{color:var(--color-accent-foreground)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:bg-accent:focus{background-color:var(--color-accent)}.focus\:text-accent-foreground:focus{color:var(--color-accent-foreground)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color:var(--color-ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus-visible\:border-ring:focus-visible{border-color:var(--color-ring)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 20%, transparent)}}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:#f5a62380}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-ring) 50%, transparent)}}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-aria-expanded\:bg-muted\/50:has([aria-expanded=true]){background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.has-aria-expanded\:bg-muted\/50:has([aria-expanded=true]){background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has([data-slot=card-action]){grid-template-columns:1fr auto}.has-\[\>svg\]\:px-1\.5:has(>svg){padding-inline:calc(var(--spacing) * 1.5)}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing) * 4)}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--color-destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 20%, transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true]{pointer-events:none}.data-\[disabled\=true\]\:opacity-50[data-disabled=true]{opacity:.5}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--color-destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing) * 8)}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--color-muted-foreground)}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:var(--color-accent)}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:var(--color-accent-foreground)}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y:var(--spacing);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x:calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:calc(2*var(--spacing))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x:var(--spacing);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y:calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:calc(2*var(--spacing))}.data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing) * 9)}.data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing) * 8)}:is(.\*\*\:data-\[slot\=command-input-wrapper\]\:h-12 *)[data-slot=command-input-wrapper]{height:calc(var(--spacing) * 12)}:is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}:is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}:is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}:is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing) * 2)}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--color-accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--color-accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--color-muted-foreground)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:var(--color-muted)}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--color-destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:#f26d6d1a}@supports (color:color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--color-destructive) 10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--color-destructive)}@media(min-width:40rem){.sm\:max-w-lg{max-width:var(--container-lg)}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}}.dark\:border-input:where([data-theme=dark],[data-theme=dark] *){border-color:var(--color-input)}.dark\:bg-destructive\/60:where([data-theme=dark],[data-theme=dark] *){background-color:#f26d6d99}@supports (color:color-mix(in lab,red,red)){.dark\:bg-destructive\/60:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-destructive) 60%,transparent)}}.dark\:bg-input\/30:where([data-theme=dark],[data-theme=dark] *){background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.dark\:bg-input\/30:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-input) 30%,transparent)}}.dark\:bg-white\/10:where([data-theme=dark],[data-theme=dark] *){background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.dark\:bg-white\/10:where([data-theme=dark],[data-theme=dark] *){background-color:color-mix(in oklab,var(--color-white) 10%,transparent)}}@media(hover:hover){.dark\:hover\:bg-accent\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:#ffffff08}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:color-mix(in oklab,var(--color-accent) 50%,transparent)}}.dark\:hover\:bg-input\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:#ffffff0e}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:where([data-theme=dark],[data-theme=dark] *):hover{background-color:color-mix(in oklab,var(--color-input) 50%,transparent)}}}.dark\:focus-visible\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *):focus-visible{--tw-ring-color:#f26d6d66}@supports (color:color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *):focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 40%, transparent)}}.dark\:aria-invalid\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *)[aria-invalid=true]{--tw-ring-color:#f26d6d66}@supports (color:color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:where([data-theme=dark],[data-theme=dark] *)[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--color-destructive) 40%, transparent)}}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:where([data-theme=dark],[data-theme=dark] *)[data-variant=destructive]:focus{background-color:#f26d6d33}@supports (color:color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:where([data-theme=dark],[data-theme=dark] *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--color-destructive) 20%,transparent)}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--color-muted-foreground)}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:calc(var(--spacing) * 12)}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-block:calc(var(--spacing) * 3)}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:calc(var(--spacing) * 5)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-3 svg:not([class*=size-]){width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--color-muted-foreground)}.\[\&_tr\]\:border-b tr{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-style:var(--tw-border-style);border-width:0}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\.border-b\]\:pb-6.border-b{padding-bottom:calc(var(--spacing) * 6)}.\[\.border-t\]\:pt-6.border-t{padding-top:calc(var(--spacing) * 6)}:is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}:is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}:is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing) * 2)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:text-destructive\![data-variant=destructive]>*):is(svg){color:var(--color-destructive)!important}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y:2px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>tr\]\:last\:border-b-0>tr:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}:root[data-theme=light]{--color-bg:#fff;--color-side:#f6f7f8;--color-raise:#fff;--color-surface:#00000008;--color-hovered:#0000000d;--color-line:#00000017;--color-line-2:#00000024;--color-text:#1b1d21;--color-dim:#565c66;--color-faint:#686d76;--color-ghost:#70757e;--color-honey:#f5a623;--color-honey-bright:#a35f00;--color-honey-dim:#b86e0e;--color-glow:#f5a62329;--color-add:#17804f;--color-del:#d14343;--color-background:#fff;--color-foreground:#1b1d21;--color-card:#fff;--color-card-foreground:#1b1d21;--color-popover:#fff;--color-popover-foreground:#1b1d21;--color-primary:#f5a623;--color-primary-foreground:#1a1204;--color-secondary:#00000008;--color-secondary-foreground:#1b1d21;--color-muted:#0000000d;--color-muted-foreground:#565c66;--color-accent:#0000000d;--color-accent-foreground:#1b1d21;--color-destructive:#d14343;--color-border:#00000017;--color-input:#00000024;--color-ring:#b86e0e}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}}:root{color-scheme:dark;--bg: #0a0b0d;--bg-side: #0c0e10;--bg-raise: #15171b;--surface: rgba(255,255,255,.03);--hover: rgba(255,255,255,.06);--border: rgba(255,255,255,.07);--border-2: rgba(255,255,255,.11);--code-bg: #0d0f12;--text: #eef0f3;--text-dim: #9aa0a9;--text-faint: #868b93;--text-ghost: #666b74;--text-bright: #f4f6f9;--text-body: #c6cbd3;--code-ink: #e4d9c4;--quote-ink: #d8cdb6;--accent: #f5a623;--accent-bright: #ffcf85;--accent-dim: #d3861a;--accent-press: #e0951a;--glow: rgba(245,166,35,.13);--add: #4cc38a;--del: #f26d6d;--accent-ink: var(--accent);--accent-hover-bg: var(--accent-bright);--danger-ink: #e07070;--danger-bright: #ff8b8b;--danger-title: #d2695e;--shadow-pop: rgba(0, 0, 0, .35);--row-hover: rgba(255,255,255,.02);--row-hover-faint: rgba(255,255,255,.015);--viz-agent: #c98500;--viz-human: #5b8def;--viz-share: #d55181;--viz-fresh-1: #4cc38a;--viz-fresh-2: #3d9a6c;--viz-fresh-3: #327656;--viz-fresh-4: #285a44;--viz-flat: #969ca4;--viz-cov-0: rgba(255,255,255,.03);--viz-cov-1: #5e420a;--viz-cov-2: #7d5507;--viz-cov-3: #a06d05;--viz-cov-4: #c98500;--viz-cov-ink-1: #f4e6c8;--viz-cov-ink-2: #fff4dc;--viz-ink-dark: #0c0d10;--viz-ink-light: #eef0f3;--warn-ink: #f0883e;--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--ui: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", "Segoe UI", Roboto, sans-serif;--r-ctl: 7px;--r-card: 10px;--r-over: 14px;--page-read: 768px;--page-app: 768px;--page-wide: 1200px;--hero-top: clamp(32px, 8vh, 88px)}:root[data-theme=light]{color-scheme:light;--bg: #ffffff;--bg-side: #f6f7f8;--bg-raise: #ffffff;--surface: rgba(0,0,0,.03);--hover: rgba(0,0,0,.05);--border: rgba(0,0,0,.09);--border-2: rgba(0,0,0,.14);--code-bg: #f5f6f8;--text: #1b1d21;--text-dim: #565c66;--text-faint: #686d76;--text-ghost: #70757e;--text-bright: #0b0c0e;--text-body: #2b2f36;--code-ink: #7a4f00;--quote-ink: #4a4033;--accent: #f5a623;--accent-bright: #a35f00;--accent-dim: #b86e0e;--accent-press: #e0951a;--glow: rgba(245,166,35,.16);--add: #17804f;--del: #d14343;--accent-ink: var(--accent-bright);--accent-hover-bg: var(--accent-press);--danger-ink: #b8322a;--danger-bright: #b42318;--danger-title: #b8322a;--shadow-pop: rgba(0, 0, 0, .12);--row-hover: rgba(0,0,0,.025);--row-hover-faint: rgba(0,0,0,.02);--viz-agent: #c98500;--viz-human: #2a78d6;--viz-share: #d55181;--viz-fresh-1: #3daa78;--viz-fresh-2: #2e8a5f;--viz-fresh-3: #23704c;--viz-fresh-4: #1b573b;--viz-flat: #c8ccd2;--viz-cov-0: rgba(0,0,0,.03);--viz-cov-1: #f0ddb0;--viz-cov-2: #e3bf6e;--viz-cov-3: #d5a132;--viz-cov-4: #c98500;--viz-cov-ink-1: #4a3305;--viz-cov-ink-2: #3a2804;--warn-ink: #c4560c}@font-face{font-family:"Jersey 10";font-style:normal;font-weight:400;font-display:swap;src:url(/assets/jersey-10-COnnvJff.woff2) format("woff2")}@font-face{font-family:Logo Fallback;src:local("Helvetica Neue"),local("Arial"),local("Segoe UI"),local("Roboto");size-adjust:73%}*{box-sizing:border-box}[hidden]{display:none!important}html,body{height:100%;margin:0}#root{display:contents}body{display:flex;background:var(--bg);color:var(--text);font:13px/1.5 var(--ui);letter-spacing:-.006em;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}::selection{background:var(--glow);color:var(--accent-bright)}:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:5px}:focus-visible{outline-color:var(--accent)}.admin input:focus-visible{outline:2px solid var(--accent);outline-offset:1px}input[type=checkbox]{accent-color:var(--accent);width:20px;height:20px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}.sprite{position:absolute}.ico{width:16px;height:16px;flex:none;stroke:currentColor;stroke-width:1.6;fill:none;stroke-linecap:round;stroke-linejoin:round}button,input,a.btn{font-family:inherit}#sidebar{width:var(--sb-w, 256px);min-width:210px;max-width:min(480px,calc(100vw - 645px));position:relative;background:var(--bg-side);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden;--row-on: color-mix(in srgb, var(--text) 9%, transparent)}#vault{display:flex;align-items:center;gap:8px;flex:none;height:52px;padding:0 16px;position:relative;z-index:45}#vault-badge{flex:none;display:grid;place-items:center;color:var(--accent-ink)}#vault-name{font-family:"Jersey 10","Logo Fallback",var(--ui);font-size:18px;font-weight:400;font-synthesis:none;letter-spacing:.01em;line-height:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#vault-beta{flex:none;font-size:11px;font-weight:500;color:var(--text-faint)}.vault-actions{margin-left:auto;display:flex;align-items:center;gap:4px}#vault #signout{width:28px;height:28px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;color:var(--text-faint);background:transparent;border:none;cursor:pointer;text-decoration:none}#vault #signout:hover{color:var(--text);background:var(--hover)}#vault #signout .ico{width:16px;height:16px}#projects{flex:none;padding:0 8px}.proj-trigger{width:100%;height:32px;display:flex;align-items:center;gap:8px;padding:0 8px 0 6px;border:0;border-radius:6px;background:transparent;color:var(--text);font:inherit;font-size:13px;font-weight:500;text-align:left;cursor:pointer}.proj-trigger:hover,.proj-trigger[data-state=open]{background:var(--hover)}.proj-trigger .proj-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.proj-trigger .updown{width:16px;height:16px;color:var(--text-faint)}.proj-mark{width:20px;height:20px;border-radius:5px;flex:none;display:grid;place-items:center;background:color-mix(in srgb,var(--mk, var(--text-faint)) 18%,transparent);color:var(--mk, var(--text-faint))}.proj-mark svg{width:12px;height:12px}.proj-mark.add{background:transparent;border:1px dashed var(--border-2);color:var(--text-faint)}#projects .row,#pinned .row,#tree .row,.sb-sync{display:flex;align-items:center;gap:8px;height:28px;padding:0 8px;border-radius:6px;color:var(--text-dim);cursor:pointer;position:relative;white-space:nowrap;overflow:hidden;font-size:13px}#projects .row:hover,#pinned .row:hover,#tree .row:hover,.sb-sync:hover{background:var(--hover);color:var(--text)}#projects .row.active,#pinned .row.active,#tree .row.active,.sb-sync.active{background:var(--row-on);color:var(--text)}#projects .row.active .label,#tree .row.active .label{font-weight:500}#projects .row .label,#pinned .label,#tree .label,.sb-sync .label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#tree{flex:1;overflow-y:auto;padding:0 8px 16px}.tguide{position:absolute;top:0;bottom:0;width:1px;background:var(--border);pointer-events:none}#tree .row{gap:6px}#tree .chev{width:14px;height:14px;flex:none;color:var(--text-faint);transition:transform .12s;display:flex;align-items:center;justify-content:center}#tree .chev .ico{width:14px;height:14px}#tree .ticon{flex:none;display:flex;color:var(--text-faint)}#tree .ticon .ico{width:16px;height:16px}#tree .row:hover .ticon,#tree .row:hover .chev{color:var(--text-dim)}#tree .row.active .chev{color:var(--text)}#tree .row.active .ticon{color:var(--accent-ink)}#tree .file .chev{visibility:hidden}#tree .row.collapsed .chev{transform:rotate(-90deg)}.field-err{color:var(--del);font-size:12px;margin:6px 2px 0}.modal,#palette{translate:none}.admin-card-table{padding:0}.admin-table{width:100%;border-collapse:collapse;table-layout:fixed}.admin-table td .ai-main,.admin-table td a.ai-main,.admin-table td .ai-copy,.admin-table td .ai-tag{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.admin-table th:last-child,.admin-table td:last-child{width:186px;text-align:right}.admin-table tr:last-child td{border-bottom:none}.admin-table th{text-align:left;font-size:11px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--text-faint);padding:0;border-bottom:1px solid var(--border);-webkit-user-select:none;user-select:none}.admin-table td{padding:0;border-bottom:1px solid var(--border);overflow:hidden;text-overflow:ellipsis}.admin-table tr.admin-item{display:table-row}.admin-table tr.admin-item td{padding:8px 10px}.admin-card-table{overflow-x:auto}.shares-table .admin-table th:last-child,.shares-table .admin-table td:last-child{width:150px}.share-acts{display:inline-flex;align-items:center;gap:6px}.share-acts .ai-btn{display:inline-flex;align-items:center;justify-content:center;padding:0 8px}.share-acts .ai-btn .ico{width:15px;height:15px}.shares-table .admin-table td .ai-tag{white-space:normal;overflow:visible;text-overflow:clip}.share-banner{margin:0 0 18px;padding:12px 14px;border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:var(--r-ctl);background:var(--surface)}.share-banner .sb-head{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text)}.share-banner .sb-head .ico,.share-banner .sb-head svg{width:15px;height:15px;flex:none;color:var(--accent-ink)}.share-banner .sb-count{color:var(--text-faint);font-size:12px}.share-banner .sb-note{margin:6px 0 10px;font-size:12.5px;line-height:1.55;color:var(--text-faint);max-width:64ch}.share-banner .sb-link{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding-top:8px;border-top:1px solid var(--border)}.share-banner .sb-link+.sb-link{margin-top:8px}.share-banner .sb-url{flex:1 1 260px;min-width:0;font-size:12px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.share-banner .sb-meta{font-size:11.5px;color:var(--text-faint)}.share-banner .sb-actions{display:flex;align-items:center;gap:6px;margin-left:auto}.nav-menu{list-style:none;margin:0;padding:0}.nav-menu .row .ico{width:16px;height:16px;flex:none}.nav-count{flex:none;margin-left:auto;font-size:12px;font-weight:500;color:var(--text-faint);font-variant-numeric:tabular-nums}#accountbar{position:relative;padding:4px 8px 8px}.gh-star{display:flex;align-items:center;gap:8px;padding:4px 8px;margin-bottom:2px;border-radius:6px;color:var(--text-faint);font-size:11px;text-decoration:none}.gh-star:hover{background:var(--hover);color:var(--text)}.gh-star .gh-mark{width:12px;height:12px;flex:none}.gh-star .ext{margin-left:auto;font-size:9px}#account-btn{width:100%;display:flex;align-items:center;gap:8px;text-align:left;padding:6px 8px;border:none;border-radius:6px;background:transparent;color:var(--text-dim);cursor:pointer;font:inherit}#account-btn:hover{background:var(--hover);color:var(--text)}#account-btn .avatar{width:24px;height:24px;flex:none;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--text-dim);font-size:11px;font-weight:600}#account-btn .acct{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}#account-btn .acct b{font-size:13px;font-weight:500;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#account-btn .acct small{font-size:12px;color:var(--text-faint);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.sb-menu{min-width:248px;max-width:300px;padding:4px;border:1px solid var(--border-2);border-radius:10px;background:var(--bg-raise);box-shadow:0 12px 32px var(--shadow-pop);z-index:80;outline:none;font-size:13px;color:var(--text)}.sb-menu [role=menuitem]{display:flex;align-items:center;gap:8px;height:32px;padding:0 8px;border-radius:6px;color:var(--text);font:inherit;font-size:13px;text-decoration:none;cursor:pointer;outline:none}.sb-menu [role=menuitem][data-highlighted]{background:var(--hover)}.sb-menu [role=menuitem]>.ico{width:16px;height:16px;color:var(--text-dim)}.sb-menu [role=menuitem][aria-current=page]{background:var(--row-on, var(--hover))}.sb-menu .label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-menu .label.dim{color:var(--text-dim)}.sb-menu .meta{flex:none;margin-left:auto;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-menu .ext{flex:none;font-size:10px;color:var(--text-faint)}.sb-menu .plan-chip{margin-left:auto;color:var(--accent-ink);border-color:var(--border-2)}.sb-menu-projects{max-height:224px;overflow-y:auto}.sb-menu [role=separator]{height:1px;margin:4px -4px;background:var(--border)}.sb-menu-label{padding:6px 8px 2px;font-size:12px;font-weight:400;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sb-theme{display:flex;align-items:center;height:32px;padding:0 4px 0 8px}.sb-theme>.label{flex:1;color:var(--text-dim)}.sb-theme .seg{display:inline-flex;gap:2px;padding:2px;border-radius:7px;background:var(--hover)}.sb-menu .seg-item{width:26px;height:22px;padding:0;display:grid;place-items:center;border-radius:5px;color:var(--text-faint);cursor:pointer;outline:none}.sb-menu .seg-item>span:first-child{display:none}.sb-menu .seg-item .ico{width:14px;height:14px}.sb-menu .seg-item[data-highlighted]{color:var(--text)}.sb-menu .seg-item[data-state=checked]{background:var(--bg-raise);color:var(--text);box-shadow:0 0 0 1px var(--border-2)}#billing-view .plan-chip{color:var(--accent-ink)}.plan-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:700px){.plan-grid{grid-template-columns:1fr}}.usage-bar{background:var(--surface);border:1px solid var(--border);border-radius:4px;height:6px;overflow:hidden}.usage-bar>div{background:var(--accent);height:100%}.plan-price{font-size:20px;font-weight:700;margin:0 0 10px}.plan-price small{font-size:12px;color:var(--text-dim);font-weight:500}.muted-note{color:var(--text-dim);font-size:13px}#main{flex:1;display:flex;flex-direction:column;min-width:0}#topbar{position:relative;display:flex;align-items:center;gap:9px;height:52px;padding:0 16px;border-bottom:1px solid var(--border)}.icon-btn{display:none;width:34px;height:34px;border:none;background:transparent;color:var(--text-dim);cursor:pointer;border-radius:7px;align-items:center;justify-content:center}.icon-btn:hover{color:var(--text);background:var(--hover)}#menu-btn{display:inline-flex}@media(min-width:901px){body.sb-collapsed #sidebar{width:48px;min-width:48px}body.sb-collapsed #sidebar>:not(#rail){display:none}body.sb-collapsed #rail{display:flex}}#sb-resize{position:absolute;top:0;right:0;bottom:0;width:6px;z-index:50;cursor:col-resize;touch-action:none}#sb-resize:hover,#sb-resize:focus-visible,body.sb-resizing #sb-resize{background:color-mix(in srgb,var(--text) 18%,transparent);outline:none}body.sb-resizing{cursor:col-resize;-webkit-user-select:none;user-select:none}@media(max-width:900px){#sb-resize{display:none}}#nav-btns{display:inline-flex;gap:2px;flex:none}.nav-btn{display:inline-flex;width:30px;height:30px;border:none;background:transparent;color:var(--text-dim);cursor:pointer;border-radius:7px;align-items:center;justify-content:center}.nav-btn:hover{color:var(--text);background:var(--hover)}.nav-btn .ico{width:17px;height:17px}#crumb{font-size:12.5px;color:var(--text);font-weight:500;letter-spacing:-.01em;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#crumb .crumb-seg{color:var(--text-dim);cursor:pointer}#crumb .crumb-seg:hover{color:var(--accent-bright)}#crumb .crumb-sep{color:var(--text-ghost);margin:0 6px}#crumb .crumbs{display:inline-flex;align-items:baseline;min-width:0;max-width:100%;vertical-align:bottom}#crumb .crumb{display:inline-flex;align-items:baseline;min-width:0;flex:none}#crumb .crumb-mid{display:inline-block;max-width:12ch;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:bottom}#crumb .crumb:last-child{flex:0 1 auto;min-width:0;overflow:hidden}#crumb .crumb-last{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#meta{flex:1;min-width:0;font-size:12px;color:var(--text-faint);text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.meta-stale{color:var(--danger-ink)}.btn{display:inline-flex;align-items:center;gap:6px;flex:none;height:30px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text-dim);font-size:12.5px;font-weight:500;cursor:pointer;text-decoration:none}.btn:hover{background:var(--hover);color:var(--text);border-color:var(--border-2)}.btn .ico{width:15px;height:15px}.btn.ghost{color:var(--text-dim)}.tipcard{display:flex;align-items:center;gap:7px;white-space:nowrap;padding:6px 9px;border-radius:8px;border:1px solid var(--border-2);background:var(--surface-solid, var(--bg-raise));color:var(--text);font-size:12.5px;font-weight:500;box-shadow:0 8px 24px var(--shadow-pop);z-index:80}.tipcard kbd{font:11px var(--ui);color:var(--text-faint);background:var(--hover);border:1px solid var(--border-2);border-radius:5px;padding:1px 5px}#more-menu{position:absolute;right:12px;top:calc(100% - 4px);z-index:80;background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-card);box-shadow:0 18px 44px -14px #000000bf;padding:6px;min-width:168px}:root[data-theme=light] #more-menu{box-shadow:0 18px 44px -14px #0000002e}.more-item{display:block;width:100%;text-align:left;min-height:40px;padding:0 12px;background:transparent;border:none;cursor:pointer;color:var(--text);font:inherit;font-size:13.5px;border-radius:var(--r-ctl)}.more-item:hover{background:var(--hover)}#content{--content-pad-b: 110px;flex:1;overflow-y:auto;padding:44px 40px var(--content-pad-b);scroll-behavior:smooth;scrollbar-gutter:stable}@media(pointer:fine){#content::-webkit-scrollbar{width:10px}#content::-webkit-scrollbar-thumb{background:var(--border-2);border-radius:5px}#content::-webkit-scrollbar-track{background:transparent}@supports not selector(::-webkit-scrollbar){#content{scrollbar-width:thin;scrollbar-color:var(--border-2) transparent}}}.page{width:100%;max-width:var(--page-app);margin-inline:auto;min-width:0}.page.read{max-width:var(--page-read)}.page.wide{max-width:var(--page-wide)}.page.read{position:relative}.rw-handle{position:absolute;top:0;bottom:0;width:14px;z-index:5;cursor:col-resize;touch-action:none;outline:none}.rw-left{left:-26px}.rw-right{right:-26px}.rw-handle:after{content:"";position:absolute;top:0;bottom:0;left:6px;width:2px;border-radius:1px;background:var(--border-2);opacity:0;transition:opacity .12s ease}.rw-handle:hover:after,.rw-handle:focus-visible:after{opacity:1}.rw-handle.dragging:after{opacity:1;background:var(--accent)}body.rw-dragging{cursor:col-resize;-webkit-user-select:none;user-select:none}@media(max-width:900px){.rw-handle{display:none}}.empty{color:var(--text-faint);text-align:center;margin-top:var(--hero-top)}.empty-hint{display:block;margin-top:6px;font-size:12px;color:var(--text-faint)}.onboard{max-width:560px;margin:var(--hero-top) auto 0}.onboard h1{font-size:25px;font-weight:640;letter-spacing:-.02em;margin:0 0 8px;color:var(--text-bright)}.onboard>p{color:var(--text-dim);margin:0 0 28px;font-size:14px}.ob-card,.setup-card{border:1px solid var(--border);border-radius:var(--r-card)}.ob-card{background:var(--bg-side);padding:20px 22px;margin-bottom:14px}.ob-card h3{margin:0 0 6px;font-size:14.5px;font-weight:600}.ob-card p{margin:0 0 14px;font-size:13px;color:var(--text-dim)}.ob-card.ob-start{border-color:var(--border-2);box-shadow:inset 2px 0 0 var(--accent)}.ob-card.ob-start .pbtn{margin-top:2px}.ob-alt{margin:12px 0 0}.ob-alt a{color:var(--text-faint);font-size:12.5px;font-weight:600;text-decoration:none}.ob-alt a:hover{color:var(--text)}.pbtn{display:inline-flex;align-items:center;gap:6px;flex:none;height:32px;padding:0 14px;border-radius:var(--r-ctl);border:none;background:var(--accent);color:#241704;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;text-decoration:none}.pbtn:hover{background:var(--accent-hover-bg)}.pbtn .ico{width:15px;height:15px}.danger-btn{display:inline-flex;align-items:center;height:32px;padding:0 14px;border-radius:var(--r-ctl);border:none;background:#b3382e;color:#fff;font-size:13px;font-weight:600;cursor:pointer}.danger-btn:hover{background:#c94336}[data-slot=input],[data-slot=textarea]{font:inherit;color:var(--text)}[data-slot=input][aria-invalid=true]:focus-visible,[data-slot=textarea][aria-invalid=true]:focus-visible{border-color:var(--del)}[data-slot=card],[data-slot=dropdown-menu-content]{border-color:var(--border)}.project-settings{display:flex;flex-direction:column;gap:14px}.project-settings>h2{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.ps-form{display:flex;flex-direction:column;gap:18px}.ps-field{display:flex;flex-direction:column;gap:7px}.ps-field label{font-size:12.5px;color:var(--text-dim)}.ps-opt{color:var(--text-ghost);font-weight:400}.ps-icon-row{display:flex;align-items:center;gap:10px}.ps-icon-row .proj-mark{width:26px;height:26px;border-radius:7px}.ps-icon-row .proj-mark svg{width:15px;height:15px}.ps-meta{display:flex;align-items:baseline;justify-content:space-between;gap:12px}.ps-meta .field-err{flex:0 1 auto;margin:0}.ps-count{font-size:11.5px;color:var(--text-faint);font-variant-numeric:tabular-nums}.ps-actions{display:flex;justify-content:flex-end}.ps-icon-grid{display:grid;grid-template-columns:repeat(6,30px);gap:4px;padding:8px}.ps-icon-cell{display:grid;place-items:center;width:30px;height:30px;border-radius:7px;border:1px solid transparent;background:none;color:var(--text-dim);cursor:pointer}.ps-icon-cell svg{width:16px;height:16px}.ps-icon-cell:hover{background:var(--hover);color:var(--text)}.ps-icon-cell.active{border-color:var(--accent);color:var(--accent-bright)}.ps-danger [data-slot=card-title]{font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--danger-title);font-weight:600}.mcp-projects{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 14px}.mcp-projects .ps-chip{margin-left:0}.ps-chip{margin-left:10px;padding:2px 8px;border-radius:999px;border:1px solid var(--border);background:var(--surface);color:var(--text-faint);font-size:11px;font-weight:600;letter-spacing:.02em;vertical-align:middle}.ps-people h4{font-size:12.5px;font-weight:600;color:var(--text-dim);margin:0}.ps-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:13px;color:var(--text-dim);margin:0 0 10px}.ps-people select{height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px}.ps-people select:disabled{opacity:.6;cursor:default}.ps-note{color:var(--text-faint);font-size:12.5px;margin:0 0 12px;max-width:56ch;line-height:1.55}.ps-people-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:20px 0 8px}.ps-danger p{color:var(--text-dim);font-size:13px;margin:0 0 14px;max-width:52ch;line-height:1.55}.ps-facts{display:grid;grid-template-columns:auto 1fr;gap:8px 20px;margin:0;font-size:13px}.ps-facts dt{color:var(--text-faint)}.ps-facts dd{margin:0;color:var(--text-dim)}.ps-export{margin:16px 0 0;max-width:62ch}.ps-export code{font-size:12px;padding:1px 5px;border-radius:4px;background:var(--surface);border:1px solid var(--border);color:var(--text)}.ps-export a{color:var(--accent-bright);text-decoration:none}.admin h1{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright)}.admin h3{font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600;margin:30px 0 10px}.admin-lbl{flex:1 1 100%;margin:0 0 6px;font-size:12.5px;font-weight:600;color:var(--text-dim)}.admin-sub{color:var(--text-dim);font-size:13.5px;margin:-2px 0 16px;line-height:1.55}.admin-h{display:flex;align-items:center;justify-content:space-between;margin:30px 0 10px}.admin-h h3{margin:0}.admin-row{display:flex;gap:9px;margin-bottom:8px}.admin-row input{flex:1;height:34px;padding:0 12px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:13px;outline:none}.admin-row input:focus{border-color:var(--accent);background:var(--hover)}.admin-list{border:1px solid var(--border);border-radius:var(--r-card);overflow:hidden;background:var(--bg-side)}.admin-list.admin-card-table{overflow-x:auto;overflow-y:hidden}.admin-item{display:flex;align-items:center;gap:11px;padding:11px 14px;border-bottom:1px solid var(--border);font-size:13.5px}.modal-actions .ai-btn{height:32px}.empty a{color:var(--accent-ink);text-decoration:none;display:inline-block;padding:6px 10px}.empty a:hover{text-decoration:underline}.empty h3{margin:0 0 8px;font-size:16px;color:var(--text)}.ai-copy{text-align:left;background:none;border:0;padding:6px 0;cursor:pointer}.ai-copy:hover{color:var(--text)}a.ai-main{color:var(--text-dim);text-decoration:none;padding:6px 0}a.ai-main:hover{color:var(--accent-ink)}.th-sort{display:block;width:100%;text-align:left;background:none;border:0;padding:6px 10px;font:inherit;color:inherit;letter-spacing:inherit;text-transform:inherit;cursor:pointer}.th-sort:hover{color:var(--text-dim)}.role-cell{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center;justify-items:start}.admin-table td .role-static{text-align:left}.role-chip-row{margin:-6px 0 12px}.role-chip{margin-left:0;padding:2px 8px;border:1px solid var(--border-2);border-radius:99px;vertical-align:middle}.ext{margin-left:4px;color:var(--text-faint);font-size:11px}.admin-item:last-child{border-bottom:none}.admin-item:hover{background:var(--hover)}.field-err{flex:1 1 100%;margin:6px 0 0}.admin-row{flex-wrap:wrap}.admin-row input[aria-invalid=true]{border-color:var(--del)}.ai-main{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}.admin-item>.ai-main{flex:1 1 55%;min-width:22ch}.admin-item>.ai-tag{flex:0 0 auto;min-width:0;max-width:45%}@media(max-width:1000px){.admin-item{flex-wrap:wrap}.admin-item>.ai-tag{flex:1 1 100%;max-width:100%}}.admin-table td .ai-main{min-width:0}.ai-main.mono{font:12px var(--mono);color:var(--text-dim);cursor:pointer}.ai-tag{font-size:11.5px;color:var(--text-faint);flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.admin-item select{height:28px;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:0 8px;font:inherit;font-size:12.5px;cursor:pointer}.admin-item select:hover{border-color:var(--border-2)}.ai-btn,.ai-del{flex:none;height:27px;padding:0 11px;border-radius:6px;border:1px solid var(--border);background:var(--surface);color:var(--text-dim);font:inherit;font-size:12px;font-weight:500;cursor:pointer}.ai-del{color:var(--del);border-color:#f26d6d47}.ai-del:hover{background:#f26d6d1f;border-color:var(--del);color:var(--danger-bright)}.ai-btn:hover{background:var(--hover);color:var(--text);border-color:var(--border-2)}.admin-empty{padding:14px;color:var(--text-faint);font-size:13px}.admin-item.toggle{cursor:pointer;align-items:flex-start}.admin-item.toggle .ai-main{white-space:normal}.tg-label{font-size:13.5px;font-weight:550;color:var(--text)}.tg-desc{font-size:12px;color:var(--text-faint);margin-top:3px;line-height:1.5}.admin-item.toggle input{margin-top:2px;flex:none}.dl-title{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.dl-title-icon{display:flex;color:var(--accent-ink)}.dl-title-icon .ico{width:20px;height:20px}.dl-sub{color:var(--text-faint);font-size:12.5px;margin:0 0 18px}.dl-heatnote{color:var(--text-faint);font-size:12px;opacity:.8;margin:-14px 0 18px}.dl-items{border:1px solid var(--border);border-radius:var(--r-card);overflow:hidden;background:var(--bg-side)}.dl-row{display:flex;align-items:center;gap:11px;padding:10px 14px;border-bottom:1px solid var(--border);cursor:pointer}.dl-row:last-child{border-bottom:none}.dl-row:hover{background:var(--hover)}.dl-row .ticon{flex:none;display:flex;color:var(--text-ghost)}.dl-row .ticon .ico{width:16px;height:16px}.dl-row:hover .ticon{color:var(--text-faint)}.dl-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13.5px;color:var(--text)}.dl-name,#crumb,.hpath,.hnote,.hrun-note,.hdev,.ai-main,.hc-name,.hc-dir,.fe-who,.fe-path,.fe-dev,.dev-name,.ha-title,.ha-sub,.hb-label>span:first-child{unicode-bidi:isolate-override;direction:ltr}.dl-meta{flex:none;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums}.dl-conflict{flex:none;font-size:10.5px;line-height:1;letter-spacing:.02em;text-transform:uppercase;padding:3px 6px;border-radius:999px;border:1px solid var(--accent-dim);background:var(--glow);color:var(--accent-bright);white-space:nowrap}.trestricted{flex:none;display:inline-flex;align-items:center;margin-left:5px;color:var(--text-faint)}.trestricted svg{width:11px;height:11px}.dl-restricted{flex:none;font-size:10.5px;line-height:1;letter-spacing:.02em;text-transform:uppercase;padding:3px 6px;border-radius:999px;border:1px solid var(--border-2);background:var(--surface);color:var(--text-dim);white-space:nowrap}.heatdot{flex:none;width:7px;height:7px;border-radius:50%;background:var(--accent)}.heatdot.lvl1{opacity:.3}.heatdot.lvl2{opacity:.55}.heatdot.lvl3{opacity:.8}.heatdot.lvl4{opacity:1;box-shadow:0 0 6px #f5a6238c}.stalemark{flex:none;font-size:11px;line-height:1;color:var(--danger-ink)}.dl-empty{padding:24px 14px;color:var(--text-faint);font-size:13px;border:1px dashed var(--border);border-radius:var(--r-card);text-align:center}.dl-h3{margin:28px 0 8px;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600}.dl-hlist{border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);overflow:hidden;max-width:none}.dl-hlist .hentry:last-child{border-bottom:none}.hentry.clickable{cursor:pointer}.hentry.clickable:hover{background:var(--hover)}.dl-more{margin-top:10px}#vault-name.vault-link{cursor:pointer}#vault-name.vault-link:hover{color:var(--accent-bright)}.gd-body{margin-top:18px}.gd-desc{margin:2px 0 8px;color:var(--text-faint);font-size:13px;line-height:1.5}.gd-list{margin:4px 0 8px;padding-left:18px;display:grid;gap:6px}.gd-code{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:10px;margin:6px 0 10px;padding:10px 12px;background:var(--bg-raise);border:1px solid var(--border);border-radius:var(--r-card);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;line-height:1.6;color:var(--text)}.gd-code>code{display:block;min-width:0;overflow-x:auto;white-space:pre}.gd-copy{align-self:start;font:inherit;font-family:inherit;font-size:11px;font-weight:600;padding:3px 9px;border-radius:6px;border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text-faint);cursor:pointer}.gd-copy:hover{color:var(--accent-bright);border-color:var(--accent-dim)}.gd-manual{margin:10px 0 0}.gd-manual>summary{display:inline-block;font-size:12.5px;font-weight:600;color:var(--text-faint);cursor:pointer;padding:4px 0}.gd-manual>summary:before{content:"▸ ";color:var(--text-ghost)}.gd-manual[open]>summary:before{content:"▾ "}.gd-manual>summary:hover{color:var(--text)}.home-insights{margin-top:30px;padding-top:22px;border-top:1px solid var(--border)}.in-title{font-size:21px;font-weight:640;letter-spacing:-.02em;margin:0 0 4px;color:var(--text-bright)}.in-title .in-scope{color:var(--text-ghost);font-weight:500;font-size:15px}.gd-head{display:flex;align-items:center;gap:9px}.gd-head .proj-mark{width:22px;height:22px;border-radius:6px}.gd-head .proj-mark svg{width:13px;height:13px}.in-desc{color:var(--text-dim);font-size:13.5px;line-height:1.55;margin:0 0 10px;max-width:62ch}.in-blank{display:grid;justify-items:center;gap:10px;padding:40px 18px;margin-top:14px;max-width:760px}.in-blank p{margin:0;max-width:52ch;line-height:1.55}.in-blank p:first-child{color:var(--text);font-size:14.5px;font-weight:600}.in-blank .pbtn{margin-top:6px}.in-top{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:4px}.in-top .in-title{margin:0}.in-lens{display:inline-flex;gap:2px;padding:2px;border-radius:var(--r-ctl);background:var(--hover)}.in-lens-btn{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;border:none;background:none;color:var(--text-faint);cursor:pointer;display:inline-flex;align-items:center;gap:6px}.in-lens-btn:hover{color:var(--text)}.in-lens-btn.active{color:var(--text-bright);background:var(--bg-raise)}.in-lens-btn .in-sw{width:8px;height:8px}.in-sec{margin:30px 0 0;min-width:0}.in-sec-head{display:flex;justify-content:space-between;align-items:flex-end;gap:12px;flex-wrap:wrap;margin-bottom:10px}.in-h2{font-size:16px;font-weight:640;color:var(--text-bright);margin:0 0 3px;letter-spacing:-.01em}.in-sub{margin:0;font-size:12.5px;color:var(--text-faint)}.in-sec-tools{display:flex;align-items:center;gap:10px}.in-astable{font:inherit;font-size:11.5px;padding:3px 9px;border-radius:var(--r-ctl);border:1px solid var(--border);background:none;color:var(--text-faint);cursor:pointer}.in-astable:hover,.in-astable[aria-pressed=true]{color:var(--text);border-color:var(--border-2)}.in-table-wrap{max-height:420px;overflow:auto;border:1px solid var(--border);border-radius:var(--r-card)}.in-data-table{width:100%;border-collapse:collapse;font-size:12px}.in-data-table th,.in-data-table td{padding:5px 10px;border-bottom:1px solid var(--border);text-align:left;white-space:nowrap}.in-data-table th{position:sticky;top:0;background:var(--bg-side);color:var(--text-faint);font-weight:600}.in-data-table td{color:var(--text);font-variant-numeric:tabular-nums}.in-split{display:grid;grid-template-columns:minmax(0,680fr) minmax(0,380fr);gap:28px;align-items:start}.in-split>.in-sec{margin-top:30px}.in-sec-hot>.in-sec{margin-top:14px}.in-sec-hot>.in-sec .in-h2{font-size:13px}@media(max-width:1100px){.in-split{grid-template-columns:minmax(0,1fr)}}.in-flag{display:inline-block;font-size:12px;line-height:1;margin-right:5px}.in-flag-stale{color:var(--warn-ink)}.in-flag-empty{color:var(--del)}.in-kpis{display:grid;grid-template-columns:minmax(0,1.3fr) repeat(3,minmax(0,1fr));border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin-top:18px}.in-kpi{padding:14px 16px;border-left:1px solid var(--border);min-width:0}.in-kpi:first-child{border-left:none}.in-kpi-l{font-size:12px;color:var(--text-faint)}.in-kpi-v{font-size:26px;font-weight:660;color:var(--text-bright);letter-spacing:-.02em;display:flex;align-items:baseline;gap:8px;margin:4px 0 8px;font-variant-numeric:tabular-nums}.in-kpi-v small{font-size:12px;font-weight:500;color:var(--text-faint)}.in-kpi-bar{display:flex;gap:2px;height:5px;border-radius:3px;overflow:hidden;margin-bottom:7px}.in-kpi-bar>span{min-width:2px}.in-kpi-meter{background:var(--hover)}.in-kpi-fill{background:var(--viz-fresh-1);border-radius:3px}.in-kpi-n{font-size:11.5px;color:var(--text-faint);display:flex;flex-wrap:wrap;gap:4px 10px}.in-kpi[data-kpi=reads] .in-kpi-n{flex-wrap:nowrap;gap:8px;white-space:nowrap}.in-status{font-size:11px;font-weight:600;padding:2px 7px;border-radius:5px;letter-spacing:0}.in-status-warn{color:var(--warn-ink);background:color-mix(in srgb,var(--warn-ink) 14%,transparent)}.in-status-crit{color:var(--del);background:color-mix(in srgb,var(--del) 14%,transparent)}@media(max-width:900px){.in-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.in-kpi:nth-child(3){border-left:none}.in-kpi:nth-child(n+3){border-top:1px solid var(--border)}.in-kpi[data-kpi=reads] .in-kpi-n{flex-wrap:wrap;gap:4px 10px}}.in-thresholds{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--text);border:1px solid var(--border);border-radius:var(--r-ctl);padding:3px 10px}.in-thresholds input{width:44px;font:inherit;font-size:12px;padding:1px 4px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--text-bright);text-align:right}.in-fix-none{padding:14px;font-size:13px;color:var(--text-faint);border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side)}.in-fix-table{width:100%;border-collapse:collapse;border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);font-size:13px}.in-fix-table th{text-align:left;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600;padding:9px 12px;border-bottom:1px solid var(--border)}.in-fix-table td{padding:8px 12px;border-bottom:1px solid var(--border);vertical-align:middle}.in-fix-row:last-child td{border-bottom:none}.in-fx-file{display:flex;align-items:center;max-width:320px}.in-fx-name{display:grid;min-width:0}.in-fx-name>span,.in-fx-name small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.in-fx-name>span{color:var(--text-bright)}.in-fx-name small{font-family:var(--mono);font-size:11px;color:var(--text-faint)}.in-fx-reads{width:30%}.in-fx-reads{display:table-cell}.in-fx-track{display:inline-flex;width:calc(100% - 44px);vertical-align:middle}.in-fx-bar{display:flex;gap:2px;height:7px;border-radius:3px;overflow:hidden}.in-fx-n{display:inline-block;width:38px;text-align:right;font-size:12px;color:var(--text);font-variant-numeric:tabular-nums}.in-fx-when{color:var(--text-dim);white-space:nowrap}.in-fx-when.empty{color:var(--del)}.in-fx-why{color:var(--text-body)}.in-fx-act{text-align:right}.in-fx-act .pbtn{height:26px;font-size:12px;padding:0 11px}.in-fx-review{font:inherit;font-size:12px;height:26px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:none;color:var(--text);cursor:pointer}.in-fx-review:hover{background:var(--hover)}@media(max-width:800px){.in-fx-why,.in-fix-table th:nth-child(4){display:none}}.in-chart{display:block;width:100%;max-width:760px;height:auto;border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin-bottom:6px}.in-axis{stroke:var(--border);stroke-width:1}.in-threshold{stroke:var(--warn-ink);stroke-opacity:.45;stroke-width:1;stroke-dasharray:4 4}.in-danger-zone{fill:var(--warn-ink);fill-opacity:.06}.in-label,.in-tick{fill:var(--text-faint);font-size:11px}.in-tick{font-size:10px;font-variant-numeric:tabular-nums}.in-quad{fill:var(--text-faint);font-size:10.5px;text-transform:uppercase;letter-spacing:.06em}.in-quad-danger{fill:var(--warn-ink);font-weight:650}.in-quad-count{fill:var(--warn-ink);font-size:10.5px;font-weight:650}.in-pt{fill:var(--text-faint);fill-opacity:.35;cursor:pointer}.in-pt:hover{fill-opacity:.9}.in-pt.danger{fill:var(--warn-ink);fill-opacity:1;stroke:var(--bg-side);stroke-width:2;paint-order:stroke}.in-pt.empty{fill:var(--del);fill-opacity:1;stroke:var(--bg-side);stroke-width:2;paint-order:stroke}.in-pt-label{fill:var(--text);font-size:11px;pointer-events:none}.in-cap{font-size:11.5px;color:var(--text-faint);font-weight:400}.in-sw-other{background:var(--text-faint);opacity:.5;border-radius:50%}.in-sw-stale{background:var(--warn-ink);border-radius:50%}.in-sw-empty{background:var(--del);border-radius:50%}.in-treemap{background:var(--bg-side)}.in-tm-cell{cursor:pointer;stroke:var(--bg-side);stroke-width:1}.in-tm-cell:hover{stroke:var(--text)}.in-tm-b1{fill:var(--viz-fresh-1);background:var(--viz-fresh-1)}.in-tm-b2{fill:var(--viz-fresh-2);background:var(--viz-fresh-2)}.in-tm-b3{fill:var(--viz-fresh-3);background:var(--viz-fresh-3)}.in-tm-b4{fill:var(--viz-fresh-4);background:var(--viz-fresh-4)}.in-tm-flat{fill:var(--viz-flat)}.in-tm-cell.flag-stale{stroke:var(--warn-ink);stroke-width:2.5}.in-tm-cell.flag-empty{stroke:var(--del);stroke-width:2.5}.in-tm-label{fill:var(--viz-ink-dark);font-size:11.5px;font-weight:620;cursor:pointer;pointer-events:none}.in-tm-label.on-dark{fill:var(--viz-ink-light)}.in-tm-sub{font-weight:450;font-size:10.5px;fill-opacity:.8}.in-tm-crumbs{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-faint);margin-bottom:8px}.in-tm-crumbs button{font:inherit;background:none;border:none;padding:0;color:var(--accent-ink);cursor:pointer}.in-tm-crumbs button.cur,.in-tm-crumbs .cur{color:var(--text)}.in-tm-crumbs .in-tm-open{margin-left:8px;color:var(--text-faint);text-decoration:underline}.in-tm-hint{margin-left:4px}.in-tm-legend{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px}.in-tm-key{display:inline-flex;align-items:center;gap:5px}.in-sw-age{display:inline-flex;gap:12px}.in-sw-flat{filter:grayscale(1);opacity:.45}.in-tm-range{color:var(--text-faint);flex-basis:100%}.in-hotpath{position:relative;display:grid;gap:2px}.in-hotpath>.in-sw{display:none}.in-hp-total{font-size:11.5px;color:var(--text-faint);font-variant-numeric:tabular-nums}.in-hp-row{display:grid;gap:4px;padding:4px 6px;border-radius:5px;cursor:pointer}.in-hp-row:hover{background:var(--hover)}.in-hp-line{display:flex;align-items:baseline;gap:8px;min-width:0}.in-hp-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12.5px;color:var(--text)}.in-hp-bar{display:flex;height:5px}.in-hp-bar>span{border-radius:3px}.in-hp-agent{background:var(--viz-agent)}.in-hp-human{background:var(--viz-human)}.in-hp-share{background:var(--viz-share)}.in-hp-none{font-size:12px;color:var(--text-faint);padding:6px}.in-hp-gone{flex:none;font-size:11.5px;color:var(--text-faint);white-space:nowrap}.in-hp-count{flex:none;text-align:right;font-size:11.5px;color:var(--text);font-variant-numeric:tabular-nums}.in-legend{margin:8px 2px 0;font-size:11.5px;color:var(--text-faint)}.in-sw{display:inline-block;width:10px;height:10px;border-radius:2px;vertical-align:-1px}.in-sw.agent{background:var(--viz-agent)}.in-sw.human{background:var(--viz-human)}.in-sw.share{background:var(--viz-share)}.in-cov{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:26px;align-items:start}@media(max-width:1000px){.in-cov{grid-template-columns:minmax(0,1fr)}}.in-matrix-wrap{overflow-x:auto}.in-matrix{border-collapse:separate;border-spacing:3px;font-size:11.5px}.in-matrix th{font-weight:500;color:var(--text-faint);padding:0 4px;white-space:nowrap}.in-matrix thead th{font-size:11px;text-align:center}.in-matrix tbody th{text-align:left;color:var(--text);max-width:170px;overflow:hidden;text-overflow:ellipsis}.in-cv{min-width:46px;height:24px;text-align:center;border-radius:4px;font-variant-numeric:tabular-nums}.in-cv-0{background:var(--viz-cov-0);color:var(--text-faint)}.in-cv-1{background:var(--viz-cov-1);color:var(--viz-cov-ink-1)}.in-cv-2{background:var(--viz-cov-2);color:var(--viz-cov-ink-2)}.in-cv-3{background:var(--viz-cov-3);color:var(--viz-ink-dark)}.in-cv-4{background:var(--viz-cov-4);color:var(--viz-ink-dark)}.in-cv-total{text-align:right;color:var(--text);padding-left:10px;font-variant-numeric:tabular-nums}.in-cv-legend{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center}.in-takeaways h3{margin:0 0 10px;font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--text-faint);font-weight:600}.in-takeaway{display:flex;gap:9px;margin-bottom:12px;font-size:12.5px}.in-takeaway b{color:var(--text-bright);font-weight:600}.in-takeaway p{margin:3px 0 0;color:var(--text-dim);line-height:1.45}.in-tk-ico{flex:none;margin-top:2px;color:var(--accent-ink)}.hfilters{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:0 0 12px;border-bottom:1px solid var(--border);margin-bottom:4px}.hf-search{position:relative;display:flex;align-items:center;flex:1 1 200px;min-width:160px}.hf-search .ico{position:absolute;left:9px;width:14px;height:14px;color:var(--text-ghost);pointer-events:none}.hf-search input{height:30px;padding-left:29px;font-size:12.5px;border-radius:var(--r-ctl);background:var(--surface)}.hf-search input::-webkit-search-cancel-button{filter:invert(.6)}.hf-user{height:30px;max-width:190px;padding:0 8px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-dates{display:flex;align-items:center;gap:6px}.hf-lbl{font-size:10px;letter-spacing:.06em;text-transform:uppercase;color:var(--text-ghost)}.hf-date{width:140px;height:30px;font-size:12.5px;border-radius:var(--r-ctl);background:var(--surface)}.hf-date::-webkit-calendar-picker-indicator{filter:invert(.6);cursor:pointer}.hf-dash{color:var(--text-ghost)}.hf-clear{height:30px;padding:0 10px;border:none;border-radius:var(--r-ctl);background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.hf-clear:hover{color:var(--text);background:var(--hover)}.hf-clear-empty{margin-top:12px}.hf-search input::placeholder{color:var(--text-faint)}.hf-seg{display:inline-flex;padding:2px;gap:2px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface)}.hf-seg button{height:24px;padding:0 10px;border:none;border-radius:5px;background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.hf-seg button:hover{color:var(--text)}.hf-seg button[aria-pressed=true]{background:var(--hover);color:var(--text-bright);font-weight:560}.hf-pick{position:relative;display:inline-flex;align-items:center}.hf-pick .ico{position:absolute;left:8px;width:14px;height:14px;color:var(--text-faint);pointer-events:none}.hf-device,.hf-range{height:30px;max-width:190px;padding:0 8px 0 27px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-chip{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 8px 0 10px;border:1px solid var(--border);border-radius:6px;background:var(--hover);color:var(--text);font:inherit;font-size:12.5px;cursor:pointer}.hf-chip .ico{width:12px;height:12px;color:var(--text-faint)}.hf-chip:hover .ico{color:var(--text)}.hsum{padding:18px 0 6px}.hsum-wait{min-height:150px}.hsum-head{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap}.hsum-total{font-size:21px;font-weight:640;letter-spacing:-.02em;color:var(--text-bright)}.hsum-sub{margin-top:2px;font-size:12.5px;color:var(--text-dim)}.hsum-range{color:var(--text-faint)}.hsum-legend{display:flex;gap:14px;font-size:12px;color:var(--text-dim)}.hsum-legend span:before{content:"";display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:2px;vertical-align:0}.hsum-legend .agent:before{background:var(--viz-agent)}.hsum-legend .human:before{background:var(--viz-human)}.hsum-bars{display:flex;gap:6px;height:104px;margin-top:14px}.hsum-bars.dense{gap:2px}.hsum-col{flex:1;display:flex;flex-direction:column;min-width:0}.hsum-stack{flex:1;display:flex;flex-direction:column-reverse;justify-content:flex-start;border-bottom:1px solid var(--border)}.hsum-stack span{display:block;min-height:0}.hsum-stack .agent{background:var(--viz-agent);border-radius:0 0 2px 2px}.hsum-stack .human{background:var(--viz-human);border-radius:3px 3px 0 0}.hsum-col.today .hsum-stack .agent{background:var(--accent)}.hsum-day{margin-top:5px;text-align:center;font-size:11px;color:var(--text-faint);white-space:nowrap}.hsum-col.today .hsum-day{color:var(--text-bright);font-weight:600}.hday{display:flex;align-items:center;gap:6px;margin:18px 0 6px;font-size:13px;color:var(--text-faint)}.hday b{color:var(--text-bright);font-weight:600}.hday:after{content:"";flex:1;height:1px;margin-left:6px;background:var(--border)}.hentry.sel{background:var(--glow);box-shadow:inset 2px 0 0 var(--accent)}.hentry.delete .hpath{text-decoration:line-through;color:var(--danger-ink)}.hgone{color:var(--text-faint)}.hstat{display:inline-flex;gap:6px;flex:none;font-family:var(--mono);font-size:11.5px;font-variant-numeric:tabular-nums}.hstat .dv-add,.hstat .dv-del{font-weight:500}.hsel-btn{flex:none;height:22px;padding:0 8px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hsel-btn{margin-left:auto}.hsel-btn:hover,.hsel-btn[aria-pressed=true]{color:var(--text);background:var(--hover);border-color:var(--border-2)}.hresolve-btn.pbtn{height:22px;padding:0 10px;font-size:12px}.havatar{display:grid;place-items:center;flex:none;width:26px;height:26px;border-radius:50%;background:var(--glow);color:var(--accent-ink)}.havatar .ico{width:14px;height:14px}.hrun-title{flex:1;display:flex;flex-direction:column;min-width:0;gap:2px}.hrun-sub{display:flex;gap:6px;min-width:0;font-size:12px;color:var(--text-faint)}.hrun-sub .hrun-meta:before{content:"· "}.hrun-what{color:var(--text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.hrun-what b{color:var(--text-bright);font-weight:600}.hrun-title .hrun-note{flex-shrink:1;min-width:0;max-width:50%;font-weight:400;color:var(--text-faint)}.hempty{display:flex;flex-direction:column;align-items:center;gap:10px;padding:48px 16px;text-align:center}.hempty b{color:var(--text-bright);font-size:15px;font-weight:600}.hempty-icon{display:grid;place-items:center;width:44px;height:44px;border-radius:var(--r-card);background:var(--hover);color:var(--text-dim)}.hempty-icon .ico{width:20px;height:20px}.herror-icon{background:#f26d6d1f;color:var(--del)}.hchips{display:flex;flex-wrap:wrap;justify-content:center;gap:6px}.hempty-hint{max-width:46ch;font-size:13px;color:var(--text-dim)}.hempty-actions{display:flex;gap:8px;margin-top:4px}.hempty-actions .hf-clear-empty{margin-top:0}.hskel-row{display:flex;align-items:center;gap:12px;padding:12px 0}.hskel-dot,.hskel-lines span,.hskel-time{background:var(--hover);border-radius:4px;animation:hskel 1.4s ease-in-out infinite}.hskel-dot{flex:none;width:28px;height:28px;border-radius:50%}.hskel-lines{flex:1;display:flex;flex-direction:column;gap:7px}.hskel-lines span{display:block;height:9px}.hskel-time{flex:none;width:40px;height:9px}.hskel-note{margin-top:10px;font-size:12.5px;color:var(--text-faint)}@keyframes hskel{50%{opacity:.45}}.fskel{display:flex;gap:40px;padding-top:8px}.fskel-main{flex:1;min-width:0;display:flex;flex-direction:column;gap:12px}.fskel-title,.fskel-meta span,.fskel-line,.fskel-rail span{display:block;background:var(--hover);border-radius:4px;animation:hskel 1.4s ease-in-out infinite}.fskel-title{width:55%;height:26px;margin-bottom:4px}.fskel-meta{display:flex;gap:12px;margin-bottom:14px}.fskel-meta span{height:10px}.fskel-line{height:11px}.fskel-rail{flex:none;width:200px;display:flex;flex-direction:column;gap:10px;padding-left:16px;border-left:1px solid var(--border)}.fskel-rail span{height:9px}@media(max-width:1399px){.fskel-rail{display:none}}@media(prefers-reduced-motion:reduce){.hskel-dot,.hskel-lines span,.hskel-time,.fskel-title,.fskel-meta span,.fskel-line,.fskel-rail span{animation:none}}.apanel{position:fixed;z-index:40;top:52px;right:0;bottom:0;width:min(460px,100vw);display:flex;flex-direction:column;border-left:1px solid var(--border);background:var(--bg-side);box-shadow:-10px 0 32px var(--shadow-pop);overflow:hidden}.ap-head{display:flex;align-items:center;gap:6px;padding:14px 14px 4px 16px}.ap-head>.ico{width:16px;height:16px;color:var(--text-dim)}.ap-name{flex:1;min-width:0;font-weight:600;font-size:14.5px;color:var(--text-bright);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ap-nav,.ap-close{display:grid;place-items:center;width:26px;height:26px;border:none;border-radius:6px;background:none;color:var(--text-faint);cursor:pointer}.ap-nav:hover:not(:disabled),.ap-close:hover{background:var(--hover);color:var(--text)}.ap-nav:disabled{opacity:.35;cursor:default}.ap-nav .ico,.ap-close .ico{width:15px;height:15px}.ap-nav:not(.down) .ico{transform:rotate(-90deg)}.ap-path{padding:0 16px;font-family:var(--mono);font-size:12px;color:var(--text-faint);overflow-wrap:anywhere}.ap-who{display:flex;align-items:center;gap:6px;padding:8px 16px 0;font-size:12.5px;color:var(--text-dim)}.ap-who .ico{width:14px;height:14px;color:var(--accent-ink)}.ap-actions{display:flex;flex-wrap:wrap;gap:8px;padding:12px 16px 14px;border-bottom:1px solid var(--border)}.dtabs{display:flex;flex-direction:column;min-height:0;flex:1}.dtabs-bar{display:flex;gap:18px;padding:0 16px;border-bottom:1px solid var(--border)}.dtabs-bar button{padding:10px 0 9px;border:none;border-bottom:2px solid transparent;background:none;color:var(--text-faint);font:inherit;font-size:13px;cursor:pointer}.dtabs-bar button[aria-selected=true]{color:var(--text-bright);border-bottom-color:var(--accent);font-weight:560}.dtabs-body{flex:1;overflow:auto;padding:8px 10px 12px}.dtabs-body .dv{margin:0}.dtabs-md{padding:4px 8px;font-size:13.5px}.dtabs-img{max-width:100%}.ap-foot{padding:9px 16px;border-top:1px solid var(--border);font-size:11.5px;color:var(--text-faint)}@media(max-width:700px){.apanel{top:0}}.apanel-empty{display:none}.activity>.history{max-width:var(--page-app);margin-inline:auto}@media(min-width:1200px){.activity.two-zone{display:grid;grid-template-columns:minmax(0,1fr) 440px;column-gap:32px;align-items:start;margin-right:-40px}.activity.two-zone>.history{min-width:0;max-width:none;margin:0}.activity.two-zone>.apanel,.activity.two-zone>.apanel-empty{position:sticky;z-index:1;top:-44px;margin-top:-44px;right:auto;bottom:auto;width:auto;height:calc(100vh - 52px);box-shadow:none}.apanel-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:32px;border-left:1px solid var(--border);background:var(--bg-side);text-align:center;color:var(--text-dim);font-size:13px}.apanel-empty>.ico{width:22px;height:22px;color:var(--text-faint)}.apanel-empty b{color:var(--text-bright);font-size:14px;font-weight:600}.apanel-empty .ap-keys{margin-top:6px;font-size:11.5px;color:var(--text-faint)}.apanel-empty kbd{padding:1px 5px;border:1px solid var(--border);border-radius:4px;font:inherit;font-size:11px}.activity.two-zone .hf-search{flex:1 1 140px;min-width:120px}.activity.two-zone .hf-seg button{padding:0 8px}.activity.two-zone .hf-device{max-width:150px}}@media(max-width:760px){.hf-search{flex-basis:100%}}.hentry{padding:11px 12px;border-bottom:1px solid var(--border);--hindent: 72px}.hentry:hover{background:var(--row-hover-faint)}.hline{display:flex;gap:10px;align-items:center}.hkind{flex:none;width:62px;white-space:nowrap;text-align:center;font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600;padding:2px 6px;border-radius:4px;color:var(--add);background:#4cc38a1f}.hentry.edit .hkind{color:var(--accent-bright);background:var(--glow)}.hentry.delete .hkind{color:var(--danger-bright);background:#f26d6d1f}.hpath{font-weight:500;cursor:pointer;color:var(--text);font-size:13px}.hpath:hover{color:var(--accent-bright)}.htime{margin-left:auto;color:var(--text-faint);font-size:12px;font-variant-numeric:tabular-nums}.hmore{display:flex;margin:14px auto}.hmore:disabled{opacity:.6;cursor:default}.hmeta{display:flex;align-items:center;gap:14px;margin-top:4px;padding-left:var(--hindent);font-size:12px;color:var(--text-dim)}.hdev,.hsize{color:var(--text-faint)}.hsize{font-variant-numeric:tabular-nums;white-space:nowrap;flex:none}.hnote{margin-top:4px;padding-left:var(--hindent);font-size:12px;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.hnote:hover{color:var(--text)}.hnote.open{white-space:normal;overflow-wrap:anywhere}.hnote:before{content:"›";display:inline-block;margin-right:5px;color:var(--text-ghost);transition:transform .12s}.hnote.open:before{transform:rotate(90deg)}.hnote a{color:var(--accent-bright);text-decoration:none}.hnote a:hover{text-decoration:underline}.hrun{border:1px solid var(--border);border-radius:var(--r-card);background:var(--bg-side);margin:10px 0;overflow:hidden}.hrun-head{display:flex;align-items:center;gap:9px;width:100%;padding:9px 12px;color:var(--text);font-size:12.5px}.hrun-toggle{display:flex;flex:none;padding:2px;border:none;border-radius:4px;background:none;color:var(--text-faint);cursor:pointer}.hrun-toggle:hover{color:var(--text);background:var(--hover)}.hrun-toggle .ico{width:13px;height:13px}.hrun-note{flex-shrink:0;font-weight:560;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:46%}.hrun-note a{color:var(--accent-bright);text-decoration:none}.hrun-note a:hover{text-decoration:underline}.hrun-meta{min-width:0;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hrun-time{margin-left:auto;flex:none;color:var(--text-faint);font-variant-numeric:tabular-nums}.hrun-undo{display:inline-flex;align-items:center;gap:4px;flex:none;padding:2px 8px 2px 5px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hrun-undo:hover{color:var(--del);border-color:#f26d6d61;background:var(--hover)}.hrun-undo:disabled{opacity:.5;cursor:default}.hrun-undo .ico{width:12px;height:12px}.undo-list{margin:10px 0;max-height:40vh;overflow-y:auto;border:1px solid var(--border);border-radius:6px}.undo-row{display:flex;align-items:baseline;gap:10px;padding:5px 9px;font-size:12.5px}.undo-row+.undo-row{border-top:1px solid var(--border)}.undo-row .undo-path{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.undo-row .undo-what{margin-left:auto;flex:none;color:var(--text-faint);font-size:11.5px}.undo-row .undo-after{flex:none;color:var(--del);font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600}.undo-warn{color:var(--del)}.hrun-body{border-top:1px solid var(--border)}.hrun-body .hentry:last-child{border-bottom:none}.hread{flex:none;padding:2px 6px;border-radius:4px;font-size:10px;text-transform:uppercase;letter-spacing:.06em;font-weight:600;color:var(--text-dim);background:var(--hover)}.hrun-reads{border-top:1px solid var(--border);padding:4px 0 6px}.hrun-reads-head{padding:6px 14px 4px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--text-faint)}.hrun-read{display:flex;gap:10px;align-items:center;width:100%;padding:5px 14px;border:none;background:none;font:inherit;text-align:left;cursor:pointer}.hrun-read:hover{background:var(--row-hover-faint)}.hrun-read .hkind{color:var(--text-dim);background:var(--hover)}.hrun-foot{padding:8px 14px 10px;border-top:1px solid var(--border);font-size:11.5px;color:var(--text-faint)}.hrestore-btn,.hremove-btn{display:inline-flex;align-items:center;gap:4px;margin-left:auto;padding:2px 8px 2px 5px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer}.hrestore-btn:hover{color:var(--accent-bright);border-color:var(--border-2);background:var(--hover)}.hremove-btn:hover{color:var(--del);border-color:#f26d6d61;background:var(--hover)}.hrestore-btn:disabled,.hremove-btn:disabled{opacity:.5;cursor:default}.hrestore-btn .ico,.hremove-btn .ico{width:12px;height:12px}.hactions{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:6px 0 0 23px}.hdiff-btn,.hver-btn{display:inline-flex;align-items:center;gap:4px;padding:2px 7px 2px 4px;border:1px solid var(--border);border-radius:5px;background:none;color:var(--text-faint);font:inherit;font-size:12px;cursor:pointer;text-decoration:none}.hdiff-btn:hover,.hver-btn:hover{color:var(--text);border-color:var(--border-2);background:var(--hover)}.hdiff-btn .ico,.hver-btn .ico{width:12px;height:12px}.hdiff-none{flex-basis:100%;font-size:12px;color:var(--text-ghost)}.dv{margin:8px 0 2px 23px;border:1px solid var(--border);border-radius:6px;overflow:hidden}.dv-msg{display:flex;flex-wrap:wrap;align-items:center;gap:12px;padding:9px 11px;font-size:12px;color:var(--text-faint)}.dv-dl{display:flex;gap:12px}.dv-msg a{color:var(--accent-bright);text-decoration:none}.dv-msg a:hover{text-decoration:underline}.dv-head{display:flex;align-items:center;gap:10px;padding:5px 11px;border-bottom:1px solid var(--border);font-size:11px;font-variant-numeric:tabular-nums}.dv-add{color:var(--add);font-weight:600}.dv-del{color:var(--del);font-weight:600}.dv-same{color:var(--text-ghost)}.dv-body{overflow-x:auto;padding:4px 0}.dv-line{display:flex;font-family:var(--mono);font-size:12px;line-height:1.55;white-space:pre}.dv-n{flex:none;width:34px;padding-right:8px;text-align:right;color:var(--text-ghost);-webkit-user-select:none;user-select:none;font-variant-numeric:tabular-nums}.dv-mark{flex:none;width:16px;text-align:center;-webkit-user-select:none;user-select:none}.dv-text{padding-right:12px}.dv-ins{background:#4cc38a1a;color:var(--add)}.dv-rm{background:#f26d6d1a;color:var(--danger-bright)}.dv-ctx{color:var(--text-dim)}#palette{position:fixed;top:12vh;left:50%;transform:translate(-50%);z-index:151;display:block;width:min(560px,92vw);background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-over);box-shadow:0 24px 70px -18px #000c;overflow:hidden;outline:none;padding:0}:root[data-theme=light] #palette{box-shadow:0 24px 70px -18px #00000040}#palette-inputwrap{display:flex;align-items:center;gap:11px;padding:14px 16px;border-bottom:1px solid var(--border)}#palette-inputwrap [data-slot=command-input-wrapper]{flex:1;display:flex;border-bottom:0;padding:0;height:auto}#palette-inputwrap [data-slot=command-input-wrapper]>svg:not(.ico){display:none}#palette input,#palette input:focus{flex:1;width:100%;border:none;background:transparent;box-shadow:none;color:var(--text);font:inherit;font-size:15px;letter-spacing:-.01em;outline:none;padding:0}#palette input::placeholder{color:var(--text-ghost)}#palette-inputwrap .ico{width:17px;height:17px;color:var(--text-faint)}#palette [cmdk-list]{list-style:none;margin:0;padding:8px;max-height:46vh;overflow-y:auto}#palette [cmdk-item]{display:flex;align-items:center;gap:11px;height:38px;padding:0 10px;border-radius:9px;cursor:pointer;color:var(--text-dim);font-size:13.5px}#palette [cmdk-item][data-selected=true]{background:var(--glow)}#palette [cmdk-item][data-selected=true] .picon{color:var(--accent-ink)}#palette [cmdk-item][data-selected=true] .plabel,#palette [cmdk-item][data-selected=true] .plabel b{color:var(--accent-bright)}#palette [cmdk-item] .picon{width:18px;flex:none;display:flex;justify-content:center;color:var(--text-faint)}#palette [cmdk-item] .picon .ico{width:15px;height:15px}#palette [cmdk-item] .ptext{flex:1;min-width:0;display:flex;align-items:baseline;gap:8px;overflow:hidden}#palette [cmdk-item] .plabel{flex:0 1 auto;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--text)}#palette [cmdk-item] .ploc{flex:1 1 0%;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px;color:var(--text-faint)}#palette [cmdk-item] .ploc b{color:var(--text-dim);font-weight:600}#palette [cmdk-item] .plabel b{color:var(--accent-bright);font-weight:600}#palette [cmdk-group-heading]{padding:10px 10px 5px;font-size:11.5px;font-weight:500;color:var(--text-faint)}#palette [cmdk-group]:first-child [cmdk-group-heading]{padding-top:4px}#palette [cmdk-item] .pkind{flex:none;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--text-ghost)}#palette [cmdk-list] .pempty{color:var(--text-faint);cursor:default;justify-content:center;height:auto;padding:14px}#palette-hint{padding:9px 16px;border-top:1px solid var(--border);font-size:11px;color:var(--text-ghost)}[data-slot=dialog-overlay]{position:fixed;inset:0;background:#06070999;-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px);z-index:150}:root[data-theme=light] [data-slot=dialog-overlay]{background:#0f111559}.modal{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:151;display:block;background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-over);padding:22px 24px;width:min(460px,calc(100vw - 40px));box-shadow:0 24px 70px -18px #000c;outline:none}:root[data-theme=light] .modal{box-shadow:0 24px 70px -18px #00000040}.modal h3{margin:0 0 10px;font-size:16px;font-weight:620;letter-spacing:-.01em}.modal p{margin:0 0 16px;font-size:13.5px;color:var(--text-dim);line-height:1.55}.modal p b{color:var(--text)}.modal-url{font:12px var(--mono);background:var(--surface);border:1px solid var(--border);border-radius:var(--r-ctl);padding:9px 11px;color:var(--text-dim);word-break:break-all;margin-bottom:16px}.modal-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.modal-expiry{display:flex;align-items:center;gap:8px;margin-bottom:16px;font-size:12.5px;color:var(--text-dim)}.modal-expiry select{height:28px;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:0 8px;font:inherit;font-size:12.5px;cursor:pointer}.modal-expiry select:disabled{opacity:.6;cursor:default}.modal-expiry-note{margin-left:auto;color:var(--text-dim)}.modal-label{display:block;font-size:12.5px;color:var(--text-dim);margin:0 0 6px}.modal-msg{margin:0 0 16px;font-size:13.5px;color:var(--text-dim);line-height:1.55}.modal-input{width:100%;height:36px;padding:0 12px;border-radius:var(--r-ctl);border:1px solid var(--border);background:var(--surface);color:var(--text);font:inherit;font-size:14px;margin-bottom:16px;outline:none}.modal-input:focus{border-color:var(--accent);background:var(--hover)}.start-points{border:0;margin:0 0 18px;padding:0}.start-points legend{padding:0}.start-point{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface);cursor:pointer;margin-bottom:6px}.start-point:hover{background:var(--hover)}.start-point.on{border-color:var(--accent);background:var(--hover)}.start-point input{accent-color:var(--accent);margin:2px 0 0;flex:none}.sp-text{display:flex;flex-direction:column;gap:2px;min-width:0}.sp-title{font-size:13.5px;color:var(--text);display:flex;align-items:center;gap:8px}.sp-rec{font-size:10.5px;letter-spacing:.02em;text-transform:uppercase;color:var(--accent-ink);border:1px solid var(--accent);border-radius:999px;padding:0 6px;line-height:15px}.sp-blurb{font-size:12px;color:var(--text-dim);overflow-wrap:anywhere}.start-point.sp-rule{margin-top:16px}.modal{max-height:calc(100vh - 32px);overflow-y:auto}.gd-note{margin:-4px 0 16px;font-size:13px;color:var(--text-dim);border-left:2px solid var(--accent);padding-left:11px;line-height:1.55}[data-sonner-toast]{background:var(--bg-raise)!important;color:var(--text)!important;border:1px solid var(--border-2)!important;border-radius:10px!important;font-size:13.5px!important;box-shadow:0 18px 44px -12px #000000b3!important}[data-sonner-toast][data-type=error]{border-color:#f26d6d80!important;color:#ffb0aa!important}:root[data-theme=light] [data-sonner-toast]{box-shadow:0 18px 44px -12px #0000002e!important}:root[data-theme=light] [data-sonner-toast][data-type=error]{color:var(--danger-bright)!important}#sb-backdrop{display:none}@media(max-width:900px){#sidebar{width:256px;max-width:calc(100vw - 48px)}#sidebar{position:fixed;z-index:60;top:0;left:0;height:100%;transform:translate(-100%);transition:transform .2s ease;box-shadow:0 0 40px #0009}body.sb-open #sidebar{transform:translate(0)}body.sb-open #sb-backdrop{display:block;position:fixed;inset:0;background:#0000008c;z-index:50}:root[data-theme=light] #sidebar{box-shadow:0 0 40px #0000002e}:root[data-theme=light] body.sb-open #sb-backdrop{background:#0f111559}.icon-btn{display:inline-flex;width:44px;height:44px}#sb-search .sb-kbd{display:none}#content{--content-pad-b: 70px;padding:24px 18px var(--content-pad-b)}#topbar{padding:0 8px;gap:4px}.btn .lbl{display:none}#topbar .btn{min-width:44px;min-height:44px;padding:0;justify-content:center;gap:0}#topbar .btn .ico{width:18px;height:18px}#more-btn:not([hidden]){display:inline-flex}#history-btn,#upload-btn,#download{display:none!important}#topbar{flex-wrap:wrap;height:auto;min-height:52px}#meta{order:1;flex:1 1 100%;text-align:left;white-space:normal;overflow:visible;padding:0 0 8px}#meta:empty{display:none}#crumb{flex:1}#vault{padding:0 8px 0 12px}#signout,#tree .row,#projects .row,#pinned .row,.sb-sync,#sb-search,.sb-menu [role=menuitem],.sb-theme{height:44px}#account-btn{min-height:44px}#project-select{height:44px}.markdown table,pre.plain{display:block;overflow-x:auto;max-width:100%}.admin-item{flex-wrap:wrap;row-gap:8px;padding:12px 14px}.admin-item select,.hf-search input,.hf-user,.hf-date,.hf-clear{height:44px}.hf-dates{flex:1 1 100%}.hf-date{flex:1;width:auto;min-width:0}.hrun-head{flex-wrap:wrap;row-gap:4px}.hrun-note{flex-shrink:1;max-width:none;white-space:normal;overflow:visible}.hrun-meta{order:1;flex:1 1 100%;white-space:normal;overflow:visible}.hrun-sub{flex-wrap:wrap}.hrun-title .hrun-note{max-width:none}.hrun-sub .hrun-meta:before{content:none}.hrun-what{white-space:normal}.hf-device,.hf-range,.hf-seg button{height:44px}.hrun-undo{order:2;margin-left:auto;min-height:32px}.ai-btn,.ai-del{height:auto;min-height:44px;padding:0 12px}.admin-table thead{display:none}.admin-table,.admin-table tbody,.admin-table td{display:block;width:auto}.admin-table tr.admin-item{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.admin-table tr.admin-item td{padding:0;border-bottom:none}.admin-table tr.admin-item td:first-child{flex:1 1 100%;width:auto}.admin-table tr.admin-item td:last-child{width:auto;text-align:left}[data-slot=dropdown-menu-item]{min-height:44px}#projects{flex:0 1 auto;max-height:none}.admin-row{flex-wrap:wrap}.admin-row input{flex:1 1 100%;min-height:44px}.admin-row button{flex:0 0 auto;align-self:flex-start;min-height:44px}.admin-item .ai-main{flex:1 1 100%;white-space:normal;overflow-wrap:anywhere}.admin-table td{white-space:normal}.admin-table td .ai-main,.admin-table td a.ai-main,.admin-table td .ai-copy,.admin-table td .ai-tag{white-space:normal;overflow-wrap:anywhere}.admin-item .ai-tag{flex:1 1 100%;max-width:100%;white-space:normal;overflow-wrap:anywhere}.ai-copy{min-height:44px;display:block;padding:12px 0;white-space:normal;overflow-wrap:anywhere;text-overflow:clip}a.ai-main{min-height:44px;display:flex;align-items:center}.gd-code{min-height:62px;padding-top:12px;padding-bottom:12px}.gd-copy{min-height:44px;padding:0 14px}.gd-tab{min-height:44px}.in-lens-btn{min-height:44px;padding:0 14px}.modal-input{height:44px}.modal-actions button{height:auto;min-height:44px}.modal-expiry select{height:44px}.pbtn,#palette [cmdk-item]{height:auto;min-height:44px}.more-item{min-height:44px}}.modal-actions .ai-del{margin-right:auto}@media(max-width:430px){.dl-row{flex-wrap:wrap;row-gap:2px}.dl-meta{flex:1 1 100%;padding-left:27px}.ai-tag{font-size:11px}.htime{white-space:nowrap;font-size:12px}.hline{flex-wrap:wrap}.hentry{--hindent: 0px}.modal-actions .ai-del{flex:0 0 100%;justify-content:center;text-align:center}}.markdown h1,.markdown h2,.markdown h3,.markdown h4{color:var(--text-bright);line-height:1.25;letter-spacing:-.018em;margin:1.5em 0 .5em;text-wrap:balance}.markdown h1:first-child{margin-top:0}.markdown h1{font-size:1.85em;font-weight:660;letter-spacing:-.024em}.markdown h2{font-size:1.32em;font-weight:620;margin-top:1.7em}.markdown h3{font-size:1.08em;font-weight:620}.markdown p,.markdown li{color:var(--text-body);font-size:14.5px;line-height:1.72}.markdown p{margin:0 0 1em}.markdown strong{color:var(--text);font-weight:620}.markdown a{color:var(--accent-bright);text-decoration:none;border-bottom:1px solid rgba(245,166,35,.28)}.markdown a:hover{border-bottom-color:var(--accent)}.markdown a.wiki-missing{color:var(--text-faint);border-bottom:none;text-decoration:underline dotted;cursor:help}.markdown ul,.markdown ol{margin:0 0 1em;padding-left:1.4em}.markdown li{margin-bottom:.4em}.markdown li::marker{color:var(--text-ghost)}.markdown code{background:var(--hover);border:1px solid var(--border);padding:.1em .4em;border-radius:5px;font:12.5px/1.5 var(--mono);color:var(--code-ink)}.markdown pre{background:var(--code-bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;overflow-x:auto;margin:1.3em 0}.markdown pre code{background:none;border:none;padding:0;color:var(--text-body)}.markdown blockquote{margin:1.3em 0;padding:.3em 1em;border-left:2px solid var(--accent);background:linear-gradient(90deg,var(--glow),transparent);border-radius:0 8px 8px 0;color:var(--quote-ink)}.markdown blockquote p{margin:.3em 0;color:var(--quote-ink)}.markdown table{border-collapse:collapse;margin:1.3em 0;font-size:13.5px}.markdown th,.markdown td{border-bottom:1px solid var(--border);padding:9px 13px;text-align:left}.markdown th{color:var(--text-faint);font-size:11px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;border-bottom-color:var(--border-2)}.markdown tr:hover td{background:var(--row-hover)}.markdown img{max-width:100%;border-radius:8px;border:1px solid var(--border)}.markdown hr{border:none;border-top:1px solid var(--border);margin:2.2em 0}.markdown .mermaid-diagram{margin:1.3em 0;overflow-x:auto}.markdown .mermaid-diagram svg{max-width:100%;height:auto}.markdown .mermaid-err{margin:-.9em 0 .4em;font-size:12px;color:var(--text-faint)}.markdown .mermaid-err-detail{margin:0 0 1.3em;font:11.5px/1.5 var(--mono);color:var(--text-faint);white-space:pre;overflow:auto;max-height:12em}.fv-head{margin:0 0 22px}.fv-chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}.fv-chip{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 8px;border-radius:6px;background:var(--hover);color:var(--text-dim);font-size:11.5px;font-weight:500;white-space:nowrap}.fv-chip .ico{width:12px;height:12px}.fv-chip.accent{background:var(--glow);color:var(--accent-ink)}.fv-meta{display:flex;flex-wrap:wrap;align-items:center;gap:6px 16px;font-size:12.5px;color:var(--text-faint)}.fv-meta>span{display:inline-flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere}.fv-meta .ico{width:13px;height:13px;flex:none}.fv-who{color:var(--text-dim)}.fv-avatar{display:inline-flex;align-items:center;justify-content:center;flex:none;width:20px;height:20px;border-radius:50%;background:var(--viz-human);color:var(--bg);font-size:10.5px;font-weight:650}.fv-rail{font-size:12.5px}.fv-sec .fv-sec-h{display:flex;align-items:baseline;margin:0 0 10px;color:var(--text-faint);font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.07em}.fv-rail .fv-sec-link{border-bottom:none;margin-left:auto;text-transform:none;letter-spacing:0;font-size:12px;font-weight:500;color:var(--accent-ink);text-decoration:none}.fv-rail .fv-sec-link:hover{color:var(--accent-bright)}.fv-rail-in{display:flex;flex-direction:column;gap:28px}.fv-rail .fv-toc ul{list-style:none;margin:0;padding:0;border-left:1px solid var(--border)}.fv-rail .fv-toc li{margin:0;font-size:12.5px;color:inherit}.fv-rail .fv-toc li a{border-bottom:none;display:block;margin-left:-1px;padding:4px 0 4px 14px;border-left:2px solid transparent;color:var(--text-dim);text-decoration:none;line-height:1.35;overflow-wrap:anywhere}.fv-rail .fv-toc li.sub a{padding-left:26px;font-size:12px;color:var(--text-faint)}.fv-rail .fv-toc li a:hover{color:var(--text)}.fv-rail .fv-toc li.on a{border-left-color:var(--accent);color:var(--accent-ink)}.fv-big{font-size:28px;font-weight:650;color:var(--text-bright);letter-spacing:-.02em;line-height:1;margin-bottom:12px;font-variant-numeric:tabular-nums}.fv-split{display:flex;gap:2px;height:6px;border-radius:3px;overflow:hidden}.fv-split-agent{background:var(--viz-agent)}.fv-split-human{background:var(--viz-human)}.fv-split-share{background:var(--viz-share)}.fv-legend{display:flex;flex-wrap:wrap;justify-content:space-between;gap:4px 12px;margin-top:8px;color:var(--text-dim)}.fv-sw{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:3px}.fv-rail .fv-readnote{margin:8px 0 0;color:var(--text-faint);font-size:12px}.fv-rail .fv-props dl{margin:0}.fv-rail .fv-props dl>div{display:flex;gap:10px;padding:4px 0}.fv-rail .fv-props dt{flex:0 0 96px;min-width:0;color:var(--text-faint);font:11.5px/1.6 var(--mono);overflow-wrap:anywhere}.fv-rail .fv-props dd{margin:0;min-width:0;color:var(--text-body);overflow-wrap:anywhere}.fv-rail .fv-props code{white-space:pre-wrap;font:11px/1.5 var(--mono);color:var(--code-ink)}.fv-rail.narrow{margin:0 0 22px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card)}.fv-rail.narrow>summary{list-style:none;cursor:pointer;padding:8px 12px;color:var(--text-faint);font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:6px;-webkit-user-select:none;user-select:none}.fv-rail.narrow>summary::-webkit-details-marker{display:none}.fv-rail.narrow>summary:before{content:"";border:4px solid transparent;border-left-color:currentColor;transition:transform .12s ease}.fv-rail.narrow[open]>summary:before{transform:rotate(90deg) translate(-1px)}.fv-rail.narrow>summary:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;border-radius:var(--r-card)}.fv-rail.narrow .fv-rail-in{padding:6px 12px 14px;gap:20px;border-top:1px solid var(--border)}@media(min-width:1400px){.page.read:has(>aside.fv-rail){max-width:min(var(--page-read),calc(100% - 300px));margin-left:max(0px,calc((100% - var(--page-read) - 300px) / 2));margin-right:auto}aside.fv-rail{position:absolute;top:0;bottom:0;left:calc(100% + 40px);width:260px}.page.read:has(>aside.fv-rail) .fv-prose table,.page.read:has(>aside.fv-rail) .fv-prose pre{display:block;overflow-x:auto;max-width:100%}aside.fv-rail .fv-rail-in{position:sticky;top:0;max-height:calc(100vh - 140px);overflow-y:auto;padding-left:20px;border-left:1px solid var(--border)}}.markdown .admin input:focus-visible{outline:2px solid var(--accent);outline-offset:1px}.admin input[aria-invalid=true]:focus-visible{outline-color:var(--del)}[role=dialog] input[aria-invalid=true]{border-color:var(--del)}[role=dialog] input[aria-invalid=true]:focus-visible{outline-color:var(--del)}button:disabled,.btn:disabled{cursor:default}input[type=checkbox]{accent-color:var(--accent)}.htmlview,.pdfview{display:block;width:100%;height:calc(100vh - 150px);border:1px solid var(--border);border-radius:var(--r-card);background:#fff}.notfound{margin-top:var(--hero-top);text-align:center;color:var(--text-dim)}.notfound h1{color:var(--text);font-size:1.4em;margin-bottom:.5em}.notfound code{background:var(--hover);border:1px solid var(--border);padding:.15em .5em;border-radius:6px}.notfound .nf-sub{max-width:440px;margin:12px auto 20px;font-size:13px;color:var(--text-faint);line-height:1.6}.vbanner{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:0 0 22px;padding:11px 14px;border:1px solid var(--accent-dim);border-radius:var(--r-card);background:var(--glow)}.vbanner .vb-icon{flex:none;display:flex;color:var(--accent-bright)}.vbanner .vb-text{flex:1 1 220px;min-width:0;display:flex;flex-direction:column;gap:1px;font-size:12.5px;line-height:1.45}.vbanner .vb-text b{color:var(--accent-bright);font-weight:600}.vbanner .vb-text span{color:var(--text-dim)}.vbanner .vb-actions{flex:none;display:flex;gap:8px}.vbanner .vb-actions .ai-btn{display:inline-flex;align-items:center;text-decoration:none}.sbadge{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:0 0 22px;padding:11px 14px;border:1px solid rgba(242,109,109,.32);border-radius:var(--r-card);background:#f26d6d14}.sbadge .sb-icon{flex:none;display:flex;color:var(--danger-ink)}.sbadge .sb-text{flex:1 1 220px;min-width:0;display:flex;flex-direction:column;gap:1px;font-size:12.5px;line-height:1.45}.sbadge .sb-text b{color:var(--danger-ink);font-weight:600}.sbadge .sb-text span{color:var(--text-dim)}pre.plain{background:var(--code-bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;overflow-x:auto;font:12.5px/1.6 var(--mono);color:var(--text-body);white-space:pre-wrap;overflow-wrap:anywhere}.csvbox{overflow-x:auto;width:fit-content;max-width:100%;border:1px solid var(--border);border-radius:var(--r-card);background:var(--code-bg)}.csvbox .csvview{display:table;max-width:none;overflow:visible;margin:0;border-collapse:collapse;font:12.5px/1.5 var(--mono);font-variant-numeric:tabular-nums}.csvbox .csvview th,.csvbox .csvview td{border-bottom:1px solid var(--border);padding:8px 14px;text-align:left;white-space:pre;vertical-align:top;color:var(--text-body);font-size:12.5px}.csvbox .csvview th{background:var(--surface);color:var(--text-faint);font-size:11px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;border-bottom-color:var(--border-2)}.csvbox .csvview tr:last-child td{border-bottom:none}.csvbox .csvview tbody tr:hover td{background:var(--row-hover)}.csvnote{color:var(--text-faint);font-size:12px;margin:10px 2px 0}.filecard{margin-top:var(--hero-top);text-align:center;color:var(--text-dim)}.filecard .name{font-size:1.2em;color:var(--text);margin-bottom:.3em}.filecard .btn{margin-top:14px}body.full-view #sidebar,body.full-view #topbar,body.full-view #sb-backdrop{display:none}body.full-view #content{padding-top:58px}body.full-view .page.bleed{max-width:none}body.full-view #content:has(.page.bleed){padding:58px 14px 14px}body.full-view .htmlview,body.full-view .pdfview{height:calc(100vh - 72px)}#exit-full{position:fixed;z-index:80;top:12px;right:16px;display:inline-flex;align-items:center;gap:7px;height:32px;padding:0 11px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text);font-size:12.5px;font-family:inherit;cursor:pointer;box-shadow:0 8px 24px -8px #000000b3}:root[data-theme=light] #exit-full{box-shadow:0 8px 24px -8px #0000002e}#exit-full:hover{background:var(--hover);border-color:var(--accent)}#exit-full kbd{font:inherit;font-size:10.5px;color:var(--text-faint);border:1px solid var(--border-2);border-radius:4px;padding:1px 4px}@media(max-width:900px){#exit-full{top:8px;right:8px;height:40px}#exit-full .lbl{display:none}}.modal-wide{width:min(600px,calc(100vw - 40px))}.sd-head{font-size:12.5px;font-weight:600;color:var(--text-dim);margin:18px 0 8px;letter-spacing:.01em}.sd-head:first-of-type{margin-top:4px}.modal .admin-list{max-height:220px;overflow-y:auto}.sd-avatar{width:22px;height:22px;flex:none;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10.5px;font-weight:700}.sd-add{gap:8px}.sd-add-input{flex:1;min-width:0;height:28px;padding:0 9px;background:var(--surface);border:1px solid var(--border);border-radius:6px;color:var(--text);font:inherit;font-size:12.5px}.sd-warn{margin:14px 0 6px;font-size:13.5px;color:var(--text)}.modal .ps-row{margin-bottom:10px}.modal .ps-note{margin-bottom:12px}@media(max-width:640px){.sd-add{flex-wrap:wrap}.sd-add-input{flex:0 0 100%;height:44px}}.setup{max-width:760px;margin:var(--hero-top) auto 0}.setup-welcome{text-align:left}.setup-foot{color:var(--text-ghost);font-size:12px;margin:10px 0 0}.setup-connect header h2{font-size:20px;font-weight:640;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright);display:flex;align-items:center;gap:8px}.setup-badge{background:var(--glow);border:1px solid rgba(245,166,35,.4);color:var(--accent-bright);font-size:10px;font-weight:600;border-radius:999px;padding:2px 8px;letter-spacing:.04em}.setup-connect header p{color:var(--text-dim);font-size:13px;margin:0 0 18px}.setup-why{color:var(--text-dim);font-size:12.5px;line-height:1.6;margin:0 0 18px;padding-left:18px}.setup-body{display:flex;gap:22px;align-items:flex-start}.setup-form{flex:1;display:flex;flex-direction:column;gap:14px;min-width:0}.setup-field{display:flex;flex-direction:column;gap:6px}.setup-field>span{color:var(--text-dim);font-size:12px}.setup-field input,.setup-root input{background:var(--bg);border:1px solid var(--border-2);border-radius:var(--r-ctl);padding:9px 12px;color:var(--text);font-size:13.5px;font-family:var(--mono);width:100%;box-sizing:border-box}.setup-field input:focus,.setup-root input:focus{outline:none;border-color:var(--accent)}.setup-root{display:flex;gap:8px}.setup-root button{background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-ctl);color:var(--text);font-size:13px;padding:0 14px;cursor:pointer;white-space:nowrap}.setup-root button:hover{background:var(--hover)}.setup-toggle{display:flex;align-items:center;gap:8px;color:var(--text);font-size:13px}.setup-ok{color:var(--add);font-size:12.5px;margin:0}.setup-err{color:var(--del);font-size:12.5px;margin:0}.setup-warn{color:var(--accent-bright);font-size:12.5px;line-height:1.5;display:flex;flex-direction:column;gap:6px}.setup-warn p{margin:0}.setup-helper{color:var(--text-dim);display:flex;flex-wrap:wrap;align-items:center;gap:6px}.setup-helper code{font-family:var(--mono);font-size:11.5px;color:var(--text);background:var(--surface);border:1px solid var(--border);border-radius:5px;padding:2px 6px;word-break:break-all}.setup-helper button{font:inherit;font-size:11.5px;color:var(--accent-ink);background:none;border:1px solid var(--border-2);border-radius:5px;padding:2px 8px;cursor:pointer}.setup-helper button:hover{background:var(--hover)}.setup-tree{width:290px;flex:none;background:var(--bg);border:1px solid var(--border);border-radius:var(--r-card);padding:14px 16px;font-family:var(--mono);font-size:12px}.setup-tree-head{font-family:inherit;color:var(--text-ghost);font-size:10.5px;letter-spacing:.06em;margin-bottom:8px}.setup-tree-root{color:var(--text)}.setup-dim{color:var(--text-dim)}.setup-tree-shared{color:var(--accent-bright);background:var(--glow);border:1px solid rgba(245,166,35,.4);border-radius:5px;padding:2px 6px;margin:3px 0;display:inline-block}.setup-shared-tag{color:var(--accent-ink);font-size:10px}.setup-tree-foot{color:var(--text-ghost);font-size:10.5px;line-height:1.5;margin:10px 0 0;font-family:-apple-system,BlinkMacSystemFont,SF Pro Text,sans-serif}.setup-syncing h2,.setup-done h2{font-size:20px;font-weight:640;margin:0 0 10px;color:var(--text-bright)}.setup-bar{height:8px;border-radius:4px;background:var(--hover);overflow:hidden;margin:14px 0}.setup-bar>div{height:100%;background:linear-gradient(90deg,var(--accent-dim),var(--accent));border-radius:4px;transition:width .3s ease}.setup-log{list-style:none;padding:0;margin:0 0 14px;font-family:var(--mono);font-size:12px;color:var(--text-ghost);display:flex;flex-direction:column;gap:5px}.setup-log li.ok{color:var(--add)}.setup-log li.ok:before{content:"✓ "}.setup-cards{display:flex;gap:12px;margin-top:18px;align-items:stretch}.setup-card{flex:1;background:var(--bg-raise);padding:16px;display:flex;flex-direction:column;gap:8px;min-width:0}.setup-card-lead{flex:1.4;border-color:#f5a62366;box-shadow:0 0 0 3px var(--glow)}.setup-card h3{font-size:14px;font-weight:600;margin:0;color:var(--text)}.setup-card p{color:var(--text-dim);font-size:12px;line-height:1.5;margin:0;flex:1}@media(max-width:720px){.setup-body,.setup-cards{flex-direction:column}.setup-tree{width:100%}}.cm-host{height:100%}.cm-preview{margin:0;padding:12px 2px 0 6px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--text);font:13px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace}.cm-preview.cm-mode-write{font-family:var(--ui);font-size:15px;line-height:1.75}.cm-host .cm-editor{height:100%;background:transparent;color:var(--text)}.cm-host .cm-editor.cm-focused{outline:none}.cm-host .cm-scroller{font:13px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace;padding:8px 0 40vh}.cm-host .cm-gutters{background:transparent;border-right:1px solid var(--line);color:var(--text-faint)}.cm-host .cm-activeLine{background:color-mix(in srgb,var(--accent) 6%,transparent)}.cm-host .cm-activeLineGutter{background:transparent;color:var(--text)}.cm-host .cm-content{caret-color:var(--text)}.cm-host .cm-cursor{border-left-color:var(--text)}.cm-host .cm-selectionBackground,.cm-host .cm-content ::selection{background:color-mix(in srgb,var(--accent) 26%,transparent)}#editor-state{color:var(--text-faint)}#editor-state[data-state=saving]{color:var(--accent-ink)}#editor-state[data-state=error]{color:var(--del)}#peer-wrote{margin:0 0 10px;padding:8px 12px;border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:6px;color:var(--text-dim);font-size:13px}.cm-host .cm-ySelection{opacity:.35}.cm-host .cm-ySelectionCaret{position:relative;border-left:1px solid currentColor;border-right:1px solid currentColor;margin-left:-1px;margin-right:-1px;box-sizing:border-box}.cm-host .cm-ySelectionInfo{position:absolute;top:-1.05em;left:-1px;font-size:11px;line-height:1.4;padding:0 4px;border-radius:3px 3px 3px 0;color:#fff;white-space:nowrap;opacity:0;transition:opacity .12s;pointer-events:none;-webkit-user-select:none;user-select:none}.cm-host .cm-ySelectionCaret:hover .cm-ySelectionInfo{opacity:1}::highlight(bd-comment){background-color:#f5a6233d}::highlight(bd-comment-active){background-color:#f5a6238c}.cm-pin{position:absolute;z-index:6;transform:translateY(-50%) translateY(calc(var(--k, 0) * 22px));min-width:20px;height:20px;padding:0 5px;border:none;border-radius:10px 10px 10px 2px;background:var(--accent);color:#241704;font:600 11px/20px var(--ui);cursor:pointer;box-shadow:0 2px 6px #00000059}.cm-pin.active{outline:2px solid var(--text);outline-offset:1px}.cm-float{position:fixed;z-index:90;display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border-radius:15px;border:1px solid var(--border-2);background:var(--bg-raise);color:var(--text);font:500 12.5px var(--ui);cursor:pointer;box-shadow:0 8px 24px -8px #0009}.cm-float:hover{border-color:var(--accent)}.cm-float .ico{width:14px;height:14px;color:var(--accent)}.cm-compose{position:fixed;z-index:90;width:320px;padding:10px;border-radius:var(--r-card);background:var(--bg-raise);border:1px solid var(--border-2);box-shadow:0 18px 44px -14px #000000bf}:root[data-theme=light] .cm-compose,:root[data-theme=light] .cm-float{box-shadow:0 18px 44px -14px #0003}.cm-compose textarea,.cm-panel textarea{display:block;width:100%;min-height:64px;resize:vertical;box-sizing:border-box;padding:7px 9px;border-radius:var(--r-ctl);border:1px solid var(--border-2);background:var(--surface);color:var(--text);font:13px/1.45 var(--ui)}.cm-compose textarea:focus-visible,.cm-panel textarea:focus-visible{outline:2px solid var(--accent);outline-offset:-1px}.cm-row{display:flex;align-items:center;justify-content:flex-end;gap:6px;margin-top:8px}.cm-spacer{flex:1}.cm-quote{margin:0 0 8px;padding:2px 0 2px 8px;border-left:2px solid var(--accent);color:var(--text-dim);font-size:12.5px;line-height:1.4;overflow-wrap:anywhere}.cm-quote.cm-el{font-family:var(--mono);font-size:11.5px}.cm-anchor{flex:1;min-width:0}.cm-anchor .cm-quote{max-height:7.5em;overflow-y:auto;white-space:pre-wrap}.cm-anchor .cm-quote+.cm-quote{margin-top:-4px}.cm-q{color:var(--text)}.cm-ctx{color:var(--text-faint)}#comments-btn .cm-count{margin-left:2px;font-size:12px;font-weight:600;color:var(--accent)}#comments-btn[aria-pressed=true]{background:var(--hover);color:var(--text)}.cm-panel{position:fixed;z-index:70;top:53px;right:0;bottom:0;width:360px;max-width:100vw;display:flex;flex-direction:column;background:var(--bg-side);border-left:1px solid var(--border)}body.full-view .cm-panel{top:0}@media(min-width:1200px){body:has(.cm-panel) #content{padding-right:400px}}.cm-head{display:flex;align-items:center;gap:10px;height:46px;padding:0 8px 0 14px;border-bottom:1px solid var(--border);flex:none}.cm-head>b{font-size:13.5px}.cm-tabs{display:flex;gap:2px;flex:1}.cm-tabs button{height:26px;padding:0 9px;border:none;border-radius:6px;background:transparent;color:var(--text-faint);font:500 12px var(--ui);cursor:pointer}.cm-tabs button[aria-selected=true]{background:var(--hover);color:var(--text)}.cm-tabs button span{margin-left:3px;color:var(--accent)}.cm-x{width:30px;height:30px;border:none;border-radius:7px;background:transparent;color:var(--text-dim);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.cm-x:hover{background:var(--hover);color:var(--text)}.cm-x .ico{width:16px;height:16px}.cm-pickbar{padding:8px 12px;border-bottom:1px solid var(--border);flex:none}.cm-pickbar .btn{width:100%;justify-content:center}.cm-pickbar .btn[aria-pressed=true]{border-color:var(--accent);color:var(--text)}.cm-list{flex:1;overflow-y:auto;padding:10px 12px;display:flex;flex-direction:column;gap:10px}.cm-empty{color:var(--text-faint);font-size:13px;line-height:1.5;margin:18px 4px}.cm-card{padding:10px 11px;border-radius:var(--r-card);border:1px solid var(--border);background:var(--surface);font-size:13px}.cm-card.active{border-color:var(--accent)}.cm-card.resolved{opacity:.85}.cm-card-top{display:flex;gap:8px;align-items:flex-start;cursor:pointer}.cm-card-top .cm-quote{flex:1}.cm-n{flex:none;min-width:18px;height:18px;padding:0 4px;border-radius:9px 9px 9px 2px;background:var(--accent);color:#241704;font:600 10.5px/18px var(--ui);text-align:center}.cm-card.resolved .cm-n{background:var(--text-faint)}.cm-flag{margin:0 0 8px;font-size:11.5px;color:var(--accent)}.cm-msg{margin:6px 0 8px}.cm-who{font-size:12px;color:var(--text-faint)}.cm-who b{color:var(--text);font-weight:600;margin-right:4px}.cm-body{margin-top:2px;color:var(--text-body);line-height:1.45;white-space:pre-wrap;overflow-wrap:anywhere}.cm-resolved{display:flex;align-items:center;gap:5px;margin:4px 0 8px;font-size:12px;color:var(--add)}.cm-resolved .ico{width:13px;height:13px}.cm-panel textarea.cm-reply{min-height:0;margin-top:6px}.cm-del{width:28px;height:27px;border:none;border-radius:6px;background:transparent;color:var(--text-faint);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.cm-del:hover{color:var(--del);background:var(--hover)}.cm-del .ico{width:14px;height:14px}.cm-foot{flex:none;padding:10px 12px 12px;border-top:1px solid var(--border)}.cm-hint{flex:1;font-size:11.5px;color:var(--text-faint)}.cm-hint code{font-family:var(--mono);font-size:11px}@media print{.fv-rail{display:none!important}:root,:root[data-theme=light]{color-scheme:light!important;--bg: #fff;--bg-side: #fff;--bg-raise: #fff;--surface: #f6f6f7;--hover: transparent;--border: #d9dade;--border-2: #c3c5ca;--code-bg: #f6f6f7;--text: #14161a;--text-bright: #000;--text-body: #1c1f24;--code-ink: #4a3a12;--quote-ink: #3a3226;--text-dim: #444851;--text-faint: #5c6069;--text-ghost: #767b84;--accent: #8a5a00;--accent-bright: #8a5a00;--glow: transparent}#sidebar,#sb-backdrop,#topbar,#palette,.modal,#more-menu,#presence,#exit-full,.rw-handle,[data-slot=dialog-overlay],[data-sonner-toaster],.cm-panel,.cm-pin,.cm-float,.cm-compose{display:none!important}body.full-view #content,body.full-view #content:has(.page.bleed){padding:0}html,body{height:auto}body{display:block;background:#fff}#main{display:block}#content{overflow:visible;padding:0}.page,.page.read,.page.wide{max-width:none}a[href]{text-decoration:underline}h1,h2,h3,h4{break-after:avoid}pre,tr,img,blockquote{break-inside:avoid}}#sb-search{display:flex;align-items:center;gap:8px;height:28px;margin:4px 0 0;padding:0 6px 0 7px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--text-dim);cursor:text}#sb-search:hover{background:var(--hover)}#sb-search:focus-within{border-color:var(--border-2);background:var(--surface)}#sb-search.filtering{border-color:var(--accent)}#sb-search .ico{width:16px;height:16px;flex:none}#sb-search input{flex:1;min-width:0;padding:0;border:0;outline:0;background:transparent;color:var(--text);font:inherit;font-size:13px;cursor:inherit}#sb-search input::placeholder{color:var(--text-dim)}.sb-kbd{flex:none;font:11px var(--ui);color:var(--text-faint);cursor:pointer;background:none;border:0;padding:0 2px}.sb-kbd:hover{color:var(--text)}#sidebar>#sb-search{margin:4px 8px 0}.sb-section{display:flex;align-items:center;flex:none;gap:2px;height:28px;margin-top:16px;padding:0 8px;font-size:12px;font-weight:500;color:var(--text-faint)}.sb-section>span{flex:1}#pinned{flex:none;max-height:30%;overflow-y:auto;padding:0 8px}#pinned .row.gone{opacity:.55;cursor:default}#pinned .row>.ico{width:16px;height:16px;flex:none;color:var(--text-faint)}.pin-badge{flex:none;font-size:12px;color:var(--text-faint);font-variant-numeric:tabular-nums}.pin-badge.danger{color:var(--danger-ink)}#pinned .pin-x{display:none}#pinned .row:hover .pin-x,#pinned .row:focus-within .pin-x{display:inline-flex}.files-head{margin-left:8px;margin-right:8px;padding-right:2px}.sb-foot{flex:none;padding:8px}.sb-sync{width:100%;border:0;background:transparent;font:inherit;font-size:12px;color:var(--text-faint);text-align:left}.sb-sync .ico{width:16px;height:16px;flex:none}.sync-dot{width:6px;height:6px;margin:0 5px;border-radius:999px;background:var(--add);flex:none}#tree .tmeta{flex:none;font-size:11px;color:var(--text-faint);padding-right:2px}#tree .tnew{color:var(--accent-ink)}#tree .tconflicts{flex:none;font-size:11px;color:var(--danger-ink);white-space:nowrap}#tree .tmore .label{font-size:12px;color:var(--text-faint);padding-left:21px}#tree .tmore:hover .label{color:var(--text)}.thover{position:absolute;right:4px;top:50%;transform:translateY(-50%);display:flex;gap:2px;opacity:0;pointer-events:none;background:var(--bg-side);border-radius:5px}#tree .row:hover .thover,#tree .row:focus-within .thover,#tree .row.menu-open .thover{opacity:1;pointer-events:auto}#tree .row.active .thover{background:transparent}.tact{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border:0;border-radius:4px;background:var(--hover);color:var(--text-dim);cursor:pointer;padding:0}.tact:hover{color:var(--text);background:var(--border-2)}.tact .ico{width:12px;height:12px}.files-head .tact{width:22px;height:22px;border-radius:5px;background:transparent;color:var(--text-faint)}.files-head .tact .ico{width:14px;height:14px}.files-head .tact:hover{background:var(--hover);color:var(--text)}.files-head .tact.on{color:var(--text);background:var(--hover)}.files-head #tree-sort-btn:not(.on){opacity:0}.files-head:hover #tree-sort-btn,.files-head:focus-within #tree-sort-btn{opacity:1}.row-menu{min-width:220px}.row-menu .ico{width:13px;height:13px}#tree-filter{flex:1;overflow-y:auto;padding:4px 8px 24px}.fgroup{padding:12px 8px 4px;font-size:12px;font-weight:500;color:var(--text-faint)}.fhit{display:flex;align-items:flex-start;gap:7px;padding:6px 8px;border-radius:7px;color:var(--text-dim);cursor:pointer}.fhit .ticon{display:flex;padding-top:1px;color:var(--text-ghost)}.fhit .ticon .ico{width:14px;height:14px}.fhit.sel{background:var(--glow);color:var(--text)}.fhit-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}.fhit-name{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fhit-name mark{background:var(--glow);color:var(--accent-bright);border-radius:3px;padding:0 1px}.fhit-path{font:11px var(--mono);color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fhit-enter{flex:none;font-size:11px;color:var(--accent-ink)}.fcontents{margin-top:8px;border:1px solid var(--border);align-items:center}.fcontents .fhit-name{flex:1}.fcontents kbd{font:10.5px var(--ui);color:var(--text-faint)}.fmore,.fempty{display:block;padding:6px 8px;font-size:12px;color:var(--text-faint);background:none;border:0;cursor:pointer;text-align:left}.fmore:hover{color:var(--text)}.fempty{cursor:default}#rail{display:none;flex:1;flex-direction:column;align-items:center;gap:2px;padding:10px 0;overflow-y:auto;overflow-x:hidden}.rail-mark{color:var(--accent-ink);display:grid;place-items:center;height:32px;margin-bottom:4px}.rail-sep{width:20px;height:1px;background:var(--border);margin:6px 0;flex:none}.rail-btn{position:relative;flex:none;width:32px;height:32px;display:grid;place-items:center;border:0;border-radius:6px;background:transparent;color:var(--text-dim);cursor:pointer}.rail-btn:hover{background:var(--hover);color:var(--text)}.rail-btn.active{background:var(--row-on);color:var(--text)}.rail-btn .ico{width:16px;height:16px}.rail-proj{margin-bottom:8px}.rail-proj:hover,.rail-proj[data-state=open]{background:var(--hover)}.rail-proj .proj-mark{width:24px;height:24px;border-radius:6px}.rail-proj .proj-mark svg{width:14px;height:14px}.rail-badge{position:absolute;top:2px;right:0;min-width:16px;height:15px;padding:0 4px;border-radius:999px;font-size:9.5px;font-weight:700;line-height:15px;text-align:center;background:var(--accent);color:var(--bg)}.rail-badge.danger{background:var(--del);color:var(--bg)}.tip-hint{color:var(--text-faint);font-weight:400}.sync-pill{display:inline-flex;align-items:center;gap:5px;margin-left:10px;height:20px;padding:0 8px;border-radius:10px;background:color-mix(in srgb,var(--add) 14%,transparent);color:var(--add);font-size:11.5px;font-weight:500;vertical-align:1px}.sync-pill:before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor}#topbar .btn.ghost{background:transparent;border-color:transparent}#topbar .btn.ghost:hover{background:var(--hover);color:var(--text)}#topbar .btn.ghost[aria-pressed=true]{background:var(--hover);color:var(--text);border-color:var(--border)}#comments-btn .cm-count{min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--glow);color:var(--accent-ink);font-size:11px;line-height:18px;text-align:center}#topbar .pbtn{height:30px;padding:0 12px;font-size:12.5px}.presence-count{margin:0 6px 0 4px;font-size:12.5px;color:var(--text-faint);white-space:nowrap}@media(max-width:900px){#topbar .pbtn{min-width:44px;min-height:44px;padding:0;justify-content:center;gap:0}#topbar .pbtn .lbl,.presence-count,.sync-pill{display:none}}.cm-msg{display:flex;gap:9px;align-items:flex-start}.cm-msg-main{flex:1;min-width:0}.cm-av{flex:none;width:24px;height:24px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:var(--hover);border:1px solid var(--border-2);color:var(--text-dim);font-size:9.5px;font-weight:650}.cm-queued{display:flex;align-items:center;gap:6px;margin:4px 0 8px;padding:6px 9px;border-radius:var(--r-ctl);background:var(--glow);color:var(--accent-ink);font-size:12px}.cm-queued .ico{width:13px;height:13px;flex:none}.cm-queued code{font:11px var(--mono)}.cm-row .btn.cm-act{height:26px;padding:0 7px;gap:5px;background:transparent;border-color:transparent;font-size:12px}.cm-row .btn.cm-act:hover{background:var(--hover)}.cm-row .btn.cm-act .ico{width:13px;height:13px}.cm-card .cm-row{justify-content:flex-start;gap:2px}.cm-pin{display:inline-flex;align-items:center;gap:3px;padding:0 6px;border-radius:10px}.cm-pin .ico{width:11px;height:11px}@media(max-width:900px){#edit-btn .ico{display:none}}@media(min-width:1400px){body:has(.cm-panel) .page.read:has(>aside.fv-rail){max-width:var(--page-read);margin-inline:auto}body:has(.cm-panel) aside.fv-rail{display:none}}@media(max-width:900px){.cm-pin{left:-19px!important;padding:0 5px}.cm-pin .ico{display:none}}@media(max-width:1200px){#topbar #comments-btn .lbl,#topbar #history-btn .lbl,.presence-count,.sync-pill{display:none}}.home{padding-bottom:40px}.home-head{margin:4px 0 26px}.home-greet{font-size:26px;font-weight:660;letter-spacing:-.02em;margin:0 0 6px;color:var(--text-bright)}.home-since{margin:0;color:var(--text-dim);font-size:14px;line-height:1.5;min-height:1.5em}.home-sec{margin-bottom:28px}.home-eyebrow{margin:0 0 10px;font-size:11.5px;font-weight:640;letter-spacing:.08em;text-transform:uppercase;color:var(--text-faint)}.home-h{display:flex;align-items:center;gap:8px;margin:0 0 12px;font-size:15.5px;font-weight:620;color:var(--text-bright)}.home-h .ico{width:15px;height:15px;color:var(--accent)}.home-count{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:18px;padding:0 6px;border-radius:999px;background:var(--hover);border:1px solid var(--accent-dim);color:var(--accent-ink);font-size:11.5px;font-weight:640}.home-row{display:flex;align-items:baseline;justify-content:space-between;gap:12px}.home-more{font-size:12.5px;color:var(--accent-bright);text-decoration:none;white-space:nowrap}.home-more:hover{text-decoration:underline}.home-none{margin:0;color:var(--text-faint);font-size:13px}.home-cards{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.home-card{display:grid;gap:4px;padding:12px 14px;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);color:var(--text);text-decoration:none;min-width:0}.home-card:hover{border-color:var(--border-2);background:var(--hover)}.hc-name{display:flex;align-items:center;gap:7px;font-weight:600;color:var(--text-bright);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hc-name .ico{width:14px;height:14px;flex:none;color:var(--text-faint)}.hc-dir{font-family:var(--mono);font-size:11.5px;color:var(--text-faint);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hc-when{font-size:12px;color:var(--text-dim)}.home-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:36px;align-items:start}.home-list{list-style:none;margin:0;padding:0;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface)}.home-attn-row{display:flex;align-items:center;gap:12px;padding:12px 14px}.home-attn-row+.home-attn-row{border-top:1px solid var(--border)}.ha-icon{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;flex:none;border-radius:8px;background:var(--hover);color:var(--text-dim)}.ha-icon .ico{width:15px;height:15px}.home-attn-row.conflict .ha-icon{color:var(--danger-bright)}.home-attn-row.comments .ha-icon,.home-attn-row.stale .ha-icon{color:var(--accent-bright)}.ha-text{display:grid;gap:2px;min-width:0;flex:1}.ha-title{color:var(--text);font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ha-title b{font-weight:600;color:var(--text-bright)}.ha-sub{color:var(--text-faint);font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.home-activity .hf-seg{margin-bottom:8px}.home-feed{list-style:none;margin:0;padding:0}.home-fe{display:flex;gap:12px;padding:11px 0;border-bottom:1px solid var(--border)}.fe-avatar{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;flex:none;border-radius:999px;background:var(--hover)}.fe-avatar .ico{width:14px;height:14px}.fe-avatar.agent{color:var(--viz-agent)}.fe-avatar.human{color:var(--viz-human)}.fe-body{display:grid;gap:2px;min-width:0;flex:1;font-size:13.5px;color:var(--text)}.fe-body b{font-weight:600;color:var(--text-bright)}.fe-what{color:var(--text-dim)}.fe-path{font-family:var(--mono);font-size:12px;color:var(--text);text-decoration:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}a.fe-path:hover{color:var(--accent-bright)}.fe-path.del{text-decoration:line-through;color:var(--text-faint)}.fe-dev{font-size:12px;color:var(--text-faint)}.fe-when{flex:none;font-size:12px;color:var(--text-faint)}.home-devlist{list-style:none;margin:0;padding:0;display:grid;gap:10px}.home-devlist li{display:flex;align-items:center;gap:10px}.dev-dot{width:7px;height:7px;flex:none;border-radius:999px;background:var(--text-ghost)}.dev-dot.on{background:var(--add)}.dev-text{display:grid;min-width:0;flex:1}.dev-name{font-size:13.5px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dev-sub{font-size:12px;color:var(--text-faint)}.dev-agent{font-size:12px;color:var(--text-dim);white-space:nowrap}.home-connect{padding:14px 16px;border:1px solid var(--accent-dim);border-radius:var(--r-card);background:var(--surface)}.home-connect .home-h{font-size:14px;margin-bottom:6px}.home-connect .gd-code>code{white-space:pre-wrap;max-height:5.2em;overflow:hidden}.home-bars{list-style:none;margin:0 0 10px;padding:0;display:grid;gap:10px}.hb-label{display:flex;justify-content:space-between;font-size:13px;color:var(--text);text-decoration:none}.hb-label:hover{color:var(--accent-bright)}.hb-n{font-variant-numeric:tabular-nums;color:var(--text-dim)}.hb-track{display:block;height:4px;margin-top:4px;border-radius:2px;background:var(--hover)}.hb-fill{display:block;height:100%;min-width:4px;border-radius:2px}.fresh-fresh .hb-fill{background:var(--add)}.fresh-aging .hb-fill{background:var(--accent)}.fresh-stale .hb-fill{background:var(--danger-bright)}.home-legend{display:flex;gap:14px;font-size:12px;color:var(--text-dim)}.home-legend span:before{content:"";display:inline-block;width:10px;height:4px;margin-right:6px;border-radius:2px;vertical-align:2px}.home-legend .fresh-fresh:before{background:var(--add)}.home-legend .fresh-aging:before{background:var(--accent)}.home-legend .fresh-stale:before{background:var(--danger-bright)}.home-files{margin-top:8px;padding-top:22px;border-top:1px solid var(--border)}@media(max-width:1100px){.home-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.home-grid{grid-template-columns:minmax(0,1fr)}}.pavatar{display:inline-flex;align-items:center;justify-content:center;flex:none;width:20px;height:20px;border-radius:50%;background:hsl(var(--ph) 70% 88%);color:hsl(var(--ph) 60% 28%);font-size:9.5px;font-weight:650;line-height:1;letter-spacing:0}.ed-state{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 9px;border-radius:999px;background:var(--hover);color:var(--text-dim);font-size:12px;white-space:nowrap}.ed-state>i{width:6px;height:6px;border-radius:50%;background:var(--text-faint)}.ed-state[data-collab=live]{color:var(--add);background:color-mix(in srgb,var(--add) 12%,transparent)}.ed-state[data-collab=live]>i{background:var(--add)}.ed-state[data-state=saving]{color:var(--accent-ink)}.ed-state[data-state=error],.ed-state[data-collab=offline]{color:var(--accent-ink);background:var(--glow)}.ed-state[data-state=error]>i,.ed-state[data-collab=offline]>i{background:var(--accent)}.ed-editors{display:inline-flex;align-items:center;margin-left:10px}.ed-editors .pavatar{width:22px;height:22px;margin-left:-5px;box-shadow:0 0 0 2px var(--bg)}.ed-editors .pavatar:first-child{margin-left:0}.ed-more{margin-left:4px;font-size:11.5px;color:var(--text-faint)}.ed-modes{display:inline-flex;gap:2px;padding:3px;margin:0 0 16px;border-radius:var(--r-ctl);background:var(--hover)}.ed-modes button{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 11px;border:0;border-radius:5px;background:none;color:var(--text-dim);font:inherit;font-size:12.5px;cursor:pointer}.ed-modes button .ico{width:13px;height:13px}.ed-modes button:hover{color:var(--text)}.ed-modes button.on{background:var(--bg-raise);color:var(--text-bright);box-shadow:0 0 0 1px var(--border)}.ed-offline{margin:0 0 12px;padding:10px 14px;border:1px solid color-mix(in srgb,var(--accent) 40%,transparent);border-radius:var(--r-card);background:var(--glow);color:var(--text-body);font-size:13px;line-height:1.5}.ed-offline b{color:var(--accent-ink)}.ed-statusbar{position:sticky;bottom:calc(-1 * var(--content-pad-b, 0px));z-index:2;display:flex;flex-wrap:wrap;gap:4px 18px;align-items:center;margin-top:12px;padding:7px 2px;border-top:1px solid var(--border);background:var(--bg);color:var(--text-faint);font-size:12px}.ed-statusbar .ico{width:12px;height:12px}.ed-guard{display:inline-flex;align-items:center;gap:5px;color:var(--add)}.ed-pos{margin-left:auto;font-family:var(--mono)}.cm-host.cm-mode-write .cm-scroller{font-family:var(--ui);font-size:15px;line-height:1.75}.cm-host.cm-mode-write .cm-line span{text-decoration:none}.cm-host.cm-mode-write .cm-activeLine{background:transparent}.cm-host .ms-line{padding-top:10px;font-weight:620;color:var(--text-bright)}.cm-host .ms-head{display:inline-flex;align-items:center;gap:6px;margin-right:8px;vertical-align:middle}.cm-host .ms-toggle{position:relative;width:18px;height:18px;padding:0;border:0;border-radius:4px;background:none;color:var(--text-faint);font-size:0;cursor:pointer}.cm-host .ms-toggle:before{content:"";position:absolute;left:6px;top:5px;border:4px solid transparent;border-left:5px solid currentColor;transform:rotate(90deg);transform-origin:2px 4px;transition:transform .12s ease}.cm-host .ms-toggle[aria-expanded=false]:before{transform:none}.cm-host .ms-toggle:hover{background:var(--hover);color:var(--text)}.cm-host .ms-toggle:disabled{opacity:.35;cursor:default}.cm-host .ms-status{float:right;margin-left:12px;font-size:12px;font-weight:400;color:var(--text-faint)}.cm-host .ms-typing{color:hsl(var(--ph, 210) 65% 62%)}.cm-host .ms-empty{color:var(--del)}.cm-host .ms-you{color:var(--accent-ink)}.cm-host .ms-summary{margin-left:8px;padding:1px 8px;border-radius:5px;background:var(--hover);color:var(--text-dim);font-size:12.5px;font-weight:400;cursor:pointer}.cm-host .cm-foldPlaceholder{background:none;border:0;padding:0;margin:0}.cm-host .cm-ySelectionInfo{font-family:var(--ui);font-size:10.5px;font-weight:600;padding:1px 5px;border-radius:4px;opacity:1!important}.cm-tooltip.cm-tooltip-autocomplete{background:var(--bg-raise);border:1px solid var(--border-2);border-radius:var(--r-card);padding:4px;box-shadow:0 18px 50px -16px #0009}.cm-tooltip.cm-tooltip-autocomplete>ul{font-family:var(--ui)!important;font-size:13px;max-height:18em}.cm-tooltip.cm-tooltip-autocomplete>ul>li{padding:6px 10px;border-radius:6px;color:var(--text)}.cm-tooltip.cm-tooltip-autocomplete>ul>li[aria-selected]{background:var(--hover);color:var(--text-bright)}.cm-tooltip.cm-tooltip-autocomplete completion-section{display:block;padding:6px 10px 2px;color:var(--text-faint);font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;border:0}.cm-tooltip-autocomplete .cm-completionDetail{margin-left:10px;color:var(--text-faint);font-style:normal;font-size:12px}.cm-tooltip-autocomplete .cm-completionMatchedText{text-decoration:none;color:var(--accent-ink)}.er-rail button.fv-sec-link{background:none;border:0;padding:0;cursor:pointer;font:inherit;font-size:12px}.fv-rail .er-empty,.fv-rail .er-note{margin:0;color:var(--text-faint);font-size:12px;line-height:1.5}.fv-rail .er-note{margin-top:8px}.er-list,.er-people,.er-vlist{list-style:none;margin:0;padding:0}.er-list li{display:flex;gap:9px;padding:5px 0;color:var(--text-body)}.er-list li.done .er-text{color:var(--text-faint);text-decoration:line-through}.er-box{flex:none;width:15px;height:15px;margin-top:2px;border:1.5px solid var(--text-faint);border-radius:4px;font-size:10px;line-height:12px;text-align:center;color:var(--bg)}.er-list li.done .er-box{background:var(--accent);border-color:var(--accent)}.er-text{display:flex;flex-direction:column;gap:1px;min-width:0;overflow-wrap:anywhere}.er-text small{color:var(--text-faint);font-size:11.5px}.er-bar{height:3px;margin:-2px 0 10px;border-radius:2px;background:var(--hover);overflow:hidden}.er-bar>span{display:block;height:100%;background:var(--add)}.er-people li{display:flex;align-items:center;gap:9px;padding:5px 0}.er-name{color:var(--text);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.er-state{margin-left:auto;font-size:12px;color:var(--text-faint);white-space:nowrap}.er-state.none{color:var(--del)}.er-state.typing{color:var(--viz-human)}.er-vlist li{display:grid;grid-template-columns:10px auto 1fr auto;align-items:center;gap:4px 8px;padding:5px 0;font-size:12px}.er-dot{width:7px;height:7px;border-radius:50%;background:var(--text-faint)}.er-dot.live{background:var(--add)}.er-dot.bad{background:var(--del)}.er-vtime{font-family:var(--mono);color:var(--text);white-space:nowrap}.er-vwho{color:var(--text-dim);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.er-vsize{font-family:var(--mono);color:var(--text-faint);text-align:right}.er-vlist li.empty .er-vsize{color:var(--del)}.er-restore{grid-column:2 / -1;justify-self:start;height:22px;padding:0 8px;border:1px solid var(--border-2);border-radius:6px;background:var(--surface);color:var(--accent-ink);font:inherit;font-size:11.5px;cursor:pointer}.er-restore:hover{background:var(--hover)}.shrink-dialog .sd-head{display:flex;align-items:center;gap:12px;margin-bottom:12px}.shrink-dialog .sd-head h3{margin:0}.sd-icon{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:color-mix(in srgb,var(--del) 14%,transparent);color:var(--del)}.sd-compare{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:0 0 18px}.sd-compare>div{display:flex;flex-direction:column;gap:3px;padding:9px 12px;border:1px solid var(--border);border-radius:var(--r-ctl);background:var(--surface);font-size:12px;color:var(--text-faint)}.sd-compare b{font-size:14px;font-weight:600}.sd-ok{color:var(--add)}.sd-bad{color:var(--del)}.sd-actions{justify-content:space-between} diff --git a/internal/webapp/static/assets/sharedfile-CtVUr4nt.js b/internal/webapp/static/assets/sharedfile-CR4ZqPh0.js similarity index 99% rename from internal/webapp/static/assets/sharedfile-CtVUr4nt.js rename to internal/webapp/static/assets/sharedfile-CR4ZqPh0.js index 20f42ae8..deb011f5 100644 --- a/internal/webapp/static/assets/sharedfile-CtVUr4nt.js +++ b/internal/webapp/static/assets/sharedfile-CR4ZqPh0.js @@ -1,4 +1,4 @@ -import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-DyFnf9EY.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-Co6en_o0.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=` `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})() BearDrive - + - +
From 94162954ab50aaa6b729d2264d049c97172e552b Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 03:02:18 +0900 Subject: [PATCH 21/34] fix(webapp): seal VisualEdit iframe channel in virgin realm and re-arm exit worker on bfcache --- CHANGELOG.md | 1 + architecture/webapp-frontend.md | 5 +- architecture/webapp-server.md | 5 +- .../webapp/frontend/e2e/inline-edit.spec.ts | 234 ++++++++++++++-- .../frontend/src/components/VisualEdit.tsx | 122 ++++++-- internal/webapp/frontend/src/inline-edit.ts | 265 +++++++++++++----- .../webapp/frontend/src/lib/editbeacon.ts | 9 +- .../frontend/src/lib/editexit.worker.ts | 84 +++++- internal/webapp/htmledit.go | 69 ++++- internal/webapp/htmledit_test.go | 78 ++++++ ...{Editor-CeIX9UEc.js => Editor-Cp12kr6p.js} | 2 +- .../static/assets/VisualEdit-D6HKLJJk.js | 1 - .../static/assets/VisualEdit-DbM9aXAX.js | 1 + .../static/assets/editexit.worker-BwVzdlZv.js | 11 + .../static/assets/editexit.worker-D_nakb5p.js | 11 - .../{index-Co6en_o0.js => index-Dgs5VYVU.js} | 4 +- ...ile-CR4ZqPh0.js => sharedfile-f4YTnm99.js} | 2 +- internal/webapp/static/index.html | 2 +- internal/webapp/static/inline-edit.js | 34 +-- 19 files changed, 759 insertions(+), 181 deletions(-) rename internal/webapp/static/assets/{Editor-CeIX9UEc.js => Editor-Cp12kr6p.js} (99%) delete mode 100644 internal/webapp/static/assets/VisualEdit-D6HKLJJk.js create mode 100644 internal/webapp/static/assets/VisualEdit-DbM9aXAX.js create mode 100644 internal/webapp/static/assets/editexit.worker-BwVzdlZv.js delete mode 100644 internal/webapp/static/assets/editexit.worker-D_nakb5p.js rename internal/webapp/static/assets/{index-Co6en_o0.js => index-Dgs5VYVU.js} (99%) rename internal/webapp/static/assets/{sharedfile-CR4ZqPh0.js => sharedfile-f4YTnm99.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa32399..f158398a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **Hub writes record their base, and devices skip redundant merges.** Conditional hub writes record the version they were built on in `Op.Base`. The sync engine merges a losing op against the op that won, and when the result equals the winner's content (another device or the hub already merged both sides), it fast-forwards and writes no new op. - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. - **`VisualEdit` flushes unacknowledged iframe edits through a same-origin exit worker when the tab closes.** The editing iframe stays `sandbox="allow-scripts"` and is never given a session, token or URL. `VisualEdit` starts a dedicated Web Worker on the app's origin (`editexit.worker.ts`), keeps it current with the rendered source, the anchored ranges and what the file and document hold after every save, and hands the iframe only one end of a `MessageChannel` (`bd-edit:port`). The app acknowledges each numbered patch it applies (`bd-edit:ack`); when the iframe unloads with an unacknowledged patch, it posts its edited spans to the worker (`bd-edit:exit`). This exit save is best-effort and runs only once the worker has started and been armed with the anchored render. The worker splices only anchored, script-free spans onto the render, merges the result three ways with the current document, and saves it with the app's own cookie: `POST /api/p//ycollab/sync` on a hub or `bdrive desktop`, or `PUT upload/content` on the latest `If-Match` in a plain folder, so it also works after earlier auto-saves. A same-word clash parks a conflict copy, an unconfirmed sharp shrink is not sent, and delivery is still subject to the browser's teardown limits (`keepalive` up to 60,000 bytes). +- **The `VisualEdit` iframe talks to the app only over a sealed channel, and the exit worker re-arms after a back/forward-cache restore.** The editable view now injects `/inline-edit.js` synchronously before any script in the synced HTML file, so it captures the browser's own `MessageChannel`, `MessagePort` methods and `Event.isTrusted` before page code can replace them. It opens a private `MessageChannel` and sends `bd-edit:hello` with one port to the app once; every later editor message (ready, patch, ack, port, flush, unlock) uses that channel instead of `window.postMessage`, and an editor opens or changes only on a trusted user event. When a page comes back from the back/forward cache, `VisualEdit` sends the exit worker `rearm` with a fresh port, so an unacknowledged edit made after the restore is still saved when the tab closes again. ## v0.18.9 — 2026-11-11 diff --git a/architecture/webapp-frontend.md b/architecture/webapp-frontend.md index 6b84cf95..1cc60683 100644 --- a/architecture/webapp-frontend.md +++ b/architecture/webapp-frontend.md @@ -192,7 +192,7 @@ classDiagram +merge3.ts merge3 merge3PreferRight merge3ForPath validMergedText diffSplices applySplices retainsChanges (TS port of internal/textmerge; .json/.jsonl merges held to valid JSON as the hub holds them) +frameflush.ts frameChannel FrameChannel saveLocked (FIFO queue of iframe messages; drain posts bd-edit:flush, optionally with lock, and waits for bd-edit:flushed; saveLocked unlocks with bd-edit:unlock unless the save landed) +editbeacon.ts ackEditedSpan unackedExitPatches applyRenderPatches buildExitSaveRequest (pure exit-save logic, tested without a DOM) - +editexit.worker.ts (dedicated same-origin Web Worker: arm / sync / disarm from VisualEdit, bd-edit:exit from the iframe's MessagePort) + +editexit.worker.ts (dedicated same-origin Web Worker: arm / sync / rearm / disarm from VisualEdit, bd-edit:exit from the iframe's MessagePort) +sharedfile.ts openSharedFile SharedFile SAVE_IDLE_MS saveNow askingShrink +sharedfile.ts merge MergeResult (an outside write, offered to an open document; held = already in the room) +sharedfile.ts rebase (the head sha moved because a co-editor saved) @@ -236,7 +236,7 @@ classDiagram components --> lib : openSharedFile (Editor and VisualEdit share one room; both loaded on demand) note for components "FileView loads Editor/VisualEdit by hand (loadEditor/useModule), not React.lazy: lazy suspends on its first render even for a module already fetched, and React then holds the fallback for at least 300 ms. Browser preloads them once a writable file has settled and on Edit hover/focus (preloadEditor), along with the file's text under EditView's own [text, url] key (prefetchEditText), so pressing Edit renders at once. Until the co-editing room answers, Editor shows the text as a plain
 — not a second CodeMirror, so nothing looking for the editor finds it — and once onStalled fires it mounts a staging CodeMirror over the text the room join will start from. Comment writes update the cached thread list from the hub's answer and refetch in the background (useCommentActions.place); a delete leaves the list before the hub answers and a refusal is put back by the refetch"
     note for components "Editor binds Mod-s to saveNow. VisualEdit stages into a private Y.Doc (stageDoc) while the room is stalled and splices an edited element as the minimal change inside it (diffSplices) instead of replacing its whole range; both hand their SharedFile to FileView through handle. FileView fills Browser's flushRef with saveNow (Promise<boolean>) + askingShrink, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation"
-    note for lib "frameflush.ts is VisualEdit's side of the iframe's postMessage stream. frameChannel handles every message strictly in arrival order, each after the one before it finishes (anchoring is async), so an edit typed just before Done cannot still be queued when the save looks at the buffer. drain() posts bd-edit:flush with an id; inline-edit.ts posts any edit it still holds and then answers bd-edit:flushed with that id on the same channel, so once the answer is handled every earlier patch is in the document. A drain waits as long as the frame is there to answer, never on a timer, and gives up only when the frame is gone or the editor closes. Done's save goes through saveLocked(drain, save, unlock): the flush carries lock: true, so the frame stops accepting edits until bd-edit:unlock and nothing typed during the save can be left out of it. If saveNow returns false or throws (a failed save or an open shrink question, so the editor stays), saveLocked posts bd-edit:unlock; a save that lands leaves the frame locked because the editor is about to close. Concurrent Done calls share one saveLocked"
+    note for lib "frameflush.ts is VisualEdit's side of the iframe's sealed message channel. frameChannel handles every message strictly in arrival order, each after the one before it finishes (anchoring is async), so an edit typed just before Done cannot still be queued when the save looks at the buffer. drain() posts bd-edit:flush with an id; inline-edit.ts posts any edit it still holds and then answers bd-edit:flushed with that id on the same channel, so once the answer is handled every earlier patch is in the document. A drain waits as long as the frame is there to answer, never on a timer, and gives up only when the frame is gone or the editor closes. Done's save goes through saveLocked(drain, save, unlock): the flush carries lock: true, so the frame stops accepting edits until bd-edit:unlock and nothing typed during the save can be left out of it. If saveNow returns false or throws (a failed save or an open shrink question, so the editor stays), saveLocked posts bd-edit:unlock; a save that lands leaves the frame locked because the editor is about to close. Concurrent Done calls share one saveLocked"
     note for components "EditView (FileView.tsx) is the editing page: a Write / Markdown / Preview segmented control over ONE Editor — Write and Markdown reconfigure the same CodeMirror through a Compartment, Preview hides it without unmounting, so the room, the cursor and the undo stack survive a switch and the /edit/ URL stays the invitation. The top bar's #editor-state reads Live · saved Ns ago / Offline · N edits pending, beside avatars of everyone in the room (awareness). EditRail is the markdown edit rail: attendee progress (meeting notes), action items from - [ ] … @owner lines (Copy as markdown), and recent versions with a one-click Restore that POSTs /restore — a new op, never a rewrite. ShrinkDialogHost is the blocking empty-save dialog: sharedfile raises it on the hub's 422 when this client saves, and — because a hub-held room's refusal never reaches a client — on seeing the document itself sharpShrink against the last known file text; Keep (the default) splices the file's current bytes back into the document, Save anyway PUTs the document as it stands with X-Bdrive-Confirm-Shrink. The ask belongs to its editor: destroying the SharedFile withdraws it (withdrawShrink closes the dialog without running either answer, and no parting save is written), and both answers are no-ops on a destroyed file. After a Restore, EditView reconciles the open document itself through the Editor's SharedFile handle (onRestored) instead of relying on the change stream: merge with held when the hub reports it folded the restore into the live room, as an ordinary outside write otherwise. Meeting notes (any daily-meetings/ folder) get cm-meeting's per-person sections: fold state is CodeMirror folding (view-only), status derives from awareness cursors and changes seen in this tab, and while the socket is down only your own section takes edits (meeting.ts offlineEditable) — the preamble, other sections, and the whole note when it has no section of yours are filtered before they reach the CRDT"
     HubApp --> components
     components --> nav : linkProps navigate
@@ -250,6 +250,7 @@ classDiagram
     components --> lib : rangeFor describe hitTest (Comments)
     components --> lib : merge3PreferRight diffSplices frameChannel saveLocked, Worker(editexit.worker.ts) + MessageChannel (VisualEdit), saveNow askingShrink (FileView flush)
     note for lib "The VisualEdit exit save. The editing iframe runs the synced file's own scripts in sandbox allow-scripts with no allow-same-origin, so it is never given a session, a token or a URL. VisualEdit spawns a dedicated same-origin Worker (editexit.worker.ts) and arms it with the rendered source, the anchored allowedRanges and the live (savedText, baseSha, docText), which it keeps current on every save and rebase through SharedFile's onBaseChange. It transfers one end of a MessageChannel to inline-edit.ts as bd-edit:port. inline-edit.ts numbers each bd-edit:patch (seq) and VisualEdit answers bd-edit:ack for each patch it applied (ackEditedSpan). On beforeunload or pagehide with an unacknowledged span, inline-edit.ts posts { type: bd-edit:exit, patches } (unackedExitPatches) over that port. The worker trusts none of it: applyRenderPatches splices only anchored, ordered, script-free spans onto renderText, and buildExitSaveRequest three-way merges the result with docText / savedText, refuses an unconfirmed sharp shrink, and sends one request with the app's own same-origin cookie: POST ycollab/sync with park_on_conflict on a hub or desktop, or PUT upload/content with the latest If-Match and X-Bdrive-Park-On-Conflict on a plain folder (a create-only conflict copy for a same-word clash). keepalive when the body is at most 60,000 bytes"
+    note for lib "The iframe channel is sealed. The hub injects /inline-edit.js synchronously before any page script (editView), so inline-edit.ts captures the native MessageChannel, MessagePort.prototype methods and the Event.prototype.isTrusted getter at t = 0, creates a private MessageChannel, and posts { type: bd-edit:hello } with one port to VisualEdit exactly once, before the page's own scripts parse. Every later message (bd-edit:ready, patch, ack, port, flush, flushed, unlock) travels on that channel, never window.postMessage, so a page script can neither read nor forge it, and an editor opens or changes only on a trusted user event (Event.isTrusted). On pageshow after a back/forward-cache restore, VisualEdit sends the worker { type: rearm } with a fresh MessageChannel and hands the iframe its end as bd-edit:port over the sealed channel; the worker clears exited and parentUnloading, so an edit left unacknowledged on a second close is saved too"
     Browser ..> components : Done awaits FileView's flushRef
     lib --> api : syncCollab putText keepalive (sharedfile)
     components ..> inlineComment : postMessage via the ?comment=1 iframe
diff --git a/architecture/webapp-server.md b/architecture/webapp-server.md
index 129dee10..8405a963 100644
--- a/architecture/webapp-server.md
+++ b/architecture/webapp-server.md
@@ -604,10 +604,11 @@ classDiagram
         text/html only, inline only, PermWrite on the path
         stampEditable marks innermost text blocks
         data-bd-src offsets in UTF-16 units
-        appends /inline-edit.js + hash + length
+        injects /inline-edit.js + hash + length synchronously, before any page script
         own ETag; declines past maxEditableHTML
     }
-    note for editView "Click-to-edit's server half (htmledit.go), shaped like printView and for the same reason: HTML's parser accepts content appended after the stored bytes. It marks the INNERMOST text-bearing block with the byte range of its own inner content, so the browser can send back one element's markup and the app can splice exactly that range — the file keeps its indentation, comments and script blocks, and the history diff is one line instead of a whole-file rewrite. Phrasing content (a, span, strong, sup) is CONTENT, not a region: stamping it instead would make the only editable thing in 'See the <a>notes</a> for the method' the link text, and real prose almost always contains one. Offsets are UTF-16 code units because the browser resolves them against a Y.Text, which is indexed like every JS string — counting bytes agrees for ASCII and silently splices over a neighbour's markup on the first accented character. A DIFFERENT ETag from the plain render: same blob, different body, and a shared tag lets a cache answer ?edit=1 with unstamped bytes. Never on /s/* or a download, and the sandbox is untouched — editing buys no capability the reading view did not have"
+    note for editView "The bootstrap goes in before the page can run a line of its own: a synchronous script tag (never defer) as the first child of head when the file has one, otherwise just before the first tag that is not html, after the doctype and leading comments. It runs in a realm no page script has touched, so it holds the original MessageChannel, MessagePort and Event.isTrusted before the synced file's scripts could replace them. Only the output moves; every data-bd-src offset is still measured on the source."
+    note for editView "Click-to-edit's server half (htmledit.go). It marks the INNERMOST text-bearing block with the byte range of its own inner content, so the browser can send back one element's markup and the app can splice exactly that range — the file keeps its indentation, comments and script blocks, and the history diff is one line instead of a whole-file rewrite. Phrasing content (a, span, strong, sup) is CONTENT, not a region: stamping it instead would make the only editable thing in 'See the <a>notes</a> for the method' the link text, and real prose almost always contains one. Offsets are UTF-16 code units because the browser resolves them against a Y.Text, which is indexed like every JS string — counting bytes agrees for ASCII and silently splices over a neighbour's markup on the first accented character. A DIFFERENT ETag from the plain render: same blob, different body, and a shared tag lets a cache answer ?edit=1 with unstamped bytes. Never on /s/* or a download, and the sandbox is untouched — editing buys no capability the reading view did not have"
     class Share {
         +Token +Project +Path +Creator +Expires
     }
diff --git a/internal/webapp/frontend/e2e/inline-edit.spec.ts b/internal/webapp/frontend/e2e/inline-edit.spec.ts
index a4f5b6cb..7db35c91 100644
--- a/internal/webapp/frontend/e2e/inline-edit.spec.ts
+++ b/internal/webapp/frontend/e2e/inline-edit.spec.ts
@@ -480,28 +480,81 @@ test("two people editing different paragraphs both land", async ({ page, browser
   expect(after).toContain('');
 });
 
-/* Every message the editing iframe receives, recorded inside it (init scripts
-   run in every frame), so a spec can prove what the sandbox was handed. */
+/* Every message the editing iframe receives, recorded inside it, so a spec
+   can prove what the sandbox was handed. Nothing reaches it on window any
+   more — the editor's traffic is on its own MessagePort — so the recorder
+   wraps addEventListener, which an init script replaces before the frame's
+   editor script captures it. Installed in the frame only. */
 async function recordFrameMessages(page: Page) {
   await page.addInitScript(() => {
+    if (window.top === window) return;
     const seen: string[] = [];
     Object.defineProperty(window, "__bdSeen", { value: seen });
-    window.addEventListener("message", (e) => seen.push(JSON.stringify(e.data) ?? ""), true);
+    const add = EventTarget.prototype.addEventListener;
+    EventTarget.prototype.addEventListener = function (
+      this: EventTarget,
+      type: string,
+      listener: EventListenerOrEventListenerObject | null,
+      opts?: boolean | AddEventListenerOptions,
+    ) {
+      if (type === "message" && typeof listener === "function") {
+        const inner = listener;
+        listener = function (this: unknown, e: Event) {
+          try {
+            seen.push(JSON.stringify((e as MessageEvent).data) ?? "");
+          } catch {
+            seen.push("");
+          }
+          return inner.call(this, e);
+        } as EventListener;
+      }
+      return add.call(this, type, listener, opts);
+    };
+  });
+}
+
+/* Patches travel on the frame's MessagePort now, so dropping them means
+   catching them at the app's end: in the parent page, a port's onmessage
+   handler skips every bd-edit:patch while `__dropBdEditPatches` is set, so
+   nothing it carries is spliced, saved or acknowledged by the app. Install
+   before the page loads; switch on with dropPatches. */
+async function installPatchDrop(page: Page) {
+  await page.addInitScript(() => {
+    if (window.top !== window) return;
+    const desc = Object.getOwnPropertyDescriptor(MessagePort.prototype, "onmessage")!;
+    const dropped = (ev: MessageEvent) => {
+      const d: unknown = ev.data;
+      return (
+        "__dropBdEditPatches" in window &&
+        window.__dropBdEditPatches === true &&
+        !!d &&
+        typeof d === "object" &&
+        "type" in d &&
+        d.type === "bd-edit:patch"
+      );
+    };
+    Object.defineProperty(MessagePort.prototype, "onmessage", {
+      configurable: true,
+      get(this: MessagePort) {
+        return desc.get!.call(this);
+      },
+      set(this: MessagePort, fn: ((this: MessagePort, ev: MessageEvent) => unknown) | null) {
+        desc.set!.call(
+          this,
+          typeof fn === "function"
+            ? function (this: MessagePort, ev: MessageEvent) {
+                if (!dropped(ev)) return fn.call(this, ev);
+              }
+            : fn,
+        );
+      },
+    });
   });
 }
 
-// Every bd-edit:patch is dropped before VisualEdit's listener can see it, so
-// nothing it carries is spliced, saved or acknowledged by the app.
 async function dropPatches(page: Page) {
   await page.evaluate(() => {
-    window.addEventListener(
-      "message",
-      (e) => {
-        const d: unknown = e.data;
-        if (d && typeof d === "object" && "type" in d && d.type === "bd-edit:patch") e.stopImmediatePropagation();
-      },
-      true,
-    );
+    Object.defineProperty(window, "__dropBdEditPatches", { value: true, configurable: true, writable: true });
   });
 }
 
@@ -520,6 +573,7 @@ test("an edit whose postMessage is not delivered before tab close still lands",
     const editor = await ctx.newPage();
     await login(editor, ADMIN);
     await recordFrameMessages(editor);
+    await installPatchDrop(editor);
     await editor.goto(`/${id}/${file}`);
     await editor.click("#edit-btn");
     const frame = editor.frameLocator("iframe.htmlview");
@@ -533,9 +587,15 @@ test("an edit whose postMessage is not delivered before tab close still lands",
     // What the sandbox was ever sent: control messages only, no URL, no token.
     const child = editor.frames().find((f) => f.url().includes("edit=1"));
     expect(child).toBeTruthy();
-    const seen = await child!.evaluate(() => (window as unknown as { __bdSeen: string[] }).__bdSeen.slice());
-    const types = seen.map((s) => (JSON.parse(s) as { type?: string } | null)?.type);
-    expect(types).toContain("bd-edit:port");
+    const seen = await child!.evaluate(() =>
+      "__bdSeen" in window && Array.isArray(window.__bdSeen) ? window.__bdSeen.map(String) : [],
+    );
+    const types = seen.map((s) => {
+      const parsed: unknown = JSON.parse(s);
+      return parsed && typeof parsed === "object" && "type" in parsed && typeof parsed.type === "string"
+        ? parsed.type
+        : undefined;
+    });
     for (const t of types) expect(["bd-edit:port", "bd-edit:ack", "bd-edit:flush", "bd-edit:unlock"]).toContain(t);
     for (const s of seen) expect(s).not.toMatch(/https?:|\/api\/|token/i);
 
@@ -551,6 +611,147 @@ test("an edit whose postMessage is not delivered before tab close still lands",
   }
 });
 
+/* The synced file's own scripts — in  and in  — try everything
+   they can reach: catch a port off window, forge an exit and a patch, post a
+   fake hello/ready to the app, click an element and fake input into it. The
+   editor's script runs before them and talks only on its own port, and only
+   a person's input opens or changes an editor: the reader's edit lands, and
+   nothing the scripts wrote does. */
+const HOSTILE_SCRIPT = ``;
+const HOSTILE = `
+
+  
+    Hostile report
+    ${HOSTILE_SCRIPT}
+  
+  
+    

Hostile report

+

Revenue grew steadily across every region.

+ ${HOSTILE_SCRIPT} + + +`; + +test("hostile scripts inside the HTML file cannot steal editor ports or forge edits on close", async ({ + page, + browser, +}) => { + await login(page, ADMIN); + const id = await project(page); + const file = `hostile-${Date.now()}-${n++}.html`; + const put = await page.request.put(`/api/p/${id}/upload/content?path=${encodeURIComponent(file)}`, { + data: HOSTILE, + headers: { "Content-Type": "text/plain; charset=utf-8" }, + }); + expect(put.ok()).toBeTruthy(); + litter.push(async () => { + await page.request.post(`/api/p/${id}/remove`, { data: { path: file } }).catch(() => {}); + }); + + const ctx = await browser.newContext(); + try { + const editor = await ctx.newPage(); + await login(editor, ADMIN); + await installPatchDrop(editor); + await editor.goto(`/${id}/${file}`); + await editor.click("#edit-btn"); + const frame = editor.frameLocator("iframe.htmlview"); + await frame.locator("html[data-bd-exit='ready']").waitFor(); + await dropPatches(editor); // only the exit worker can save what follows + + await frame.locator("p.lead").click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" Genuine edit."); + await editor.close({ runBeforeUnload: true }); + + const after = await waitForSource(page, id, file, "Revenue grew steadily across every region. Genuine edit."); + expect(after).not.toContain("PWNED_EXIT"); + expect(after).not.toContain("PWNED_PATCH"); + expect(after).not.toContain("PWNED_INPUT"); + expect(after.split("").length - 1).toBe(1); + } finally { + await ctx.close().catch(() => {}); + } +}); + +/* The page goes into the bfcache (pagehide, persisted) with an edit the app + never heard: the exit worker saves it, and that exit's port is spent. The + page comes back (pageshow) and is edited again — still unheard — and then + really closed. The worker must have been re-armed with a fresh port, or the + second edit goes nowhere. Both must land. */ +test("after a bfcache pagehide and pageshow, a second undelivered edit still saves on tab close", async ({ + page, + browser, +}) => { + await login(page, ADMIN); + const id = await project(page); + const file = await ownFile(page, id); + + const ctx = await browser.newContext(); + try { + const editor = await ctx.newPage(); + await login(editor, ADMIN); + await installPatchDrop(editor); + await editor.goto(`/${id}/${file}`); + await editor.click("#edit-btn"); + const frame = editor.frameLocator("iframe.htmlview"); + await frame.locator("html[data-bd-exit='ready']").waitFor(); + await dropPatches(editor); + const child = editor.frames().find((f) => f.url().includes("edit=1")); + expect(child).toBeTruthy(); + + await frame.locator("p.lead").click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" First bfcache."); + + // Into the bfcache, in the browser's order: the parent, then the frame. + await editor.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true }))); + await child!.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true }))); + await waitForSource(page, id, file, "Revenue grew steadily across every region. First bfcache."); + + // Back again: the app hands the frame a fresh exit port. + await child!.evaluate(() => document.documentElement.removeAttribute("data-bd-exit")); + await editor.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))); + await child!.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))); + await frame.locator("html[data-bd-exit='ready']").waitFor(); + + await frame.locator("li").first().click(); + await editor.keyboard.press("End"); + await editor.keyboard.type(" Second close."); + await editor.close({ runBeforeUnload: true }); + + const after = await waitForSource(page, id, file, "North America led the quarter. Second close."); + expect(after).toContain("Revenue grew steadily across every region. First bfcache."); + expect(after.split("First bfcache.").length - 1).toBe(1); + expect(after.split("").length - 1).toBe(1); + } finally { + await ctx.close().catch(() => {}); + } +}); + const REPO = fileURLToPath(new URL("../../../../", import.meta.url)); function freePort(): Promise { @@ -604,6 +805,7 @@ test("plain-folder mode: an auto-saved edit followed by an undelivered edit befo const onDisk = () => fs.readFileSync(page, "utf8"); const editor = await ctx.newPage(); + await installPatchDrop(editor); await editor.goto(base + "/page.html"); await editor.click("#edit-btn"); const frame = editor.frameLocator("iframe.htmlview"); diff --git a/internal/webapp/frontend/src/components/VisualEdit.tsx b/internal/webapp/frontend/src/components/VisualEdit.tsx index a111cc74..e074f04f 100644 --- a/internal/webapp/frontend/src/components/VisualEdit.tsx +++ b/internal/webapp/frontend/src/components/VisualEdit.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useLayoutEffect, useRef, useState } from "react"; import * as Y from "yjs"; import { openSharedFile, type SaveState, type SharedFile } from "../lib/sharedfile"; import { diffSplices, merge3PreferRight } from "../lib/merge3"; @@ -131,6 +131,29 @@ export function VisualEdit({ fileRef.current?.rebase(baseSha); }, [baseSha]); + /* The frame's channel. Its script runs first in the document, before any of + the page's own, and hands up one end of a MessageChannel (`bd-edit:hello`) + before a page script exists to see it; every message after that travels + on that port, so nothing the page's scripts post on window is heard. + + Only the FIRST hello from a frame document is taken, so it must not be + missed: this listener is in place in the same task that commits the + iframe (a layout effect), before the frame can have loaded anything. */ + const helloPort = useRef(null); + const helloTake = useRef<((port: MessagePort) => void) | null>(null); + useLayoutEffect(() => { + helloPort.current = null; + const onHello = (e: MessageEvent) => { + if (!frame.current || e.source !== frame.current.contentWindow || helloPort.current) return; + const d: unknown = e.data; + if (!d || typeof d !== "object" || !("type" in d) || d.type !== "bd-edit:hello" || !e.ports[0]) return; + helloPort.current = e.ports[0]; + helloTake.current?.(e.ports[0]); + }; + window.addEventListener("message", onHello); + return () => window.removeEventListener("message", onHello); + }, [apiBase, path, fileURL, gen]); + useEffect(() => { /* The two halves arrive independently and BOTH are needed before a range means anything: the iframe's ranges, and a shared document that actually @@ -196,16 +219,43 @@ export function VisualEdit({ let frameInteracted = false; let latestSavedText = seed.current; let latestBaseSha: string | undefined = shaRef.current; + // The frame's end of the sealed channel (see helloPort above). + let appPort: MessagePort | null = null; const noteFrameInteraction = () => { if (frameInteracted || document.activeElement !== frame.current) return; frameInteracted = true; if (exitWorker && !workerDisarmed) exitWorker.postMessage({ type: "interacted" }); }; + // A real unload of this page (never a component cleanup): the worker may + // save what the frame hands it. + let hadPageHide = false; const onParentUnload = () => { + hadPageHide = true; noteFrameInteraction(); if (!exitWorker || workerDisarmed || !frameInteracted) return; exitWorker.postMessage({ type: "parent-unload" }); }; + /* Back from the bfcache: the exit that went on the way out closed its + port, and this page may be closed again with another edit the app has + not heard. A fresh port to the worker, for the same render. */ + const onPageShow = (e: PageTransitionEvent) => { + if (!hadPageHide && !e.persisted) return; + hadPageHide = false; + if (!anchored || !exitWorker || workerDisarmed || !appPort) return; + const mc = new MessageChannel(); + exitWorker.postMessage( + { + type: "rearm", + savedText: latestSavedText, + baseSha: latestBaseSha, + hasBaseSha: true, + docText: activeDocText(), + interacted: frameInteracted, + }, + [mc.port1], + ); + appPort.postMessage({ type: "bd-edit:port" }, [mc.port2]); + }; const activeDocText = () => stageDoc ? stageDoc.getText("body").toString() : (fileRef.current?.collab.text.toString() ?? ""); const syncExitWorker = () => { @@ -227,11 +277,12 @@ export function VisualEdit({ // Every deliberate re-render of the frame: its unload is no tab closing. const reload = () => { disarmExitWorker(); + appPort?.close(); + appPort = null; setGen((g) => g + 1); }; const armExitWorker = (renderText: string) => { - const win = frame.current?.contentWindow; - if (!exitWorker || workerDisarmed || !win) return; + if (!exitWorker || workerDisarmed || !appPort) return; const mc = new MessageChannel(); exitWorker.postMessage( { @@ -249,15 +300,15 @@ export function VisualEdit({ }, [mc.port1], ); - win.postMessage({ type: "bd-edit:port" }, "*", [mc.port2]); + appPort.postMessage({ type: "bd-edit:port" }, [mc.port2]); }; const ackPatch = (msg: Patch) => { - if (typeof msg.seq === "number") frame.current?.contentWindow?.postMessage({ type: "bd-edit:ack", seq: msg.seq }, "*"); + if (typeof msg.seq === "number") appPort?.postMessage({ type: "bd-edit:ack", seq: msg.seq }); }; const drainFrame = async (lock: boolean) => { const el = frame.current; - const win = el?.contentWindow; - if (!el || !win) return; + const port = appPort; + if (!el || !port) return; // A frame that reloads or is replaced cannot answer: stop waiting then. let reloaded = false; const onLoad = () => { @@ -266,8 +317,8 @@ export function VisualEdit({ el.addEventListener("load", onLoad); try { await channel.drain( - (m) => win.postMessage(m, "*"), - () => !frameReady || reloaded || frame.current !== el || el.contentWindow !== win, + (m) => port.postMessage(m), + () => !frameReady || reloaded || frame.current !== el || appPort !== port, lock, ); } finally { @@ -280,24 +331,24 @@ export function VisualEdit({ /* Lock the frame and drain it: every patch it posted is in the document and nothing more can be typed until the returned release. Done's save and the join (a staging buffer folded into the room) both hold one; - counted per frame window, so neither unlocks the other early and a + counted per frame channel, so neither unlocks the other early and a release meant for a frame since replaced never touches the new one. */ - const winLocks = new Map(); + const portLocks = new Map(); const lockFrame = async (): Promise<() => void> => { - const win = frame.current?.contentWindow; - if (!win) return () => {}; - winLocks.set(win, (winLocks.get(win) ?? 0) + 1); + const port = appPort; + if (!port) return () => {}; + portLocks.set(port, (portLocks.get(port) ?? 0) + 1); let released = false; const release = () => { if (released) return; released = true; - const left = (winLocks.get(win) ?? 1) - 1; + const left = (portLocks.get(port) ?? 1) - 1; if (left > 0) { - winLocks.set(win, left); + portLocks.set(port, left); return; } - winLocks.delete(win); - win.postMessage({ type: "bd-edit:unlock" }, "*"); + portLocks.delete(port); + port.postMessage({ type: "bd-edit:unlock" }); }; try { await drainFrame(true); @@ -513,6 +564,8 @@ export function VisualEdit({ } if (msg.type === "bd-edit:ready") { + anchored = false; + anchors.clear(); ranges = msg.ranges; srcHash = msg.hash; srcLen = msg.len; @@ -617,15 +670,20 @@ export function VisualEdit({ ); return true; }; - const onMessage = (e: MessageEvent) => { - // The iframe is sandboxed WITHOUT allow-same-origin, so its origin is - // the string "null" and checking it proves nothing. Identity has to come - // from the window itself — checked as the message arrives, since the - // frame may be replaced before its turn in the queue comes. - if (!frame.current || e.source !== frame.current.contentWindow) return; - const msg = e.data as FromFrame; - if (!msg || typeof msg !== "object") return; - channel.enqueue(() => handleMessage(msg)); + // Every message from the frame arrives on its sealed port, in order. + const adoptPort = (port: MessagePort) => { + if (appPort === port) return; + appPort?.close(); + appPort = port; + anchored = false; + ranges = null; + anchors.clear(); + frameReady = false; + port.onmessage = (ev: MessageEvent) => { + const msg = ev.data as FromFrame; + if (!msg || typeof msg !== "object") return; + channel.enqueue(() => handleMessage(msg)); + }; }; // The document filling in is itself a reason to try anchoring again: the @@ -637,16 +695,19 @@ export function VisualEdit({ }; file.collab.text.observe(retry); - window.addEventListener("message", onMessage); + helloTake.current = adoptPort; + if (helloPort.current) adoptPort(helloPort.current); window.addEventListener("blur", noteFrameInteraction); window.addEventListener("beforeunload", onParentUnload); window.addEventListener("pagehide", onParentUnload); + window.addEventListener("pageshow", onPageShow); return () => { if (handle?.current === exposed) handle.current = null; + if (helloTake.current === adoptPort) helloTake.current = null; window.removeEventListener("blur", noteFrameInteraction); window.removeEventListener("beforeunload", onParentUnload); window.removeEventListener("pagehide", onParentUnload); - onParentUnload(); + window.removeEventListener("pageshow", onPageShow); frameReady = false; channel.close(); clearTimeout(retryTimer); @@ -665,7 +726,8 @@ export function VisualEdit({ cheap price for not having to be right about task ordering across browsers. */ setTimeout(() => { - window.removeEventListener("message", onMessage); + appPort?.close(); + appPort = null; clearTimeout(stageTimer); file.destroy(); disarmExitWorker(); diff --git a/internal/webapp/frontend/src/inline-edit.ts b/internal/webapp/frontend/src/inline-edit.ts index c4095f22..60dd6054 100644 --- a/internal/webapp/frontend/src/inline-edit.ts +++ b/internal/webapp/frontend/src/inline-edit.ts @@ -4,17 +4,20 @@ This is a separate bundle from the app, loaded only by the ?edit=1 render (server.go's serveEditable). A reader never downloads an editor, and the iframe keeps exactly the sandbox it always had — no allow-same-origin — so - nothing here can reach the hub's session. It talks to the app by postMessage - and accepts two things back: `bd-edit:flush` (a numeric id, optionally - `lock: true`), which posts any edit still held here and answers - `bd-edit:flushed` with that id — so the app's Done saves only after every - patch before the answer has landed — and, with `lock`, stops accepting - edits until `bd-edit:unlock`, so nothing typed during Done's save can be - left out of it. It also takes `bd-edit:ack` (each patch's `seq`, once the + nothing here can reach the hub's session. It is injected FIRST in the + document, before any of the page's own scripts, and hands the app one end + of a MessageChannel (`bd-edit:hello`); everything after travels on that + port, never on window, so the page's scripts can neither hear nor forge + it. Back it takes `bd-edit:flush` (a numeric id, optionally `lock: true`), + which posts any edit still held here and answers `bd-edit:flushed` with + that id — so the app's Done saves only after every patch before the answer + has landed — and, with `lock`, stops accepting edits until + `bd-edit:unlock`. It also takes `bd-edit:ack` (each patch's `seq`, once the app has it in the document) and `bd-edit:port` (a MessagePort to the app's exit worker, lib/editexit.worker.ts): a tab closed before a patch was acknowledged posts every edited span down that port on the way out. This - frame never holds a URL or credential and makes no request of its own. + frame never holds a URL or credential and makes no request of its own, and + only a person's input (Event.isTrusted) opens or changes an editor. Three things had to be true at once, and they decided the design: @@ -43,6 +46,92 @@ import { baseKeymap, toggleMark } from "@tiptap/pm/commands"; import { history, undo, redo } from "@tiptap/pm/history"; import { ackEditedSpan, unackedExitPatches, type EditedSpan } from "./lib/editbeacon"; +/* ---- t = 0: before the page's own scripts exist ---- + + The server injects this script first in the document, synchronous, so it + runs in a realm no page script has touched yet. Everything a page script + could later replace to see or forge this editor's traffic is taken now: + the channel to the app, the methods that move messages on it, the + isTrusted getter that tells a person's input from a script's, and the DOM + reads the ranges come from. The app's end of the channel is handed up + below (`bd-edit:hello`) before any page script can watch window messages; + nothing in this editor ever travels on window again. */ +const NativeMessageChannel = window.MessageChannel; +const portPost = MessagePort.prototype.postMessage; +const portClose = MessagePort.prototype.close; +const portStart = MessagePort.prototype.start; +const targetAddListener = EventTarget.prototype.addEventListener; +const getIsTrusted = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted")!.get!; +const getMsgData = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data")!.get!; +const getMsgPorts = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "ports")!.get!; +const elGetAttribute = Element.prototype.getAttribute; +const elClosest = Element.prototype.closest; +const docQueryAll = window.Document.prototype.querySelectorAll; +const nativeSetTimeout = window.setTimeout.bind(window); +const nativeClearTimeout = window.clearTimeout.bind(window); +const postToParent = window.parent.postMessage.bind(window.parent); + +// The hash the server computed over the STORED bytes, read while this script +// is still `currentScript`. The app compares it with the document it holds: +// if they differ, the ranges describe a file that has since moved on, and it +// reloads rather than splicing by them. +const self = document.currentScript as HTMLScriptElement | null; +const hash = self?.dataset.srcHash ?? ""; +// The source length in UTF-16 units, which is the app's fallback check when it +// cannot compute a hash — crypto.subtle exists only in a secure context, and a +// LAN hub on plain HTTP is not one. +const len = Number(self?.dataset.srcLen ?? "-1"); + +// This frame's end of the channel to the app; never on window or the DOM. +const appChannel = new NativeMessageChannel(); +const appPort = appChannel.port1; +const send = (msg: Record) => { + portPost.call(appPort, msg); +}; + +/* A person's input, as opposed to a script's. Each trusted input event opens + a window that lasts through its own task — the handler and ProseMirror's + DOM-observer microtask after it — and closes on the next one. A document + change outside such a window was made by a script, not by the reader. */ +let trustedEditOpen = false; +let composing = false; +let trustedTimer: ReturnType | undefined; +const openTrustedWindow = (ms = 0) => { + trustedEditOpen = true; + nativeClearTimeout(trustedTimer); + trustedTimer = nativeSetTimeout(() => { + trustedEditOpen = false; + }, ms); +}; +for (const name of [ + "keydown", + "beforeinput", + "input", + "textInput", + "compositionstart", + "compositionupdate", + "compositionend", + "paste", + "cut", + "drop", +]) { + targetAddListener.call( + document, + name, + (e: Event) => { + if (!getIsTrusted.call(e)) return; + if (name === "compositionstart") composing = true; + else if (name === "compositionend") { + composing = false; + openTrustedWindow(60); + return; + } + openTrustedWindow(0); + }, + true, + ); +} + const SRC_ATTR = "data-bd-src"; /* The schema IS the fidelity envelope. Every element whose markup this cannot @@ -156,7 +245,7 @@ function roundTrips(el: HTMLElement): boolean { type Range = { start: number; end: number }; function rangeOf(el: Element): Range | null { - const raw = el.getAttribute(SRC_ATTR); + const raw = elGetAttribute.call(el, SRC_ATTR); if (!raw) return null; const [a, b] = raw.split(","); const start = Number(a); @@ -165,8 +254,6 @@ function rangeOf(el: Element): Range | null { return { start, end }; } -const send = (msg: Record) => parent.postMessage(msg, "*"); - /* Whether an element may be edited is settled once and remembered. The check parses, so doing it per mousemove would be the one thing on this page that makes reading a document slow. */ @@ -315,6 +402,17 @@ function mount(el: HTMLElement, x?: number, y?: number) { editable: () => !locked, dispatchTransaction(tr) { if (locked && tr.docChanged) return; + if (tr.docChanged && !trustedEditOpen && !composing) { + /* The element changed with no input from the reader: the page's + own script wrote into it (or faked an event). That is not an + edit to save — close the editor and say so. */ + send({ type: "bd-edit:clobbered" }); + view?.destroy(); + view = null; + host = null; + range = null; + return; + } view!.updateState(view!.state.apply(tr)); /* Reported on EVERY change, with no debounce of its own. @@ -339,13 +437,17 @@ function mount(el: HTMLElement, x?: number, y?: number) { // ---- wiring ---- function nearestEditable(target: EventTarget | null): HTMLElement | null { - const el = (target as Element | null)?.closest?.(`[${SRC_ATTR}]`); + const el = target instanceof Element ? (elClosest.call(target, `[${SRC_ATTR}]`) as Element | null) : null; return el instanceof HTMLElement ? el : null; } -document.addEventListener( +targetAddListener.call( + document, "click", - (e) => { + (ev: Event) => { + // Only a person's click opens an editor: never el.click() from a script. + if (!getIsTrusted.call(ev)) return; + const e = ev as MouseEvent; if (locked) return; // no element opens or closes while Done saves const el = nearestEditable(e.target); if (!el) { @@ -361,104 +463,106 @@ document.addEventListener( // Verdicts are computed on approach so the outline only ever appears on // something that will actually open. An element that cannot be edited says so // on hover instead of refusing a click for no visible reason. -document.addEventListener( +targetAddListener.call( + document, "mouseover", - (e) => { + (e: Event) => { const el = nearestEditable(e.target); if (el) editable(el); }, true, ); -/* A page whose own script rewrites the DOM can replace the element out from - under an open editor, and the keystrokes go with it. There is no way to stop - that from here — the page's script is the page — so the honest move is to - notice and say so. Detaching is the observable form of every version of this: - a React re-render, a chart redraw, a template swap. */ -new MutationObserver(() => { - if (host && !host.isConnected) { - send({ type: "bd-edit:clobbered" }); - view?.destroy(); - view = null; - host = null; - range = null; - } -}).observe(document.documentElement, { childList: true, subtree: true }); +/* The rest needs the document's body, which this script — first in the + document — runs ahead of. */ +function initDOM() { + /* A page whose own script rewrites the DOM can replace the element out from + under an open editor, and the keystrokes go with it. There is no way to + stop that from here — the page's script is the page — so the honest move + is to notice and say so. Detaching is the observable form of every version + of this: a React re-render, a chart redraw, a template swap. */ + new MutationObserver(() => { + if (host && !host.isConnected) { + send({ type: "bd-edit:clobbered" }); + view?.destroy(); + view = null; + host = null; + range = null; + } + }).observe(document.documentElement, { childList: true, subtree: true }); -const style = document.createElement("style"); -style.textContent = ` + const style = document.createElement("style"); + style.textContent = ` [${SRC_ATTR}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } [${SRC_ATTR}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } [${SRC_ATTR}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } [${SRC_ATTR}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } `; -document.head.appendChild(style); - -// The hash the server computed over the STORED bytes. The app compares it with -// the document it holds: if they differ, the ranges below describe a file that -// has since moved on, and it reloads rather than splicing by them. -const self = - (document.currentScript as HTMLScriptElement | null) ?? - document.querySelector("script[data-src-hash]"); -const hash = self?.dataset.srcHash ?? ""; -// The source length in UTF-16 units, which is the app's fallback check when it -// cannot compute a hash — crypto.subtle exists only in a secure context, and a -// LAN hub on plain HTTP is not one. -const len = Number(self?.dataset.srcLen ?? "-1"); - -send({ - type: "bd-edit:ready", - hash, - len, - ranges: [...document.querySelectorAll(`[${SRC_ATTR}]`)] - .map((el) => rangeOf(el)) - .filter(Boolean), -}); + (document.head ?? document.documentElement).appendChild(style); + + send({ + type: "bd-edit:ready", + hash, + len, + ranges: [...(docQueryAll.call(document, `[${SRC_ATTR}]`) as NodeListOf)] + .map((el) => rangeOf(el)) + .filter(Boolean), + }); -// The markers are in the served HTML, so their presence says nothing about -// whether this script has run. Anything waiting to interact — a test, or a -// person — needs to know the listeners are actually installed, and this is -// the only observable difference between "rendered" and "editable". -document.documentElement.setAttribute("data-bd-ready", ""); + // The markers are in the served HTML, so their presence says nothing about + // whether this script has run. Anything waiting to interact — a test, or a + // person — needs to know the listeners are actually installed, and this is + // the only observable difference between "rendered" and "editable". + document.documentElement.setAttribute("data-bd-ready", ""); +} /* Leaving with an edit the app never acknowledged: hand it to the exit - worker, once per unload (marking it acknowledged). The worker, not this + worker, once per unload. What goes is recorded as acknowledged — the + ancestor (`ackedHtml`) for an edit made after the page comes back from the + bfcache, so that one neither drops nor repeats this. The worker, not this frame, decides whether and how it is saved. */ function exitUnacked() { if (!exitPort) return; const patches = unackedExitPatches(editedSpans.values()); if (patches === null) return; - for (const s of editedSpans.values()) s.acked = true; - exitPort.postMessage({ type: "bd-edit:exit", patches }); + for (const s of editedSpans.values()) { + s.acked = true; + s.ackedHtml = s.html; + } + portPost.call(exitPort, { type: "bd-edit:exit", patches }); } -window.addEventListener("beforeunload", () => { +targetAddListener.call(window, "beforeunload", () => { unmount(); exitUnacked(); }); // Flush on pagehide too; keep the open element mounted when entering bfcache. -window.addEventListener("pagehide", (e: PageTransitionEvent) => { - if (e.persisted) flush(); +targetAddListener.call(window, "pagehide", (e: Event) => { + if ((e as PageTransitionEvent).persisted) flush(); else unmount(); exitUnacked(); }); -/* Done in the app: post what the open editor holds, then answer. The answer - follows every patch on the same channel, so once the app has handled it, it - has handled them all. With `lock`, nothing more is typed until the app - unlocks (its save failed or asked a question) or tears the page down (it - saved). Only the app (the parent window) may ask. */ -window.addEventListener("message", (e) => { - if (e.source !== window.parent) return; - const msg = e.data as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown } | null; - if (!msg) return; +/* The app, on this frame's sealed port — never window: + - bd-edit:ack a patch is in the app's document + - bd-edit:port the exit worker's port (again, after a bfcache restore) + - bd-edit:flush Done: post what the open editor holds, then answer; the + answer follows every patch on the channel, so once the + app has it, it has them all. With `lock`, nothing more is + typed until bd-edit:unlock (its save failed or asked a + question) or the page is torn down (it saved). */ +targetAddListener.call(appPort, "message", (e: Event) => { + const msg = getMsgData.call(e) as { type?: unknown; id?: unknown; lock?: unknown; seq?: unknown } | null; + if (!msg || typeof msg !== "object") return; if (msg.type === "bd-edit:ack" && typeof msg.seq === "number") { ackEditedSpan(editedSpans.values(), msg.seq); return; } - if (msg.type === "bd-edit:port" && e.ports[0]) { - exitPort?.close(); - exitPort = e.ports[0]; + if (msg.type === "bd-edit:port") { + const next = (getMsgPorts.call(e) as ReadonlyArray)[0]; + if (!next) return; + if (exitPort) portClose.call(exitPort); + exitPort = next; document.documentElement.setAttribute("data-bd-exit", "ready"); return; } @@ -476,3 +580,10 @@ window.addEventListener("message", (e) => { view?.setProps({ editable: () => !locked }); } }); +portStart.call(appPort); + +if (document.readyState !== "loading") initDOM(); +else targetAddListener.call(document, "DOMContentLoaded", initDOM, { once: true }); + +// The app's end of the channel, before any page script can see a message. +postToParent({ type: "bd-edit:hello" }, "*", [appChannel.port2]); diff --git a/internal/webapp/frontend/src/lib/editbeacon.ts b/internal/webapp/frontend/src/lib/editbeacon.ts index 29482f0f..c8575090 100644 --- a/internal/webapp/frontend/src/lib/editbeacon.ts +++ b/internal/webapp/frontend/src/lib/editbeacon.ts @@ -177,8 +177,15 @@ export function buildExitSaveRequest( if (mergedOk && want === state.savedText) return null; if (hasCollabRoute(state.apiBase)) { + const priorSent = ancestor !== state.savedText ? [ancestor] : undefined; const payload = mergedOk - ? { base: state.baseSha, base_text: state.savedText, text: want, park_on_conflict: true } + ? { + base: state.baseSha, + base_text: state.savedText, + text: want, + park_on_conflict: true, + ...(priorSent ? { prior_sent: priorSent } : {}), + } : { base_text: state.renderText, text: renderedWant, park_on_conflict: true }; const body = JSON.stringify(payload); return { diff --git a/internal/webapp/frontend/src/lib/editexit.worker.ts b/internal/webapp/frontend/src/lib/editexit.worker.ts index cbbdc6f9..03e1042b 100644 --- a/internal/webapp/frontend/src/lib/editexit.worker.ts +++ b/internal/webapp/frontend/src/lib/editexit.worker.ts @@ -12,7 +12,10 @@ transferred port is the iframe's end of the channel sync — what the file holds / the document now, as the app saves disarm — the editor reloaded or closed normally: nothing more to do - From the iframe (the port), once: bd-edit:exit with every edited span. */ + rearm — the page came back from the bfcache after an exit: a fresh + port from the frame, and what the file holds now + From the iframe (the port), once per arming: bd-edit:exit with every + edited span. */ import { buildExitSaveRequest, type ExitPatch, type ExitWorkerState } from "./editbeacon"; @@ -30,9 +33,18 @@ type Arm = { interacted?: boolean; }; type Sync = { type: "sync"; savedText?: string; baseSha?: string; hasBaseSha?: boolean; docText?: string }; +type Rearm = { + type: "rearm"; + savedText: string; + baseSha?: string; + hasBaseSha?: boolean; + docText: string; + interacted?: boolean; +}; type FromApp = | Arm | Sync + | Rearm | { type: "interacted" } | { type: "parent-unload" } | { type: "disarm" }; @@ -45,6 +57,7 @@ let interacted = false; let parentUnloading = false; let pendingPatches: ExitPatch[] | null = null; let pendingTimer: ReturnType | undefined; +let workerSaved: { fromText: string; text: string; sha?: string } | null = null; /* A frame script cannot trigger a write on its own: both user interaction in the frame (`interacted`) and a real parent unload (`parentUnloading`) must @@ -58,17 +71,37 @@ const tryFlush = () => { exited = true; childPort?.close(); childPort = null; - const req = buildExitSaveRequest(state, patches); + const curState = state; + const req = buildExitSaveRequest(curState, patches); if (!req) return; + const fromText = curState.savedText; void fetch(req.url, { method: req.method, credentials: "same-origin", headers: req.headers, body: req.body, keepalive: req.keepalive, - }).catch(() => {}); + }) + .then(async (res) => { + if (!res.ok) return; + const out = (await res.json().catch(() => null)) as { + ok?: boolean; + sha?: string; + text?: string; + parked?: string; + } | null; + if (!out || out.parked) return; + const landedText = typeof out.text === "string" ? out.text : req.method === "PUT" ? req.body : null; + if (landedText === null) return; + workerSaved = { fromText, text: landedText, sha: out.sha }; + if (state === curState && state.savedText === fromText) { + if (state.docText === state.savedText) state.docText = landedText; + state.savedText = landedText; + if (typeof out.sha === "string" && out.sha) state.baseSha = out.sha; + } + }) + .catch(() => {}); }; - const onExit = (ev: MessageEvent) => { const msg = ev.data as { type?: unknown; patches?: unknown } | null; if (!msg || msg.type !== "bd-edit:exit" || !Array.isArray(msg.patches)) return; @@ -102,6 +135,7 @@ self.onmessage = (ev: MessageEvent) => { docText: msg.docText, }; if (msg.interacted) interacted = true; + workerSaved = null; parentUnloading = false; pendingPatches = null; clearTimeout(pendingTimer); @@ -111,6 +145,33 @@ self.onmessage = (ev: MessageEvent) => { if (childPort) childPort.onmessage = onExit; return; } + /* Back from the bfcache: the first exit already went (and closed its + port), but the page lives on and may be closed again with a new edit the + app has not heard. Same render, so the ranges stand; if the app itself + never learned of the worker's own exit save (frozen in bfcache), keep the + worker's landed version rather than rolling `savedText` back to before it. */ + if (msg.type === "rearm") { + if (!state) return; + if (workerSaved && msg.savedText === workerSaved.fromText) { + state.savedText = workerSaved.text; + if (workerSaved.sha) state.baseSha = workerSaved.sha; + state.docText = msg.docText === workerSaved.fromText ? workerSaved.text : msg.docText; + } else { + workerSaved = null; + state.savedText = msg.savedText; + if (msg.hasBaseSha) state.baseSha = msg.baseSha; + state.docText = msg.docText; + } + if (msg.interacted) interacted = true; + exited = false; + parentUnloading = false; + pendingPatches = null; + clearTimeout(pendingTimer); + childPort?.close(); + childPort = ev.ports[0] ?? null; + if (childPort) childPort.onmessage = onExit; + return; + } if (msg.type === "interacted") { interacted = true; tryFlush(); @@ -123,9 +184,18 @@ self.onmessage = (ev: MessageEvent) => { } if (msg.type === "sync") { if (!state) return; - if (typeof msg.savedText === "string") state.savedText = msg.savedText; - if (msg.hasBaseSha) state.baseSha = msg.baseSha; - if (typeof msg.docText === "string") state.docText = msg.docText; + if (typeof msg.savedText === "string") { + if (!workerSaved || msg.savedText !== workerSaved.fromText) { + workerSaved = null; + state.savedText = msg.savedText; + if (msg.hasBaseSha) state.baseSha = msg.baseSha; + } + } else if (msg.hasBaseSha && !workerSaved) { + state.baseSha = msg.baseSha; + } + if (typeof msg.docText === "string") { + state.docText = workerSaved && msg.docText === workerSaved.fromText ? workerSaved.text : msg.docText; + } return; } if (msg.type === "disarm") { diff --git a/internal/webapp/htmledit.go b/internal/webapp/htmledit.go index 860ace8b..9cd374df 100644 --- a/internal/webapp/htmledit.go +++ b/internal/webapp/htmledit.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "slices" "strings" "golang.org/x/net/html" @@ -255,7 +256,7 @@ func (s *stamper) findOpen(name string) int { } // stampEditable rewrites HTML source so every innermost text-bearing element -// carries its inner content's byte range in the original source, and appends +// carries its inner content's byte range in the original source, and inserts // the bootstrap that turns those ranges into editable regions. // // It is total: any input returns valid HTML. Malformed markup loses markers, @@ -269,6 +270,35 @@ func stampEditable(src []byte, scriptURL string) []byte { // token length no matter what gets emitted in its place. off := 0 + /* Where the bootstrap goes: before the page can run a line of its own. + + The page is whatever the project's writers put there, and the bootstrap + is what talks to the editor outside the frame. Run after the page's + scripts, it would find a realm they had already had their way with — a + message listener in place to take the channel's port, prototypes + replaced under it. Run first and synchronously, it holds the originals + before the parser reaches any page script. So it is the first child of + when the file has one, and otherwise sits just before the first + tag that is not — after the doctype and leading comments, so + neither the rendering mode nor a byte of the body moves. Only the + output is touched: every offset above is measured on the source. + bootChunk indexes s.out; bootAfter says after it rather than before. */ + bootChunk, bootAfter, decided := -1, false, false + htmlChunk := -1 + place := func(tt html.TokenType, name string) { + if decided { + return + } + switch { + case strings.EqualFold(name, "html"): + htmlChunk = len(s.out) - 1 // the bootstrap goes inside it + case strings.EqualFold(name, "head") && tt == html.StartTagToken: + bootChunk, bootAfter, decided = len(s.out)-1, true, true + default: + bootChunk, bootAfter, decided = len(s.out)-1, false, true + } + } + for { tt := z.Next() if tt == html.ErrorToken { @@ -297,10 +327,12 @@ func stampEditable(src []byte, scriptURL string) []byte { } if voidElements[tok.DataAtom] { s.out = append(s.out, chunk) + place(tt, tok.Data) continue } s.closeImplied(tok.DataAtom, start) s.out = append(s.out, chunk) + place(tt, tok.Data) inert := neverEditable[tok.DataAtom] || (len(s.stack) > 0 && s.stack[len(s.stack)-1].inert) s.stack = append(s.stack, openElem{ @@ -329,22 +361,35 @@ func stampEditable(src []byte, scriptURL string) []byte { default: // self-closing, comments, doctype: pass through untouched s.out = append(s.out, chunk) + if tt == html.SelfClosingTagToken { + name, _ := z.TagName() + place(tt, string(name)) + } } } sum := sha256.Sum256(src) - body := bytes.Join(s.out, nil) - // Appended after the stored bytes — the same place printSuffix goes, and - // for the same reason: HTML's parser accepts trailing content, and this - // path never touches what is served for download. - // - // The length rides along with the hash because the browser cannot always - // compute a hash: crypto.subtle exists only in a secure context, and a - // LAN hub served over plain HTTP is not one. Comparing lengths is a weaker - // check — it misses an edit that happens to preserve length — but it is - // the difference between a safety net and none at all on those hubs. - return fmt.Appendf(body, "\n", + // Synchronous, never defer: deferred, it would run after every page + // script. The length rides along with the hash because the browser cannot + // always compute a hash: crypto.subtle exists only in a secure context, + // and a LAN hub served over plain HTTP is not one. Comparing lengths is a + // weaker check — it misses an edit that happens to preserve length — but + // it is the difference between a safety net and none at all on those hubs. + boot := fmt.Appendf(nil, "", scriptURL, hex.EncodeToString(sum[:]), fmt.Sprint(utf16Len(src))) + if !decided && htmlChunk >= 0 { + bootChunk, bootAfter, decided = htmlChunk, true, true + } + if !decided { + // No tag at all: nothing runs before it wherever it goes. + return append(append(bytes.Join(s.out, nil), '\n'), boot...) + } + at := bootChunk + if bootAfter { + at++ + } + s.out = slices.Insert(s.out, at, boot) + return bytes.Join(s.out, nil) } func hasSrcAttr(t html.Token) bool { diff --git a/internal/webapp/htmledit_test.go b/internal/webapp/htmledit_test.go index bf766090..82ece6aa 100644 --- a/internal/webapp/htmledit_test.go +++ b/internal/webapp/htmledit_test.go @@ -452,3 +452,81 @@ func TestStampPreservesEverythingElse(t *testing.T) { } } } + +/* +The bootstrap runs before any of the page's own scripts. + + The page is whatever the project's writers put there. A script of its own + that ran first could listen for the editor's message and take the + channel's port, or replace the prototypes the bootstrap relies on. So the + bootstrap is synchronous and placed ahead of every page script — first in + , or before the first tag — while the doctype stays first (it sets + the rendering mode), the body's bytes stay put, and every range is still + measured on the stored source. +*/ +func TestStampRunsBootstrapBeforeEveryPageScript(t *testing.T) { + const boot = `"+ + "

hi

") + if !strings.HasPrefix(out, "") { + t.Fatalf("doctype is no longer first: %.60q", out) + } + if b := strings.Index(out, boot); !strings.Contains(out, ""+boot) || b > strings.Index(out, "evilHead()") { + t.Fatalf("bootstrap is not the first thing in : %q", out) + } + }) + t.Run("fragment", func(t *testing.T) { + src := "

hi

" + out := check(t, src) + if !strings.HasPrefix(out, boot) { + t.Fatalf("bootstrap does not lead the fragment: %q", out) + } + marks := parseStamped(t, []byte(out)) + if len(marks) != 1 || sliceU16([]byte(src), marks[0].start, marks[0].end) != "hi" { + t.Fatalf("

marks %+v, want one range slicing \"hi\"", marks) + } + }) + t.Run("headless", func(t *testing.T) { + src := "\n\n

Hello

\n" + out := check(t, src) + if !strings.HasPrefix(out, "\n"+boot) { + t.Fatalf("bootstrap is not between the doctype and : %q", out) + } + if !strings.Contains(out, "\n ") + if !strings.HasPrefix(out, ""+boot) { + t.Fatalf("bootstrap is not inside : %q", out) + } + }) + t.Run("no tags", func(t *testing.T) { + out := check(t, "") + if !strings.HasPrefix(out, "\n"+boot) { + t.Fatalf("tagless input: %q", out) + } + }) +} diff --git a/internal/webapp/static/assets/Editor-CeIX9UEc.js b/internal/webapp/static/assets/Editor-Cp12kr6p.js similarity index 99% rename from internal/webapp/static/assets/Editor-CeIX9UEc.js rename to internal/webapp/static/assets/Editor-Cp12kr6p.js index 9c182452..ee220865 100644 --- a/internal/webapp/static/assets/Editor-CeIX9UEc.js +++ b/internal/webapp/static/assets/Editor-Cp12kr6p.js @@ -1,4 +1,4 @@ -import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-Co6en_o0.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-CR4ZqPh0.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` +import{s as nr,b as Nr,o as TO,p as Vh,c as CO,r as oe,d as ZO,f as XO,e as AO,g as RO,j as wn,t as wl,w as MO,a as jO}from"./index-Dgs5VYVU.js";import{r as $l,b as Gi,a as As,c as Rs,e as Pl,f as LO,g as YO,h as Gr,t as $n,i as Pn,U as EO,S as zO,o as _O}from"./sharedfile-f4YTnm99.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";let Ms=[],Bh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Bh[i])e=i+1;else return!0;if(e==t)return!1}}function vl(n){return n>=127462&&n<=127487}const Tl=8205;function VO(n,e,t=!0,i=!0){return(t?qh:BO)(n,e,i)}function qh(n,e,t){if(e==n.length)return e;e&&Dh(n.charCodeAt(e))&&Ih(n.charCodeAt(e-1))&&e--;let i=Ur(n,e);for(e+=Cl(i);e=0&&vl(Ur(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function BO(n,e,t){for(;e>1;){let i=qh(n,e-2,t);if(i=56320&&n<57344}function Ih(n){return n>=55296&&n<56320}function Cl(n){return n<65536?1:2}class _{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ui(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),nt.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ui(this,e,t);let i=[];return this.decompose(e,t,i,0),nt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _i(this),s=new _i(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _i(this,e)}iterRange(e,t=this.length){return new Nh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Gh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):nt.from(ie.split(e,[]))}}class ie extends _{constructor(e,t=qO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new DO(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Zl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=Nn(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);[e,t]=ui(this,e,t);let r=Nn(this.text,Nn(i.text,Zl(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):nt.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}}class nt extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ui(this,e,t),i.lines=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[r]=a,new nt(c,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ui(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof nt))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let O of e)i+=O.lines;if(i<32){let O=[];for(let d of e)d.flatten(O);return new ie(O,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,c=[];function f(O){let d;if(O.lines>s&&O instanceof nt)for(let p of O.children)f(p);else O.lines>o&&(a>o||!a)?(u(),l.push(O)):O instanceof ie&&a&&(d=c[c.length-1])instanceof ie&&O.lines+d.lines<=32?(a+=O.lines,h+=O.length+1,c[c.length-1]=new ie(d.text.concat(O.text),d.length+1+O.length)):(a+O.lines>r&&u(),a+=O.lines,h+=O.length+1,c.push(O))}function u(){a!=0&&(l.push(c.length==1?c[0]:nt.from(c,h)),h=-1,a=c.length=0)}for(let O of e)f(O);return u(),l.length==1?l[0]:new nt(l,t)}}_.empty=new ie([""],0);function qO(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Nn(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(a>i&&(l=l.slice(0,i-r)),r0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Nh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _i(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Gh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},_i.prototype[Symbol.iterator]=Nh.prototype[Symbol.iterator]=Gh.prototype[Symbol.iterator]=function(){return this});let DO=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ui(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function fe(n,e,t=!0,i=!0){return VO(n,e,t,i)}function IO(n){return n>=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function jt(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return IO(i)?(t-55296<<10)+(i-56320)+65536:t}function GO(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Ft(n){return n<65536?1:2}const js=/\r\n?|\n/;var me=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(me||(me={}));class at{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=l}else{if(i!=me.Simple&&h>=e&&(i==me.TrackDel&&re||i==me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&l>=e)return rt?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new at(e)}static create(e){return new at(e)}}class re extends at{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ls(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Ys(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length0&&Pt(i,t,s.text),s.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(c=!1){if(!c&&!r.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let d=O?typeof O=="string"?_.of(O.split(i||js)):O:_.empty,p=d.length;if(f==u&&p==0)return;fo&&ce(r,f-o,-1),ce(r,u-f,p),Pt(s,r,d),o=u}}return h(e),a(!l),l}static empty(e){return new re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;rl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:r>=0&&e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,h,s,c,f),r=h,s=c}}}function Ys(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ui(n),l=new Ui(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);ce(r,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),s.forward2(a),o.forward(a)}}}}class Ui{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class wt{constructor(e,t,i,r){this.from=e,this.to=t,this.flags=i,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new wt(i,r,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,i);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,r,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,i,r){return new wt(e,t,i,r)}}class y{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:y.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new y(e.ranges.map(t=>wt.fromJSON(t)),e.main)}static single(e,t=e){return new y([y.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;rr.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?y.range(a,l):y.range(l,a))}}return new y(e,t)}}function Fh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ao=0;class Z{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Ao++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ro),!!e.static,e.enables)}of(e){return new Gn([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Gn(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Ro(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Gn{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Ao++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Es(f,c)){let O=i(f);if(l?!Xl(O,f.values[o],r):!r(O,f.values[o]))return f.values[o]=O,1}return 0},reconfigure:(f,u)=>{let O,d=u.config.address[s];if(d!=null){let p=sr(u,d);if(this.dependencies.every(g=>g instanceof Z?u.facet(g)===f.facet(g):g instanceof We?u.field(g,!1)==f.field(g,!1):!0)||(l?Xl(O=i(f),p,r):r(O=i(f),p)))return f.values[o]=p,0}else O=i(f);return f.values[o]=O,1}}}get extension(){return this}}function Xl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>{let s=i.facet(vn),o=r.facet(vn),l;return(l=s.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}}const Yt={lowest:4,low:3,default:2,high:1,highest:0};function Ci(n){return e=>new Hh(e,n)}const Nt={highest:Ci(Yt.highest),high:Ci(Yt.high),default:Ci(Yt.default),low:Ci(Yt.low),lowest:Ci(Yt.lowest)};class Hh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class un{of(e){return new zs(this,e)}reconfigure(e){return un.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class zs{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class rr{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let u of FO(e,t,o))u instanceof We?r.push(u):(s[u.facet.id]||(s[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of r)l[u.id]=h.length<<1,h.push(O=>u.slot(O));let c=i?.config.facets;for(let u in s){let O=s[u],d=O[0].facet,p=c&&c[u]||[];if(O.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,Ro(p,O))a.push(i.facet(d));else{let g=d.combine(O.map(S=>S.value));a.push(i&&d.compare(g,i.facet(d))?i.facet(d):g)}else{for(let g of O)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(S=>g.dynamicSlot(S)));l[d.id]=h.length<<1,h.push(g=>UO(g,d,O))}}let f=h.map(u=>u(l));return new rr(e,o,f,l,a,s)}}function FO(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof zs&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let h of o)s(h,l);else if(o instanceof zs){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,l)}else if(o instanceof Hh)s(o.inner,o.prec);else if(o instanceof We)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof Gn)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Yt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,l)}}return s(n,Yt.default),i.reduce((o,l)=>o.concat(l))}function Wi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function sr(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Kh=Z.define(),_s=Z.define({combine:n=>n.some(e=>e),static:!0}),Jh=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),ec=Z.define(),tc=Z.define(),ic=Z.define(),nc=Z.define({combine:n=>n.length?n[0]:!1});class Ge{constructor(e,t){this.type=e,this.value=t}static define(){return new HO}}class HO{of(e){return new Ge(this,e)}}class KO{constructor(e){this.map=e}of(e){return new V(this,e)}}class V{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new V(this.type,t)}is(e){return this.type==e}static define(e={}){return new KO(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}V.reconfigure=V.define();V.appendConfig=V.define();class ne{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Fh(i,t.newLength),s.some(l=>l.type==ne.time)||(this.annotations=s.concat(ne.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ne(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ne.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ne.time=Ge.define();ne.userEvent=Ge.define();ne.addToHistory=Ge.define();ne.remote=Ge.define();function JO(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ne?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ne?n=s[0]:n=sc(e,ri(s),!1)}return n}function td(n){let e=n.startState,t=e.facet(ic),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=rc(i,Ws(e,s,n.changes.newLength),!0))}return i==n?n:ne.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const id=[];function ri(n){return n==null?id:Array.isArray(n)?n:[n]}var mt=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(mt||(mt={}));const nd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Vs;try{Vs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function rd(n){if(Vs)return Vs.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||nd.test(t)))return!0}return!1}function sd(n){return e=>{if(!/\S/.test(e))return mt.Space;if(rd(e))return mt.Word;for(let t=0;t-1)return mt.Word;return mt.Other}}class W{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;lr.set(h,a)),t=null),r.set(l.value.compartment,l.value.extension)):l.is(V.reconfigure)?(t=null,i=l.value):l.is(V.appendConfig)&&(t=null,i=ri(i).concat(l.value));let s;t?s=e.startState.values.slice():(t=rr.resolve(i,r,this),s=new W(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(_s)?e.newSelection:e.newSelection.asSingle();new W(t,e.newDoc,o,s,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ri(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return W.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=rr.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(W.lineSeparator)||js)),r=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Fh(r,i.length),t.staticFacet(_s)||(r=r.asSingle()),new W(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(W.tabSize)}get lineBreak(){return this.facet(W.lineSeparator)||` diff --git a/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js b/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js deleted file mode 100644 index b44174d2..00000000 --- a/internal/webapp/static/assets/VisualEdit-D6HKLJJk.js +++ /dev/null @@ -1 +0,0 @@ -import{r as u,j as W,w as Ne,a as qe}from"./index-Co6en_o0.js";import{o as Ae,D as Ie,c as M,a as K,m as ve,d as Te}from"./sharedfile-CR4ZqPh0.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const _e=50,Ge=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function He(){let o=null;const l=new Map;let f=0,h=!1;const P=()=>o?o.then(()=>{}):Promise.resolve(),j=c=>{const p=c.catch(()=>{}).finally(()=>{o===p&&(o=null)});o=p};return{enqueue(c){if(o){j(o.then(c));return}try{const p=c();Ge(p)&&j(Promise.resolve(p))}catch{}},flushed(c){l.get(c)?.(),l.delete(c)},async drain(c,p,O=!1){if(await P(),h||p())return;const y=++f;let C;const U=new Promise(F=>{l.set(y,F),C=setInterval(()=>{!h&&!p()||(l.delete(y),F())},_e)});try{c(O?{type:"bd-edit:flush",id:y,lock:!0}:{type:"bd-edit:flush",id:y}),await U}finally{clearInterval(C)}await P()},close(){h=!0;for(const c of l.values())c();l.clear()}}}async function Oe(o,l,f){let h=!1;try{return await o(),h=await l(),h}finally{h||f()}}async function Ue(o){if(!globalThis.crypto?.subtle)return null;try{const l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(l)].map(f=>f.toString(16).padStart(2,"0")).join("")}catch{return null}}function Qe({apiBase:o,fileURL:l,path:f,initial:h,me:P,onStateChange:j,onCollab:c,onPeers:p,onConflictCopy:O,baseSha:y,onSaved:C,onWriting:U,onRendered:F,handle:B}){const w=u.useRef(null),[oe,Se]=u.useState(null),[ke,se]=u.useState(!1),[Ee,ae]=u.useState(!1),ie=u.useRef(0),[ce,Le]=u.useState(0),m=u.useRef({onStateChange:j,onCollab:c,onPeers:p,onSaved:C,onWriting:U,onRendered:F,onConflictCopy:O});m.current={onStateChange:j,onCollab:c,onPeers:p,onSaved:C,onWriting:U,onRendered:F,onConflictCopy:O};const D=u.useRef(h),J=u.useRef(P);J.current=P;const Q=u.useRef(y);Q.current=y;const X=u.useRef(null);return u.useEffect(()=>{X.current?.rebase(y)},[y]),u.useEffect(()=>{let S=null,N=!1,r=null,v;const Re=700;se(!1),ae(!1);const We=setTimeout(()=>{!T&&ie.current<1&&(ie.current++,E())},11e3),Me=setTimeout(()=>ae(!0),24e3),V=He();let Z=!1,d=null;try{d=typeof Worker<"u"?new Worker(new URL("/assets/editexit.worker-D_nakb5p.js",import.meta.url),{type:"module"}):null}catch{d=null}let k=!1,q=!1,$=D.current,ee=Q.current;const Y=()=>{q||document.activeElement!==w.current||(q=!0,d&&!k&&d.postMessage({type:"interacted"}))},A=()=>{Y(),!(!d||k||!q)&&d.postMessage({type:"parent-unload"})},Pe=()=>r?r.getText("body").toString():X.current?.collab.text.toString()??"",z=()=>{!d||k||d.postMessage({type:"sync",savedText:$,baseSha:ee,hasBaseSha:!0,docText:Pe()})},le=()=>{!d||k||(k=!0,d.postMessage({type:"disarm"}),d.terminate())},E=()=>{le(),Le(e=>e+1)},je=e=>{const t=w.current?.contentWindow;if(!d||k||!t)return;const s=new MessageChannel;d.postMessage({type:"arm",apiBase:o,path:f,who:J.current?.name,renderText:e,renderLen:e.length,allowedRanges:[...g.keys()],savedText:$,baseSha:ee,docText:e,interacted:q},[s.port1]),t.postMessage({type:"bd-edit:port"},"*",[s.port2])},de=e=>{typeof e.seq=="number"&&w.current?.contentWindow?.postMessage({type:"bd-edit:ack",seq:e.seq},"*")},Ce=async e=>{const t=w.current,s=t?.contentWindow;if(!t||!s)return;let a=!1;const n=()=>{a=!0};t.addEventListener("load",n);try{await V.drain(b=>s.postMessage(b,"*"),()=>!Z||a||w.current!==t||t.contentWindow!==s,e)}finally{t.removeEventListener("load",n)}clearTimeout(v),v=void 0},I=new Map,ue=async()=>{const e=w.current?.contentWindow;if(!e)return()=>{};I.set(e,(I.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const a=(I.get(e)??1)-1;if(a>0){I.set(e,a);return}I.delete(e),e.postMessage({type:"bd-edit:unlock"},"*")};try{await Ce(!0)}catch(a){throw s(),a}return s},i=X.current=Ae({apiBase:o,path:f,seed:D.current,baseSha:Q.current,who:J.current?.name,me:J.current,onConflictCopy:e=>m.current.onConflictCopy?.(e),onShrinkRefused:e=>qe(f,e),onShrinkWithdrawn:Ne,beforeJoin:async()=>r?ue():()=>{},onReady:()=>{if(clearTimeout(v),v=void 0,r){const e=r;r=null;const t=e.getText("body").toString(),s=i.collab.text.toString();if(T&&t===s)for(const[a,n]of g){const b=M(n.from,e),_=M(n.to,e);b&&_&&g.set(a,{from:K(i.collab.text,b.index),to:K(i.collab.text,_.index),span:n.span,orig:n.orig})}else g.clear(),T=!1,t!==s&&E();e.destroy()}N=!0,L()},onSolo:()=>{i.collab.text.length||i.collab.text.insert(0,D.current),N=!0,L()},onStalled:()=>{N||r||(r=new Ie,r.getText("body").insert(0,D.current),N=!0,L())},onState:e=>m.current.onStateChange?.(e),onCollab:e=>m.current.onCollab?.(e),onPeers:e=>m.current.onPeers?.(e),onSaved:e=>m.current.onSaved?.(e),onWriting:()=>m.current.onWriting?.(),onBaseChange:(e,t)=>{$=e,ee=t,z()},soloText:()=>r?r.getText("body").toString():D.current,soloApply:({from:e,to:t,insert:s})=>{r&&r.transact(()=>{const a=r.getText("body");t>e&&a.delete(e,t-e),s&&a.insert(e,s)})}});let fe=null;const pe={...i,saveNow:()=>{let e=()=>{};return fe??=Oe(async()=>{e=await ue()},()=>i.saveNow(),()=>e()).finally(()=>{fe=null})}};B&&(B.current=pe);const g=new Map,xe=e=>e.start+","+e.end,L=async()=>{if(T||!S||!N)return;const e=r?r.getText("body"):i.collab.text,t=e.toString();if(!t)return;if(S.some(n=>n.end>t.length||n.start>n.end)){S=null,E();return}const s=await Ue(t);if(s!==null?s!==he:te>=0&&t.length!==te){S=null,E();return}g.clear();for(const n of S)g.set(xe(n),{from:K(e,n.start),to:K(e,n.end),span:n.end-n.start,orig:t.slice(n.start,n.end)});T=!0,je(t),se(!0),m.current.onRendered?.()};let he="",te=-1,T=!1;const Fe=e=>{if(e.type==="bd-edit:flushed"){V.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){Se("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return S=e.ranges,he=e.hash,te=e.len,Z=!0,L();if(e.type==="bd-edit:patch"&&(Y(),!!q)){if(!T)return L().then(()=>{ye(e)&&(de(e),z())});ye(e)&&(de(e),z())}},ye=e=>{const t=g.get(xe(e));if(!t)return!1;if(r){const x=M(t.from,r),G=M(t.to,r);if(!x||!G||x.index>G.index)return!1;const H=r.getText("body"),De=G.index-x.index;if(x.index===0&&G.index===H.length&&t.spant.span*4+256)return g.clear(),T=!1,E(),!1;const re=H.toString().slice(x.index,G.index),be=ve(t.orig,re,e.html);return t.orig=e.html,re===be||(r.transact(()=>{for(const R of Te(re,be))R.deleteCount>0&&H.delete(x.index+R.index,R.deleteCount),R.insertText&&H.insert(x.index+R.index,R.insertText)}),m.current.onStateChange?.("dirty"),clearTimeout(v),v=setTimeout(()=>{i.saveNow()},Re)),!0}const s=i.collab.doc,a=M(t.from,s),n=M(t.to,s);if(!a||!n||a.index>n.index)return!1;const b=i.collab.text,_=n.index-a.index;if(a.index===0&&n.index===b.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:_,stamped:t.span,docLength:b.length}),g.clear(),T=!1,E(),!1;const ne=b.toString().slice(a.index,n.index),ge=ve(t.orig,ne,e.html);return t.orig=e.html,ne===ge||i.collab.applySplices(Te(ne,ge).map(x=>({...x,index:x.index+a.index}))),!0},we=e=>{if(!w.current||e.source!==w.current.contentWindow)return;const t=e.data;!t||typeof t!="object"||V.enqueue(()=>Fe(t))},me=()=>{z(),L()};return i.collab.text.observe(me),window.addEventListener("message",we),window.addEventListener("blur",Y),window.addEventListener("beforeunload",A),window.addEventListener("pagehide",A),()=>{B?.current===pe&&(B.current=null),window.removeEventListener("blur",Y),window.removeEventListener("beforeunload",A),window.removeEventListener("pagehide",A),A(),Z=!1,V.close(),clearTimeout(We),clearTimeout(Me),clearTimeout(v),i.collab.text.unobserve(me),setTimeout(()=>{window.removeEventListener("message",we),clearTimeout(v),i.destroy(),le(),r?.destroy()},300)}},[o,f,ce]),W.jsxs(W.Fragment,{children:[oe&&W.jsx("div",{id:"edit-clobbered",className:"banner",children:oe}),Ee&&!ke&&W.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",W.jsx("b",{children:"Edit source"}),"."]}),W.jsx("iframe",{ref:w,className:"htmlview",sandbox:"allow-scripts",src:l+(l.includes("?")?"&":"?")+"edit=1",title:f},ce)]})}export{Qe as VisualEdit}; diff --git a/internal/webapp/static/assets/VisualEdit-DbM9aXAX.js b/internal/webapp/static/assets/VisualEdit-DbM9aXAX.js new file mode 100644 index 00000000..f60bd54a --- /dev/null +++ b/internal/webapp/static/assets/VisualEdit-DbM9aXAX.js @@ -0,0 +1 @@ +import{r as i,j,w as _e,a as Ge}from"./index-Dgs5VYVU.js";import{o as Be,D as Oe,c as C,a as te,m as Re,d as Me}from"./sharedfile-f4YTnm99.js";import"./_commonjsHelpers-CqkleIqs.js";import"./mermaid-DQuCJ8Gi.js";const Ve=50,ze=o=>o!==null&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function";function Je(){let o=null;const d=new Map;let p=0,b=!1;const F=()=>o?o.then(()=>{}):Promise.resolve(),N=f=>{const h=f.catch(()=>{}).finally(()=>{o===h&&(o=null)});o=h};return{enqueue(f){if(o){N(o.then(f));return}try{const h=f();ze(h)&&N(Promise.resolve(h))}catch{}},flushed(f){d.get(f)?.(),d.delete(f)},async drain(f,h,O=!1){if(await F(),b||h())return;const v=++p;let q;const V=new Promise(A=>{d.set(v,A),q=setInterval(()=>{!b&&!h()||(d.delete(v),A())},Ve)});try{f(O?{type:"bd-edit:flush",id:v,lock:!0}:{type:"bd-edit:flush",id:v}),await V}finally{clearInterval(q)}await F()},close(){b=!0;for(const f of d.values())f();d.clear()}}}async function Ue(o,d,p){let b=!1;try{return await o(),b=await d(),b}finally{b||p()}}async function Ye(o){if(!globalThis.crypto?.subtle)return null;try{const d=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o));return[...new Uint8Array(d)].map(p=>p.toString(16).padStart(2,"0")).join("")}catch{return null}}function tt({apiBase:o,fileURL:d,path:p,initial:b,me:F,onStateChange:N,onCollab:f,onPeers:h,onConflictCopy:O,baseSha:v,onSaved:q,onWriting:V,onRendered:A,handle:z}){const L=i.useRef(null),[ue,Pe]=i.useState(null),[We,de]=i.useState(!1),[je,fe]=i.useState(!1),pe=i.useRef(0),[ne,Ce]=i.useState(0),T=i.useRef({onStateChange:N,onCollab:f,onPeers:h,onSaved:q,onWriting:V,onRendered:A,onConflictCopy:O});T.current={onStateChange:N,onCollab:f,onPeers:h,onSaved:q,onWriting:V,onRendered:A,onConflictCopy:O};const D=i.useRef(b),J=i.useRef(F);J.current=F;const re=i.useRef(v);re.current=v;const oe=i.useRef(null);i.useEffect(()=>{oe.current?.rebase(v)},[v]);const I=i.useRef(null),U=i.useRef(null);return i.useLayoutEffect(()=>{I.current=null;const g=y=>{if(!L.current||y.source!==L.current.contentWindow||I.current)return;const n=y.data;!n||typeof n!="object"||!("type"in n)||n.type!=="bd-edit:hello"||!y.ports[0]||(I.current=y.ports[0],U.current?.(y.ports[0]))};return window.addEventListener("message",g),()=>window.removeEventListener("message",g)},[o,p,d,ne]),i.useEffect(()=>{let g=null,y=!1,n=null,k;const Fe=700;de(!1),fe(!1);const Ne=setTimeout(()=>{!m&&pe.current<1&&(pe.current++,M())},11e3),qe=setTimeout(()=>fe(!0),24e3),Y=Je();let Z=!1,l=null;try{l=typeof Worker<"u"?new Worker(new URL("/assets/editexit.worker-BwVzdlZv.js",import.meta.url),{type:"module"}):null}catch{l=null}let E=!1,R=!1,K=D.current,Q=re.current,c=null;const X=()=>{R||document.activeElement!==L.current||(R=!0,l&&!E&&l.postMessage({type:"interacted"}))};let se=!1;const $=()=>{se=!0,X(),!(!l||E||!R)&&l.postMessage({type:"parent-unload"})},he=e=>{if(!se&&!e.persisted||(se=!1,!m||!l||E||!c))return;const t=new MessageChannel;l.postMessage({type:"rearm",savedText:K,baseSha:Q,hasBaseSha:!0,docText:ye(),interacted:R},[t.port1]),c.postMessage({type:"bd-edit:port"},[t.port2])},ye=()=>n?n.getText("body").toString():oe.current?.collab.text.toString()??"",ee=()=>{!l||E||l.postMessage({type:"sync",savedText:K,baseSha:Q,hasBaseSha:!0,docText:ye()})},xe=()=>{!l||E||(E=!0,l.postMessage({type:"disarm"}),l.terminate())},M=()=>{xe(),c?.close(),c=null,Ce(e=>e+1)},Ae=e=>{if(!l||E||!c)return;const t=new MessageChannel;l.postMessage({type:"arm",apiBase:o,path:p,who:J.current?.name,renderText:e,renderLen:e.length,allowedRanges:[...x.keys()],savedText:K,baseSha:Q,docText:e,interacted:R},[t.port1]),c.postMessage({type:"bd-edit:port"},[t.port2])},me=e=>{typeof e.seq=="number"&&c?.postMessage({type:"bd-edit:ack",seq:e.seq})},De=async e=>{const t=L.current,s=c;if(!t||!s)return;let a=!1;const r=()=>{a=!0};t.addEventListener("load",r);try{await Y.drain(S=>s.postMessage(S),()=>!Z||a||L.current!==t||c!==s,e)}finally{t.removeEventListener("load",r)}clearTimeout(k),k=void 0},H=new Map,ge=async()=>{const e=c;if(!e)return()=>{};H.set(e,(H.get(e)??0)+1);let t=!1;const s=()=>{if(t)return;t=!0;const a=(H.get(e)??1)-1;if(a>0){H.set(e,a);return}H.delete(e),e.postMessage({type:"bd-edit:unlock"})};try{await De(!0)}catch(a){throw s(),a}return s},u=oe.current=Be({apiBase:o,path:p,seed:D.current,baseSha:re.current,who:J.current?.name,me:J.current,onConflictCopy:e=>T.current.onConflictCopy?.(e),onShrinkRefused:e=>Ge(p,e),onShrinkWithdrawn:_e,beforeJoin:async()=>n?ge():()=>{},onReady:()=>{if(clearTimeout(k),k=void 0,n){const e=n;n=null;const t=e.getText("body").toString(),s=u.collab.text.toString();if(m&&t===s)for(const[a,r]of x){const S=C(r.from,e),_=C(r.to,e);S&&_&&x.set(a,{from:te(u.collab.text,S.index),to:te(u.collab.text,_.index),span:r.span,orig:r.orig})}else x.clear(),m=!1,t!==s&&M();e.destroy()}y=!0,P()},onSolo:()=>{u.collab.text.length||u.collab.text.insert(0,D.current),y=!0,P()},onStalled:()=>{y||n||(n=new Oe,n.getText("body").insert(0,D.current),y=!0,P())},onState:e=>T.current.onStateChange?.(e),onCollab:e=>T.current.onCollab?.(e),onPeers:e=>T.current.onPeers?.(e),onSaved:e=>T.current.onSaved?.(e),onWriting:()=>T.current.onWriting?.(),onBaseChange:(e,t)=>{K=e,Q=t,ee()},soloText:()=>n?n.getText("body").toString():D.current,soloApply:({from:e,to:t,insert:s})=>{n&&n.transact(()=>{const a=n.getText("body");t>e&&a.delete(e,t-e),s&&a.insert(e,s)})}});let we=null;const be={...u,saveNow:()=>{let e=()=>{};return we??=Ue(async()=>{e=await ge()},()=>u.saveNow(),()=>e()).finally(()=>{we=null})}};z&&(z.current=be);const x=new Map,ve=e=>e.start+","+e.end,P=async()=>{if(m||!g||!y)return;const e=n?n.getText("body"):u.collab.text,t=e.toString();if(!t)return;if(g.some(r=>r.end>t.length||r.start>r.end)){g=null,M();return}const s=await Ye(t);if(s!==null?s!==Te:ae>=0&&t.length!==ae){g=null,M();return}x.clear();for(const r of g)x.set(ve(r),{from:te(e,r.start),to:te(e,r.end),span:r.end-r.start,orig:t.slice(r.start,r.end)});m=!0,Ae(t),de(!0),T.current.onRendered?.()};let Te="",ae=-1,m=!1;const Ie=e=>{if(e.type==="bd-edit:flushed"){Y.flushed(e.id);return}if(e.type==="bd-edit:clobbered"){Pe("This page rewrites itself as it runs, and it replaced the part you were editing. That edit was not saved.");return}if(e.type==="bd-edit:ready")return m=!1,x.clear(),g=e.ranges,Te=e.hash,ae=e.len,Z=!0,P();if(e.type==="bd-edit:patch"&&(X(),!!R)){if(!m)return P().then(()=>{Se(e)&&(me(e),ee())});Se(e)&&(me(e),ee())}},Se=e=>{const t=x.get(ve(e));if(!t)return!1;if(n){const w=C(t.from,n),G=C(t.to,n);if(!w||!G||w.index>G.index)return!1;const B=n.getText("body"),He=G.index-w.index;if(w.index===0&&G.index===B.length&&t.spant.span*4+256)return x.clear(),m=!1,M(),!1;const ce=B.toString().slice(w.index,G.index),Le=Re(t.orig,ce,e.html);return t.orig=e.html,ce===Le||(n.transact(()=>{for(const W of Me(ce,Le))W.deleteCount>0&&B.delete(w.index+W.index,W.deleteCount),W.insertText&&B.insert(w.index+W.index,W.insertText)}),T.current.onStateChange?.("dirty"),clearTimeout(k),k=setTimeout(()=>{u.saveNow()},Fe)),!0}const s=u.collab.doc,a=C(t.from,s),r=C(t.to,s);if(!a||!r||a.index>r.index)return!1;const S=u.collab.text,_=r.index-a.index;if(a.index===0&&r.index===S.length&&t.spant.span*4+256)return console.warn("bdrive: refusing an implausible patch range",{span:_,stamped:t.span,docLength:S.length}),x.clear(),m=!1,M(),!1;const le=S.toString().slice(a.index,r.index),Ee=Re(t.orig,le,e.html);return t.orig=e.html,le===Ee||u.collab.applySplices(Me(le,Ee).map(w=>({...w,index:w.index+a.index}))),!0},ie=e=>{c!==e&&(c?.close(),c=e,m=!1,g=null,x.clear(),Z=!1,e.onmessage=t=>{const s=t.data;!s||typeof s!="object"||Y.enqueue(()=>Ie(s))})},ke=()=>{ee(),P()};return u.collab.text.observe(ke),U.current=ie,I.current&&ie(I.current),window.addEventListener("blur",X),window.addEventListener("beforeunload",$),window.addEventListener("pagehide",$),window.addEventListener("pageshow",he),()=>{z?.current===be&&(z.current=null),U.current===ie&&(U.current=null),window.removeEventListener("blur",X),window.removeEventListener("beforeunload",$),window.removeEventListener("pagehide",$),window.removeEventListener("pageshow",he),Z=!1,Y.close(),clearTimeout(Ne),clearTimeout(qe),clearTimeout(k),u.collab.text.unobserve(ke),setTimeout(()=>{c?.close(),c=null,clearTimeout(k),u.destroy(),xe(),n?.destroy()},300)}},[o,p,ne]),j.jsxs(j.Fragment,{children:[ue&&j.jsx("div",{id:"edit-clobbered",className:"banner",children:ue}),je&&!We&&j.jsxs("div",{id:"edit-not-ready",className:"banner",children:["This file could not be opened for editing — the shared document never loaded. Reload the page to try again, or use ",j.jsx("b",{children:"Edit source"}),"."]}),j.jsx("iframe",{ref:L,className:"htmlview",sandbox:"allow-scripts",src:d+(d.includes("?")?"&":"?")+"edit=1",title:p},ne)]})}export{tt as VisualEdit}; diff --git a/internal/webapp/static/assets/editexit.worker-BwVzdlZv.js b/internal/webapp/static/assets/editexit.worker-BwVzdlZv.js new file mode 100644 index 00000000..2917927f --- /dev/null +++ b/internal/webapp/static/assets/editexit.worker-BwVzdlZv.js @@ -0,0 +1,11 @@ +(function(){"use strict";function q(e,t,n){const r=p=>String(p).padStart(2,"0"),o=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+o,i=e.lastIndexOf("/"),h=i<0?"":e.slice(0,i+1),v=i<0?e:e.slice(i+1);return h+v.slice(0,Math.max(0,255-l.length))+l}function J(e){return/\/p\/[^/]+\/$/.test(e)}const Z=4e3;function F(e,t){let n=0;for(;n0?p[s-1]:null,g=new Int32Array(2*s+1);for(let d=-s;d<=s;d+=2){let c;s===0?c=0:d===-s||d!==s&&a[d-1+s-1]=o&&T>=l){b=s;break}}p.push(g)}if(b<0)return[{aS:n,aE:n+o,bS:n,bE:n+l}];const y=[];let A=o,S=l;for(let s=b;s>0;s--){const a=p[s-1],g=A-S,d=g===-s||g!==s&&a[g-1+s-1]m&&S>H;)A--,S--,y.push(A,S);A=c,S=T}for(;A>0&&S>0;)A--,S--,y.push(A,S);const _=[];let E=0,f=0;for(let s=y.length-2;s>=0;s-=2){const a=y[s],g=y[s+1];(a>E||g>f)&&_.push({aS:n+E,aE:n+a,bS:n+f,bE:n+g}),E=a+1,f=g+1}return(El.startsWith(i)&&(i===""||i.endsWith(` +`)||l[i.length]===` +`);return e.length>=t.length&&o(e,t)?e:t.length>e.length&&o(t,e)?t:null}return n?Q(e,t)<=0?e+t:t+e:null}function L(e,t,n,r,o=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const l=new Map,i=U(e,r),h=U(t,r),v=U(n,r),p=B(i,l),b=[...F(p,B(h,l)).map(f=>({h:f,toks:h,side:0})),...F(p,B(v,l)).map(f=>({h:f,toks:v,side:1}))];b.sort((f,s)=>f.h.aS-s.h.aS||f.h.aE-s.h.aE||f.side-s.side);const y=(f,s,a)=>f.slice(s,a).join(""),A=(f,s,a,g)=>{let d="",c=a;for(const T of f)T.side===s&&(d+=y(i,c,T.h.aS)+y(T.toks,T.h.bS,T.h.bE),c=T.h.aE);return d+y(i,c,g)};let S="",_=0,E=0;for(;Em.side)).size===1){S+=A(f,f[0].side,s,a);continue}const d=A(f,0,s,a),c=A(f,1,s,a);if(d===c){S+=d;continue}if(s===a){const m=ee(d,c,r!==N,i.length===0);if(m===null){if(!o)return null;S+=c;continue}S+=m;continue}if(r===N)return null;const T=r===z?L(y(i,s,a),d,c,N):L(y(i,s,a),d,c,r+1,o);if(T===null){if(!o)return null;S+=c;continue}S+=T}return S+y(i,_,i.length)}const W=e=>e===""||e.endsWith(` +`)?e:e+` +`;function te(e,t,n,r){let o=t.endsWith(` +`);return o===e.endsWith(` +`)&&(o=n.endsWith(` +`)),r===""||o===r.endsWith(` +`)?r:o?r+` +`:r.slice(0,-1)}function ne(e,t,n){const r=L(W(e),W(t),W(n),K);return r===null?{ok:!1}:{ok:!0,text:te(e,t,n,r)}}function re(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),r=n.lastIndexOf("."),o=r>=0?n.slice(r).toLowerCase():"",l=i=>{try{return JSON.parse(i),!0}catch{return!1}};if(o===".json")return l(t);if(o===".jsonl")for(const i of t.split(` +`)){const h=i.trim();if(h.length>0&&!l(h))return!1}return!0}function oe(e,t,n,r){const o=ne(t,n,r);return!o.ok||n===r||n===t||r===t||re(e,o.text)?o:{ok:!1}}const se=256;function le(e,t){return e<=0||t>=e?!1:t===0?!0:e>=se&&t*5new TextEncoder().encode(e).length,ie=256,ae=1<<20,X=6e4,D=(e,t)=>t>0&&t=56320&&e.charCodeAt(t)<=57343&&e.charCodeAt(t-1)>=55296&&e.charCodeAt(t-1)<=56319;function Y(e,t,n,r){if(e.length!==t||r.length<1||r.length>ie)return null;let o="",l=0;for(const{start:i,end:h,html:v}of r){if(!Number.isInteger(i)||!Number.isInteger(h)||i<=0||i>h||h>=t||itypeof p.ackedHtml=="string").map(p=>({start:p.start,end:p.end,html:p.ackedHtml})),o=r.length>0?Y(e.renderText,e.renderLen,e.allowedRanges,r):e.renderText;if(o===null)return null;const l=e.docText||e.savedText;let i=!0,h=n;if(l!==o&&l!==n){const p=oe(e.path,o,l,n);p.ok?h=p.text:i=!1}if(e.savedText.length>0&&le(I(e.savedText),I(h))||i&&h===e.savedText)return null;if(J(e.apiBase)){const p=o!==e.savedText?[o]:void 0,b=i?{base:e.baseSha,base_text:e.savedText,text:h,park_on_conflict:!0,...p?{prior_sent:p}:{}}:{base_text:e.renderText,text:n,park_on_conflict:!0},y=JSON.stringify(b);return{url:e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path),method:"POST",headers:{"Content-Type":"application/json"},body:y,keepalive:I(y)<=X}}const v="text/plain; charset=utf-8";if(i){const p={"Content-Type":v,"X-Bdrive-Park-On-Conflict":"1"};return e.baseSha&&(p["If-Match"]=`"${e.baseSha}"`),{url:e.apiBase+"upload/content?path="+encodeURIComponent(e.path),method:"PUT",headers:p,body:h,keepalive:I(h)<=X}}return{url:e.apiBase+"upload/content?path="+encodeURIComponent(q(e.path,e.who||"browser",new Date)),method:"PUT",headers:{"Content-Type":v,"If-None-Match":"*","X-Bdrive-Park-On-Conflict":"1"},body:n,keepalive:I(n)<=X}}let u=null,k=null,O=!1,M=!1,P=!1,R=!1,C=null,w,x=null;const j=()=>{if(O||M||!u||!P||!R||!C)return;const e=C;C=null,clearTimeout(w),M=!0,k?.close(),k=null;const t=u,n=ce(t,e);if(!n)return;const r=t.savedText;fetch(n.url,{method:n.method,credentials:"same-origin",headers:n.headers,body:n.body,keepalive:n.keepalive}).then(async o=>{if(!o.ok)return;const l=await o.json().catch(()=>null);if(!l||l.parked)return;const i=typeof l.text=="string"?l.text:n.method==="PUT"?n.body:null;i!==null&&(x={fromText:r,text:i,sha:l.sha},u===t&&u.savedText===r&&(u.docText===u.savedText&&(u.docText=i),u.savedText=i,typeof l.sha=="string"&&l.sha&&(u.baseSha=l.sha)))}).catch(()=>{})},$=e=>{const t=e.data;if(!(!t||t.type!=="bd-edit:exit"||!Array.isArray(t.patches))&&!(O||M||!u)){if(C=t.patches,clearTimeout(w),P&&R){j();return}w=setTimeout(()=>{C=null},500)}};self.onmessage=e=>{const t=e.data;if(!(!t||typeof t!="object"||O)){if(t.type==="arm"){u={apiBase:t.apiBase,path:t.path,who:t.who,renderText:t.renderText,renderLen:t.renderLen,allowedRanges:new Set(t.allowedRanges),savedText:t.savedText,baseSha:t.baseSha,docText:t.docText},t.interacted&&(P=!0),x=null,R=!1,C=null,clearTimeout(w),k?.close(),k=e.ports[0]??null,M=!1,k&&(k.onmessage=$);return}if(t.type==="rearm"){if(!u)return;x&&t.savedText===x.fromText?(u.savedText=x.text,x.sha&&(u.baseSha=x.sha),u.docText=t.docText===x.fromText?x.text:t.docText):(x=null,u.savedText=t.savedText,t.hasBaseSha&&(u.baseSha=t.baseSha),u.docText=t.docText),t.interacted&&(P=!0),M=!1,R=!1,C=null,clearTimeout(w),k?.close(),k=e.ports[0]??null,k&&(k.onmessage=$);return}if(t.type==="interacted"){P=!0,j();return}if(t.type==="parent-unload"){R=!0,j();return}if(t.type==="sync"){if(!u)return;typeof t.savedText=="string"?(!x||t.savedText!==x.fromText)&&(x=null,u.savedText=t.savedText,t.hasBaseSha&&(u.baseSha=t.baseSha)):t.hasBaseSha&&!x&&(u.baseSha=t.baseSha),typeof t.docText=="string"&&(u.docText=x&&t.docText===x.fromText?x.text:t.docText);return}t.type==="disarm"&&(O=!0,u=null,C=null,clearTimeout(w),k?.close(),k=null,self.close())}}})(); diff --git a/internal/webapp/static/assets/editexit.worker-D_nakb5p.js b/internal/webapp/static/assets/editexit.worker-D_nakb5p.js deleted file mode 100644 index 51b7d57a..00000000 --- a/internal/webapp/static/assets/editexit.worker-D_nakb5p.js +++ /dev/null @@ -1,11 +0,0 @@ -(function(){"use strict";function Y(e,t,n){const r=h=>String(h).padStart(2,"0"),l=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",i=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+l,s=e.lastIndexOf("/"),d=s<0?"":e.slice(0,s+1),E=s<0?e:e.slice(s+1);return d+E.slice(0,Math.max(0,255-i.length))+i}function $(e){return/\/p\/[^/]+\/$/.test(e)}const q=4e3;function H(e,t){let n=0;for(;n0?h[o-1]:null,p=new Int32Array(2*o+1);for(let f=-o;f<=o;f+=2){let a;o===0?a=0:f===-o||f!==o&&c[f-1+o-1]=l&&g>=i){S=o;break}}h.push(p)}if(S<0)return[{aS:n,aE:n+l,bS:n,bE:n+i}];const x=[];let b=l,T=i;for(let o=S;o>0;o--){const c=h[o-1],p=b-T,f=p===-o||p!==o&&c[p-1+o-1]m&&T>j;)b--,T--,x.push(b,T);b=a,T=g}for(;b>0&&T>0;)b--,T--,x.push(b,T);const I=[];let y=0,u=0;for(let o=x.length-2;o>=0;o-=2){const c=x[o],p=x[o+1];(c>y||p>u)&&I.push({aS:n+y,aE:n+c,bS:n+u,bE:n+p}),y=c+1,u=p+1}return(yi.startsWith(s)&&(s===""||s.endsWith(` -`)||i[s.length]===` -`);return e.length>=t.length&&l(e,t)?e:t.length>e.length&&l(t,e)?t:null}return n?V(e,t)<=0?e+t:t+e:null}function L(e,t,n,r,l=!1){if(t===n)return t;if(t===e)return n;if(n===e)return t;const i=new Map,s=N(e,r),d=N(t,r),E=N(n,r),h=U(s,i),S=[...H(h,U(d,i)).map(u=>({h:u,toks:d,side:0})),...H(h,U(E,i)).map(u=>({h:u,toks:E,side:1}))];S.sort((u,o)=>u.h.aS-o.h.aS||u.h.aE-o.h.aE||u.side-o.side);const x=(u,o,c)=>u.slice(o,c).join(""),b=(u,o,c,p)=>{let f="",a=c;for(const g of u)g.side===o&&(f+=x(s,a,g.h.aS)+x(g.toks,g.h.bS,g.h.bE),a=g.h.aE);return f+x(s,a,p)};let T="",I=0,y=0;for(;ym.side)).size===1){T+=b(u,u[0].side,o,c);continue}const f=b(u,0,o,c),a=b(u,1,o,c);if(f===a){T+=f;continue}if(o===c){const m=G(f,a,r!==P,s.length===0);if(m===null){if(!l)return null;T+=a;continue}T+=m;continue}if(r===P)return null;const g=r===K?L(x(s,o,c),f,a,P):L(x(s,o,c),f,a,r+1,l);if(g===null){if(!l)return null;T+=a;continue}T+=g}return T+x(s,I,s.length)}const B=e=>e===""||e.endsWith(` -`)?e:e+` -`;function Q(e,t,n,r){let l=t.endsWith(` -`);return l===e.endsWith(` -`)&&(l=n.endsWith(` -`)),r===""||l===r.endsWith(` -`)?r:l?r+` -`:r.slice(0,-1)}function ee(e,t,n){const r=L(B(e),B(t),B(n),F);return r===null?{ok:!1}:{ok:!0,text:Q(e,t,n,r)}}function te(e,t){const n=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1),r=n.lastIndexOf("."),l=r>=0?n.slice(r).toLowerCase():"",i=s=>{try{return JSON.parse(s),!0}catch{return!1}};if(l===".json")return i(t);if(l===".jsonl")for(const s of t.split(` -`)){const d=s.trim();if(d.length>0&&!i(d))return!1}return!0}function ne(e,t,n,r){const l=ee(t,n,r);return!l.ok||n===r||n===t||r===t||te(e,l.text)?l:{ok:!1}}const re=256;function oe(e,t){return e<=0||t>=e?!1:t===0?!0:e>=re&&t*5new TextEncoder().encode(e).length,le=256,se=1<<20,W=6e4,z=(e,t)=>t>0&&t=56320&&e.charCodeAt(t)<=57343&&e.charCodeAt(t-1)>=55296&&e.charCodeAt(t-1)<=56319;function D(e,t,n,r){if(e.length!==t||r.length<1||r.length>le)return null;let l="",i=0;for(const{start:s,end:d,html:E}of r){if(!Number.isInteger(s)||!Number.isInteger(d)||s<=0||s>d||d>=t||stypeof h.ackedHtml=="string").map(h=>({start:h.start,end:h.end,html:h.ackedHtml})),l=r.length>0?D(e.renderText,e.renderLen,e.allowedRanges,r):e.renderText;if(l===null)return null;const i=e.docText||e.savedText;let s=!0,d=n;if(i!==l&&i!==n){const h=ne(e.path,l,i,n);h.ok?d=h.text:s=!1}if(e.savedText.length>0&&oe(_(e.savedText),_(d))||s&&d===e.savedText)return null;if($(e.apiBase)){const h=s?{base:e.baseSha,base_text:e.savedText,text:d,park_on_conflict:!0}:{base_text:e.renderText,text:n,park_on_conflict:!0},S=JSON.stringify(h);return{url:e.apiBase+"ycollab/sync?path="+encodeURIComponent(e.path),method:"POST",headers:{"Content-Type":"application/json"},body:S,keepalive:_(S)<=W}}const E="text/plain; charset=utf-8";if(s){const h={"Content-Type":E,"X-Bdrive-Park-On-Conflict":"1"};return e.baseSha&&(h["If-Match"]=`"${e.baseSha}"`),{url:e.apiBase+"upload/content?path="+encodeURIComponent(e.path),method:"PUT",headers:h,body:d,keepalive:_(d)<=W}}return{url:e.apiBase+"upload/content?path="+encodeURIComponent(Y(e.path,e.who||"browser",new Date)),method:"PUT",headers:{"Content-Type":E,"If-None-Match":"*","X-Bdrive-Park-On-Conflict":"1"},body:n,keepalive:_(n)<=W}}let A=null,k=null,w=!1,M=!1,R=!1,O=!1,C=null,v;const X=()=>{if(w||M||!A||!R||!O||!C)return;const e=C;C=null,clearTimeout(v),M=!0,k?.close(),k=null;const t=ie(A,e);t&&fetch(t.url,{method:t.method,credentials:"same-origin",headers:t.headers,body:t.body,keepalive:t.keepalive}).catch(()=>{})},ce=e=>{const t=e.data;if(!(!t||t.type!=="bd-edit:exit"||!Array.isArray(t.patches))&&!(w||M||!A)){if(C=t.patches,clearTimeout(v),R&&O){X();return}v=setTimeout(()=>{C=null},500)}};self.onmessage=e=>{const t=e.data;if(!(!t||typeof t!="object"||w)){if(t.type==="arm"){A={apiBase:t.apiBase,path:t.path,who:t.who,renderText:t.renderText,renderLen:t.renderLen,allowedRanges:new Set(t.allowedRanges),savedText:t.savedText,baseSha:t.baseSha,docText:t.docText},t.interacted&&(R=!0),O=!1,C=null,clearTimeout(v),k?.close(),k=e.ports[0]??null,M=!1,k&&(k.onmessage=ce);return}if(t.type==="interacted"){R=!0,X();return}if(t.type==="parent-unload"){O=!0,X();return}if(t.type==="sync"){if(!A)return;typeof t.savedText=="string"&&(A.savedText=t.savedText),t.hasBaseSha&&(A.baseSha=t.baseSha),typeof t.docText=="string"&&(A.docText=t.docText);return}t.type==="disarm"&&(w=!0,A=null,C=null,clearTimeout(v),k?.close(),k=null,self.close())}}})(); diff --git a/internal/webapp/static/assets/index-Co6en_o0.js b/internal/webapp/static/assets/index-Dgs5VYVU.js similarity index 99% rename from internal/webapp/static/assets/index-Co6en_o0.js rename to internal/webapp/static/assets/index-Dgs5VYVU.js index 929981a7..c4389704 100644 --- a/internal/webapp/static/assets/index-Co6en_o0.js +++ b/internal/webapp/static/assets/index-Dgs5VYVU.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-CeIX9UEc.js","assets/sharedfile-CR4ZqPh0.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-D6HKLJJk.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Editor-Cp12kr6p.js","assets/sharedfile-f4YTnm99.js","assets/_commonjsHelpers-CqkleIqs.js","assets/mermaid-DQuCJ8Gi.js","assets/VisualEdit-DbM9aXAX.js"])))=>i.map(i=>d[i]); import{g as PS}from"./_commonjsHelpers-CqkleIqs.js";import{_ as US,h as PR,r as UR,L as VR,D as HR}from"./mermaid-DQuCJ8Gi.js";function qR(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(i){if(i.ep)return;i.ep=!0;const l=n(i);fetch(i.href,l)}})();var Fm={exports:{}},Rl={};var Xb;function BR(){if(Xb)return Rl;Xb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var f in i)f!=="key"&&(l[f]=i[f])}else l=i;return i=l.ref,{$$typeof:e,type:r,key:u,ref:i!==void 0?i:null,props:l}}return Rl.Fragment=t,Rl.jsx=n,Rl.jsxs=n,Rl}var Wb;function GR(){return Wb||(Wb=1,Fm.exports=BR()),Fm.exports}var o=GR(),Im={exports:{}},Be={};var Jb;function KR(){if(Jb)return Be;Jb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),w=Symbol.iterator;function x(O){return O===null||typeof O!="object"?null:(O=w&&O[w]||O["@@iterator"],typeof O=="function"?O:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function _(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}_.prototype.isReactComponent={},_.prototype.setState=function(O,D){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,D,"setState")},_.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=_.prototype;function R(O,D,B){this.props=O,this.context=D,this.refs=E,this.updater=B||j}var T=R.prototype=new N;T.constructor=R,S(T,_.prototype),T.isPureReactComponent=!0;var A=Array.isArray;function M(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function U(O,D,B){var P=B.ref;return{$$typeof:e,type:O,key:D,ref:P!==void 0?P:null,props:B}}function Z(O,D){return U(O.type,D,O.props)}function X(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var D={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(B){return D[B]})}var ae=/\/+/g;function le(O,D){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):D.toString(36)}function be(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(M,M):(O.status="pending",O.then(function(D){O.status==="pending"&&(O.status="fulfilled",O.value=D)},function(D){O.status==="pending"&&(O.status="rejected",O.reason=D)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function $(O,D,B,P,I){var re=typeof O;(re==="undefined"||re==="boolean")&&(O=null);var he=!1;if(O===null)he=!0;else switch(re){case"bigint":case"string":case"number":he=!0;break;case"object":switch(O.$$typeof){case e:case t:he=!0;break;case y:return he=O._init,$(he(O._payload),D,B,P,I)}}if(he)return I=I(O),he=P===""?"."+le(O,0):P,A(I)?(B="",he!=null&&(B=he.replace(ae,"$&/")+"/"),$(I,D,B,"",function(ve){return ve})):I!=null&&(X(I)&&(I=Z(I,B+(I.key==null||O&&O.key===I.key?"":(""+I.key).replace(ae,"$&/")+"/")+he)),D.push(I)),1;he=0;var we=P===""?".":P+":";if(A(O))for(var Se=0;Se>>1,K=$[ee];if(0>>1;eei(B,V))Pi(I,B)?($[ee]=I,$[P]=V,ee=P):($[ee]=B,$[D]=V,ee=D);else if(Pi(I,V))$[ee]=I,$[P]=V,ee=P;else break e}}return q}function i($,q){var V=$.sortIndex-q.sortIndex;return V!==0?V:$.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,f=u.now();e.unstable_now=function(){return u.now()-f}}var h=[],m=[],y=1,g=null,w=3,x=!1,j=!1,S=!1,E=!1,_=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function T($){for(var q=n(m);q!==null;){if(q.callback===null)r(m);else if(q.startTime<=$)r(m),q.sortIndex=q.expirationTime,t(h,q);else break;q=n(m)}}function A($){if(S=!1,T($),!j)if(n(h)!==null)j=!0,M||(M=!0,Q());else{var q=n(m);q!==null&&be(A,q.startTime-$)}}var M=!1,L=-1,H=5,U=-1;function Z(){return E?!0:!(e.unstable_now()-U$&&Z());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,w=g.priorityLevel;var K=ee(g.expirationTime<=$);if($=e.unstable_now(),typeof K=="function"){g.callback=K,T($),q=!0;break t}g===n(h)&&r(h),T($)}else r(h);g=n(h)}if(g!==null)q=!0;else{var O=n(m);O!==null&&be(A,O.startTime-$),q=!1}}break e}finally{g=null,w=V,x=!1}q=void 0}}finally{q?Q():M=!1}}}var Q;if(typeof R=="function")Q=function(){R(X)};else if(typeof MessageChannel<"u"){var ae=new MessageChannel,le=ae.port2;ae.port1.onmessage=X,Q=function(){le.postMessage(null)}}else Q=function(){_(X,0)};function be($,q){L=_(function(){$(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):H=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_next=function($){switch(w){case 1:case 2:case 3:var q=3;break;default:q=w}var V=w;w=q;try{return $()}finally{w=V}},e.unstable_requestPaint=function(){E=!0},e.unstable_runWithPriority=function($,q){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var V=w;w=$;try{return q()}finally{w=V}},e.unstable_scheduleCallback=function($,q,V){var ee=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0ee?($.sortIndex=V,t(m,$),n(h)===null&&$===n(m)&&(S?(N(L),L=-1):S=!0,be(A,V-ee))):($.sortIndex=K,t(h,$),j||x||(j=!0,M||(M=!0,Q()))),$},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function($){var q=w;return function(){var V=w;w=q;try{return $.apply(this,arguments)}finally{w=V}}}})(Vm)),Vm}var nw;function YR(){return nw||(nw=1,Um.exports=ZR()),Um.exports}var Hm={exports:{}},kn={};var sw;function QR(){if(sw)return kn;sw=1;var e=$g();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Hm.exports=QR(),Hm.exports}var aw;function XR(){if(aw)return Ml;aw=1;var e=YR(),t=$g(),n=VS();function r(s){var a="https://react.dev/errors/"+s;if(1K||(s.current=ee[K],ee[K]=null,K--)}function B(s,a){K++,ee[K]=s.current,s.current=a}var P=O(null),I=O(null),re=O(null),he=O(null);function we(s,a){switch(B(re,a),B(I,s),B(P,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?bb(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=bb(a),s=wb(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}D(P),B(P,s)}function Se(){D(P),D(I),D(re)}function ve(s){s.memoizedState!==null&&B(he,s);var a=P.current,c=wb(a,s.type);a!==c&&(B(I,s),B(P,c))}function Me(s){I.current===s&&(D(P),D(I)),he.current===s&&(D(he),_l._currentValue=V)}var Ye,ht;function tt(s){if(Ye===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ye=a&&a[1]||"",ht=-1)":-1q2.exec(t)?.[1]===" ").map(t=>t.trim())}function GB(e,t){const n=h=>/(\d{4}-\d{2}-\d{2})[^/]*\.md$/i.exec(h)?.[1]??"",r=n(e),i=e.split("/"),l=i.slice(0,i.lastIndexOf("daily-meetings")+1).join("/")+"/";if(!r||l==="/")return null;let u=null,f="";for(const h of t){if(h===e||!h.startsWith(l))continue;const m=n(h);m&&mf&&(u=h,f=m)}return u}const yV=256;function KB(e,t){return e<=0||t>=e?!1:t===0?!0:e>=yV&&t*5new TextEncoder().encode(e).length;function bV(e){return e.split(/\s+/).filter(t=>/[\p{L}\p{N}]/u.test(t)).length}function wV(e,t=Date.now()){const n=Math.max(0,Math.round((t-e)/1e3));return n<3?"just now":n<60?`${n}s ago`:n<3600?`${Math.floor(n/60)}m ago`:new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function SV(e){let t=0;for(let n=0;nl.trim().toLowerCase().replace(/\s+/g," "),r=n(e),i=n(t);return!r||!i?!1:r===i||i.split(/[ @.]/)[0]===r}function ZB(e,t,n){const r=e.find(i=>Sg(i.name,t));return r?n.every(([i,l])=>i>=r.headingEnd&&l<=r.to):!1}function B2(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}const jg=SV;function G2({name:e,title:t}){return o.jsx("span",{className:"pavatar",title:t??e,style:{"--ph":jg(e)},children:B2(e)})}function jV({people:e,path:t}){if(!e.length)return null;const n=[...e].sort((u,f)=>{const h=t&&u.path===t?0:1,m=t&&f.path===t?0:1;return h-m}),r=n.slice(0,5),i=t?e.filter(u=>u.path===t).length:0,l=n.length-r.length;return o.jsxs("div",{id:"presence",className:"flex items-center gap-1","aria-label":"People viewing this project",children:[r.map((u,f)=>o.jsx("span",{title:u.path?`${u.name} — ${u.path}`:u.name,className:"inline-flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium ring-1 ring-black/10",style:{backgroundColor:`hsl(${jg(u.name)} 70% 88%)`,color:`hsl(${jg(u.name)} 60% 28%)`,outline:t&&u.path===t?"2px solid hsl(var(--ring))":void 0,outlineOffset:"1px"},children:B2(u.name)},u.name+f)),l>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",l]}),i>0&&o.jsxs("span",{className:"presence-count",title:`${i} ${i===1?"person is":"people are"} on this file`,children:[i," viewing"]})]})}function K2(e,t){let n;for(const r of e)t.startsWith(r.prefix)&&(!n||r.prefix.length>n.prefix.length)&&(n=r);return n}function CV(e,t,n){const r=new Array(e);return new Proxy(r,{get(i,l,u){if(typeof l=="string"){const f=l.charCodeAt(0);if(f>=48&&f<=57){const h=+l;if(Number.isInteger(h)&&h>=0&&hr[y]!==m))&&(r=f,i=t(...f),n?.onChange&&!(l&&n.skipInitialOnChange)&&n.onChange(i),l=!1),i}return u.updateDeps=f=>{r=f},u}function nS(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _V=(e,t)=>Math.abs(e-t)<1.01,EV=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}};let zl;const vp=()=>{if(zl!==void 0)return zl;if(typeof navigator>"u")return zl=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return zl=!0;const e=navigator.maxTouchPoints;return zl=navigator.platform==="MacIntel"&&e!==void 0&&e>0},sS=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},NV=e=>e,kV=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,i=new Array(r);for(let l=0;l{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=u=>{const{width:f,height:h}=u;t({width:Math.round(f),height:Math.round(h)})};if(i(sS(n)),!r.ResizeObserver)return()=>{};const l=new r.ResizeObserver(u=>{const f=()=>{const h=u[0];if(h?.borderBoxSize){const m=h.borderBoxSize[0];if(m){i({width:m.inlineSize,height:m.blockSize});return}}i(sS(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()});return l.observe(n,{box:"border-box"}),()=>{l.unobserve(n)}},Fd={passive:!0},MV=typeof window>"u"?!0:"onscrollend"in window,TV=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const l=e.options.useScrollendEvent&&MV;let u=0;const f=l?null:EV(i,()=>t(u,!1),e.options.isScrollingResetDelay),h=g=>()=>{u=n(r),f?.(),t(u,g)},m=h(!0),y=h(!1);return r.addEventListener("scroll",m,Fd),l&&r.addEventListener("scrollend",y,Fd),()=>{r.removeEventListener("scroll",m),l&&r.removeEventListener("scrollend",y)}},OV=(e,t)=>TV(e,t,n=>{const{horizontal:r,isRtl:i}=e.options;return r?n.scrollLeft*(i&&-1||1):n.scrollTop}),AV=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),i=n.options.getItemKey(r);return n.itemSizeCache.get(i)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),i=n.options.getItemKey(r),l=n.itemSizeCache.get(i);if(l!==void 0)return l}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},DV=(e,{adjustments:t=0,behavior:n},r)=>{var i,l;(l=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||l.call(i,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},zV=DV;class LV{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(l=>{const u=()=>{const f=l.target,h=this.indexFromElement(f);if(!f.isConnected){this.observer.unobserve(f);for(const[m,y]of this.elementsCache)if(y===f){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(f,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var l;return(l=r())==null?void 0:l.observe(i,{box:"border-box"})},unobserve:i=>{var l;return(l=r())==null?void 0:l.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{var r,i;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NV,rangeExtractor:kV,onChange:()=>{},measureElement:AV,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const w in n){const x=n[w];x!==void 0&&(l[w]=x)}const u=this.options;let f=null,h=null,m=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const w=u.count,x=l.count,j=this.getMeasurements(),S=w>0?((r=j[0])==null?void 0:r.key)??u.getItemKey(0):null,E=w>0?((i=j[w-1])==null?void 0:i.key)??u.getItemKey(w-1):null;if(x!==w||w>0&&x>0&&(l.getItemKey(0)!==S||l.getItemKey(x-1)!==E)){m=!0;const R=w>0?this.getVirtualItemForOffset(this.getScrollOffset())??j[0]:null;R&&(f=[R.key,this.getScrollOffset()-R.start]);const T=l.followOnAppend===!0?"auto":l.followOnAppend||null;T&&x>w&&this.isAtEnd(u.scrollEndThreshold)&&(w===0||l.getItemKey(x-1)!==E)&&(h=T)}}this.options=l,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,g=0;if(f&&this.scrollOffset!==null){const[w,x]=f,j=this.getMeasurements(),{count:S,getItemKey:E}=this.options;let _=0;for(;_{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=go(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const f=this.getScrollOffset();this.scrollDirection=u?f===l?this.scrollDirection:f{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},f=()=>{this._iosTouching=!1,!(!vp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Fd),l.addEventListener("touchend",f,Fd),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",f),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const i=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,i&&this.scrollElement&&this.options.enabled){const[l,u,f,h]=i;l!==null&&!f&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?h!==0&&(this._iosDeferredAdjustment+=h):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),f&&this.scrollToEnd({behavior:f})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const i=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=i,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=go(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,i,l,u,f,h,m)=>(this.prevLanes!==void 0&&this.prevLanes!==f&&(this.lanesChangedFlag=!0),this.prevLanes=f,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m}),{key:!1}),this.getMeasurements=go(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:i,getItemKey:l,enabled:u,lanes:f,laneAssignmentMode:h,gap:m},y)=>{const g=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const _ of this.laneAssignments.keys())_>=n&&this.laneAssignments.delete(_);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(_=>{this.itemSizeCache.set(_.key,_.size)}));const w=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),f===1){const _=n*2;let N=this._flatMeasurements;if(!N||N.length<_){const A=new Float64Array(_);N&&w>0&&A.set(N.subarray(0,w*2)),N=A,this._flatMeasurements=N}let R;if(w===0)R=r+i;else{const A=w-1;R=N[A*2]+N[A*2+1]+m}for(let A=w;A1){T=R;const Z=j[T],X=Z!==void 0?x[Z]:void 0;A=X?X.end+m:r+i}else if(E===f){let Z=0,X=S[0],Q=j[0];for(let ae=1;aethis.options.debug}),this.calculateRange=go(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,l)=>n.length===0||r===0?(this.range=null,null):(this.range=FV(n,r,i,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=go(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,l,u)=>l===null||u===null?[]:n({startIndex:l,endIndex:u,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,i-l),f=Math.min(this.options.count-1,i+l);return n>=u&&n<=f}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((u,f)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(f))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i,l;if(n<0||n>=this.options.count)return;let u,f,h;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)h=this.options.getItemKey(n),f=m[n*2],u=m[n*2+1];else{const w=this.measurementsCache[n];if(!w)return;h=w.key,f=w.start,u=w.size}const y=this.itemSizeCache.get(h)??u,g=r-y;if(g!==0){const w=this.options.anchorTo==="end"&&((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=w?this.getTotalSize():0,j=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:h,start:f,size:u,end:f+u,lane:0},g,this):f[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let l=0,u=n.length;lthis.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const i=this._flatMeasurements,l=this.options.lanes===1&&i!=null,u=Z2(0,r.length-1,l?f=>i[f*2]:f=>nS(r[f]).start,n);return nS(r[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=n>=u+l?"end":"start"),r==="center"?n+=(i-l)/2:r==="end"&&(n-=l);const f=this.getMaxScrollOffset();return Math.max(Math.min(f,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[n];if(!u)return;if(r==="auto")if(u.end>=l+i-this.options.scrollPaddingEnd)r="end";else if(u.start<=l+this.options.scrollPaddingStart)r="start";else return[l,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const f=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(f,r,u.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const l=this.getOffsetForAlignment(n,r),u=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const l=this.getOffsetForIndex(n,r);if(!l)return;const[u,f]=l,h=this.now();this.scrollState={index:n,align:f,behavior:i,startedAt:h,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,l=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:l,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1){const l=r.length-1,u=this._flatMeasurements;u!=null?i=u[l*2]+u[l*2+1]:i=((n=r[l])==null?void 0:n.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&l.some(f=>f===null);){const f=r[u];l[f.lane]===null&&(l[f.lane]=f.end),u--}i=Math.max(...l.filter(f=>f!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const i of r)i&&this.itemSizeCache.has(i.key)&&n.push({index:i.index,key:i.key,start:i.start,size:i.size,end:i.end,lane:i.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(vp()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,l=1,u=i!==this.scrollState.lastTargetOffset;if(!u&&_V(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==i&&this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const f=this.getSize()||600,h=Math.abs(i-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&h>f;this.scrollState.lastTargetOffset=i,m||(this.scrollState.behavior="auto"),this._scrollToOffset(i,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Z2=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,l=n(i);if(lr)t=i-1;else return i}return e>0?e-1:0};function $V(e,t,n){let r=0;for(;r<=t;){const i=(r+t)/2|0,l=e[i*2];if(ln)t=i-1;else return i}return r>0?r-1:0}function FV(e,t,n,r,i){const l=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:l};if(r===1&&i!==null){const m=$V(i,l,n);let y=m;const g=n+t;for(;ye[m].start,n),h=f;if(r===1)for(;h1){const m=Array(r).fill(0);for(;hg=0&&y.some(g=>g>=n);){const g=e[f];y[g.lane]=g.start,f--}f=Math.max(0,f-f%r),h=Math.min(l,h+(r-1-h%r))}return{startIndex:f,endIndex:h}}const yp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function IV({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const i=b.useReducer(m=>m+1,0)[1],l=b.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=n;const u=m=>{const y=l.current;if(!y.enabled||!y.container)return;const g=m.getTotalSize();if(g!==y.lastSize){y.lastSize=g;const _=m.options.horizontal?"width":"height";y.container.style[_]=`${g}px`}const w=!!m.options.horizontal,x=y.mode==="transform",j=w?"left":"top",S=m.options.scrollMargin,E=m.getVirtualItems();for(const _ of E){const N=_.start-S,R=m.elementsCache.get(_.key);R&&y.lastPositions.get(R)!==N&&(y.lastPositions.set(R,N),x?R.style.transform=w?`translate3d(${N}px, 0, 0)`:`translate3d(0, ${N}px, 0)`:R.style[j]=`${N}px`)}},f={...r,onChange:(m,y)=>{var g;const w=l.current;let x=!0;if(w.enabled){u(m);const j=m.range,S=w.prevRange;x=!S||S.isScrolling!==m.isScrolling||S.startIndex!==j?.startIndex||S.endIndex!==j?.endIndex,x&&(w.prevRange=j?{startIndex:j.startIndex,endIndex:j.endIndex,isScrolling:m.isScrolling}:null)}x&&(e&&y?rc.flushSync(i):i()),(g=r.onChange)==null||g.call(r,m,y)}},[h]=b.useState(()=>{const m=new LV(f);return Object.assign(m,{containerRef:y=>{const g=l.current;if(g.container=y,g.lastSize=null,y&&g.enabled){const w=m.getTotalSize();g.lastSize=w;const x=m.options.horizontal?"width":"height";y.style[x]=`${w}px`}}})});return h.setOptions(f),yp(()=>h._didMount(),[]),yp(()=>h._willUpdate()),yp(()=>{u(h)}),h}function PV(e){return IV({observeElementRect:RV,observeElementOffset:OV,scrollToFn:zV,...e})}function UV({...e}){return o.jsx(nz,{"data-slot":"context-menu",...e})}function VV({...e}){return o.jsx(sz,{"data-slot":"context-menu-trigger",...e})}function HV({className:e,...t}){return o.jsx(rz,{children:o.jsx(az,{"data-slot":"context-menu-content",className:at("z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})})}function qV({className:e,inset:t,variant:n="default",...r}){return o.jsx(iz,{"data-slot":"context-menu-item","data-inset":t,"data-variant":n,className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function BV({className:e,...t}){return o.jsx(oz,{"data-slot":"context-menu-separator",className:at("-mx-1 my-1 h-px bg-border",e),...t})}function GV({className:e,...t}){return o.jsx("span",{"data-slot":"context-menu-shortcut",className:at("ml-auto text-xs tracking-widest text-muted-foreground",e),...t})}const KV=/\.bdrive-conflict-([A-Za-z0-9_-]{0,32})-(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;function Vr(e){const t=KV.exec(e);if(!t)return null;const[,n,r,i,l,u,f,h]=t,m=new Date(Date.UTC(+r,+i-1,+l,+u,+f,+h));return m.getUTCFullYear()!==+r||m.getUTCMonth()!==+i-1||m.getUTCDate()!==+l||m.getUTCHours()!==+u||m.getUTCMinutes()!==+f||m.getUTCSeconds()!==+h?null:{original:e.slice(0,t.index),device:n,when:m}}function YB(e,t,n){const r=m=>String(m).padStart(2,"0"),i=String(n.getUTCFullYear())+r(n.getUTCMonth()+1)+r(n.getUTCDate())+"T"+r(n.getUTCHours())+r(n.getUTCMinutes())+r(n.getUTCSeconds())+"Z",l=".bdrive-conflict-"+t.replace(/[^A-Za-z0-9_-]/g,"-").slice(0,32)+"-"+i,u=e.lastIndexOf("/"),f=u<0?"":e.slice(0,u+1),h=u<0?e:e.slice(u+1);return f+h.slice(0,Math.max(0,255-l.length))+l}const Y2=-.005,Cg=-.005,Q2=-.01,_g=1,Vl=[0,.9,.8,.6,.7],ZV=.5,YV=2,QV=1,XV=5,WV=5,JV=/[\p{M}\u1160-\u11ff\ud7b0-\ud7ff]/u;function eH(e){if(!/[^\x00-\x7f]/.test(e)||e.normalize("NFC")===e){const l=e.toLowerCase();if(l.length===e.length)return{text:l,cased:e,from:null,to:null}}let t="",n="";const r=[],i=[];for(let l=0;l65535?2:1);for(;u65535?2:1}const f=e.slice(l,u),h=f.normalize("NFC");let m=h.toLowerCase();m.length!==h.length&&(m=h),t+=m,n+=h;const y=f.length===1&&h.length===1;for(let g=0;g=97&&e<=122?1<=48&&e<=57?1<<26:0}function nH(e,t){return e===47?1:e===45||e===95||e===32?2:e===46?3:e>=97&&e<=122&&t>=65&&t<=90?4:0}const Wu=new Map,sH=2e5;function W2(e){let t=Wu.get(e);if(t)return t;const{text:n,cased:r,from:i,to:l}=eH(e),u=n.lastIndexOf("/")+1,f=new Uint8Array(n.length);let h=0,m=0,y=47;for(let x=0;x=u&&(m|=S)}const g=n.slice(u),w=g.lastIndexOf(".");return t={label:e,text:n,bonus:f,name:u,base:g,stem:w>0?g.slice(0,w):g,mask:h,nameMask:m,from:i,to:l},Wu.size>=sH&&Wu.clear(),Wu.set(e,t),t}let Hl=new Int32Array(64);function aS(e,t,n){Hl.length0&&(N=Math.max(h[y+_-1]+Vl[f[n+_]],h[m+_-1]+_g)),h[g+_]=N,h[w+_]=E=Math.max(N,E+S)}else h[g+_]=-1/0,h[w+_]=E=E+S;[m,g]=[g,m],[y,w]=[w,y]}return h[y+l-1]}function aH(e,t,n,r){const i=e.length,l=t.text.length-n,{text:u,bonus:f}=t,h=new Float64Array(i*l),m=new Float64Array(i*l);for(let w=0;w0&&(N=Math.max(m[_-l-1]+Vl[f[n+E]],h[_-l-1]+_g)),h[_]=N,m[_]=S=Math.max(N,S+j)}else h[_]=-1/0,m[_]=S=S+j}}const y=new Array(i);let g=!1;for(let w=i-1,x=l-1;w>=0;w--)for(;x>=0;x--){const j=w*l+x;if(h[j]!==-1/0&&(g||h[j]===m[j])){g=w>0&&x>0&&m[j]===h[j-l-1]+_g,y[w]=n+x--;break}}return r.push(...y),m[i*l-1]}function iH(e){const t=tH(e);if(!t)return null;const n=t.split(/\s+/).map(r=>{const i=[];if(r.length>=WV){const l=new Set;for(let u=0;u=0;i--){const u=ya[i+1]>n?t.lastIndexOf(e[i],ya[i+1]-1):-1;if(u=0;i--)ya[i]=-1;let l=n;for(let u=0;u=l)return!0;if(l=t.indexOf(e[u],l)+1,l===0)return!1}return!0}function lH(e,t,n,r){if(!oH(e.text,t.text,n?t.name:0))return-1/0;let i=-1/0,l=-1;for(let u=0;ui&&(i=f,l=u)}return l<0?-1/0:(r&&Eg(e.drops[l].text,e.drops[l].mask,t,n,r),i-QV)}function bp(e,t,n,r){let i=0,l=!1;for(const u of e.tokens){let f=Eg(u.text,u.mask,t,n.nameOnly,r);if(f===-1/0&&n.typo&&!l){const h=u.mask&~(n.nameOnly?t.nameMask:t.mask);(h&h-1)===0&&(f=lH(u,t,n.nameOnly,r)),l=!0}if(f===-1/0)return-1/0;i+=f}return n.typo&&!l?-1/0:((e.whole===t.stem||e.whole===t.base)&&(i+=YV),i)}class wp{idx=[];score=[];limit;items;constructor(t,n){this.limit=t,this.items=n}better(t,n,r){const i=this.score[r];if(t!==i)return t>i;const l=this.items[n].label.length,u=this.items[this.idx[r]].label.length;return l!==u?l0&&this.better(n,t,r-1);)r--;this.idx.splice(r,0,t),this.score.splice(r,0,n),this.idx.length>this.limit&&(this.idx.pop(),this.score.pop())}}}function cH(e,t){e.sort((r,i)=>r-i);const n=[];for(const r of e){const i=t.from?t.from[r]:r,l=t.to?t.to[r]:r+1,u=n[n.length-1];u&&i<=u[1]?u[1]=Math.max(u[1],l):n.push([i,l])}return n}function J2(e,t,{limit:n=40,nameOnly:r=!1}={}){const i=iH(e);if(!i)return{hits:[],total:0};const l={nameOnly:r,typo:!1},u=new wp(n,t),f=[];let h=0;for(let S=0;S0,typo:!0},y=new wp(XV,t);if(i.tokens.some(S=>S.drops.length))for(const S of f){const E=bp(i,t[S],m);E!==-1/0&&y.add(S,E)}const g=new wp(n,t);u.idx.forEach((S,E)=>g.add(S,u.score[E]));const w=h?u.score[0]:-1/0,x=new Set;return y.idx.forEach((S,E)=>{y.score[E]>w&&(x.add(S),g.add(S,y.score[E]))}),{hits:g.idx.map((S,E)=>{const _=[];return bp(i,t[S],x.has(S)?m:l,_),{index:S,score:g.score[E],ranges:cH(_,t[S])}}),total:h+x.size}}const uH=[/^\./,/^_lint\.py$/];function oS(e){return uH.some(t=>t.test(e))}const dH=5;function eN(e){return"\0sys:"+e}const fH=e=>e&&Date.parse(e)||0;function hH(e,t){const n=new Map,r=new Map,i=new Map,l=new Set,u=[],f=h=>{let m=0,y=0;for(const g of h.children||[])if(g.dir){const[w,x]=f(g);m+=w,y=Math.max(y,x)}else{l.add(g.path),Vr(g.path)&&u.push(g.path);const w=fH(g.time);i.set(g.path,w),t>0&&w>t&&m++,y=Math.max(y,w)}return h.path&&(r.set(h.path,m),i.set(h.path,y)),[m,y]};e&&f(e);for(const h of u){const m=Vr(h).original;l.has(m)&&n.set(m,(n.get(m)||0)+1)}return{conflicts:n,fresh:r,latest:i}}function mH(e,t){const n=Vr(e);return!!n&&t.conflicts.has(n.original)}function pH(e,t){const{expanded:n,showAll:r,stats:i,keep:l=""}=t,u=t.cap??dH,f=[],h=(w,x)=>(i.latest.get(x.path)||0)-(i.latest.get(w.path)||0),m=w=>l===w||l.startsWith(w+"/"),y=(w,x)=>{for(const j of w)f.push({kind:"node",node:j,depth:x,conflicts:j.dir?0:i.conflicts.get(j.path)||0,fresh:j.dir&&i.fresh.get(j.path)||0}),j.dir&&n.has(j.path)&&g(j,x+1)},g=(w,x)=>{const j=(w.children||[]).filter(_=>!mH(_.path,i)),S=j.filter(_=>!oS(_.name));t.order==="recent"&&S.sort(h);const E=j.filter(_=>oS(_.name));if(x>0&&S.length>u&&!r.has(w.path)){const _=[...S].sort(h),N=new Set([..._.slice(0,u),..._.slice(u).filter(A=>m(A.path))]),R=_.slice(0,u),T=_.slice(u).filter(A=>m(A.path));y(S.filter(A=>N.has(A)),x),f.push({kind:"more",parent:w.path,depth:x,hidden:S.length-R.length-T.length})}else y(S,x);if(E.length){const _=eN(w.path),N=n.has(_)||E.some(R=>m(R.path));f.push({kind:"system",parent:w.path,depth:x,count:E.length,open:N}),N&&y(E,x+1)}};return e&&g(e,0),f}const gH=5,vH=100;function yH(e,t,n){const r=(u,f,h)=>{const{hits:m,total:y}=J2(e,u.map(W2),{limit:h,nameOnly:!0});return{list:m.map(w=>{const x=u[w.index],j=x.lastIndexOf("/")+1;return{path:x,name:x.slice(j),dir:f,ranges:w.ranges.map(([S,E])=>[S-j,E-j])}}),total:y}},i=r([...t],!0,gH),l=r([...n].map(u=>u.path).filter(u=>!Vr(u)),!1,vH);return{folders:i.list,files:l.list,folderCount:i.total,fileCount:l.total}}function tN(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t+1)}function Ng({text:e,ranges:t,offset:n=0,className:r,tag:i="b"}){const l=[];let u=0;for(const[f,h]of t){const m=Math.max(f-n,u),y=Math.min(h-n,e.length);y<=m||(m>u&&l.push(e.slice(u,m)),l.push(o.jsx(i,{children:e.slice(m,y)},m)),u=y)}return un.open(e),children:[o.jsx(ge,{name:t?"folderopen":"doc"})," ",t?"Open folder":"Open",o.jsx(u,{children:"↵"})]}),n.newFile&&(n.canCreateIn?.(f)??!0)&&o.jsxs(i,{onSelect:()=>n.newFile(f),children:[o.jsx(ge,{name:"fileplus"})," New file"]}),n.togglePin&&o.jsxs(i,{onSelect:()=>n.togglePin(e),children:[o.jsx(ge,{name:"star"})," ",n.pinned?.(e)?"Unpin":"Pin to sidebar"]}),o.jsx(l,{}),o.jsxs(i,{onSelect:()=>n.copyPath(e),children:[o.jsx(ge,{name:"copy"})," Copy path"]}),n.copyShareLink&&!t&&o.jsxs(i,{onSelect:()=>n.copyShareLink(e),children:[o.jsx(ge,{name:"link"})," Copy share link"]}),(n.history||n.insights)&&o.jsx(l,{}),n.history&&o.jsxs(i,{onSelect:()=>n.history(e),children:[o.jsx(ge,{name:"hist"})," Show history"]}),n.insights&&o.jsxs(i,{onSelect:()=>n.insights(e),children:[o.jsx(ge,{name:"insights"})," View in Insights"]}),n.remove&&!t&&o.jsxs(o.Fragment,{children:[o.jsx(l,{}),o.jsxs(i,{variant:"destructive",onSelect:()=>n.remove(e),children:[o.jsx(ge,{name:"trash"})," Delete…"]})]})]})}function wH(e){const t=e.getBoundingClientRect();e.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:t.left+24,clientY:t.bottom}))}function Sp(e){return t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())}}function SH(e){const{root:t,expanded:n,onToggle:r,currentPath:i,listingShowing:l,restricted:u,stats:f,order:h,actions:m}=e,y=b.useRef(null),[g,w]=b.useState(()=>new Set),[x,j]=b.useState(null),[S,E]=b.useState(null),_=b.useRef(0),N=b.useRef(""),R=b.useRef(null),T=()=>{_.current=y.current?.scrollTop??0},A=b.useMemo(()=>pH(t,{expanded:n,showAll:g,stats:f,keep:i,order:h}),[t,n,g,f,i,h]),M=PV({count:A.length,getScrollElement:()=>y.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:U=>{const Z=A[U];return Z.kind==="node"?Z.node.path:Z.kind+":"+Z.parent}});b.useEffect(()=>{if(!i)return;const U=A.findIndex(Z=>Z.kind==="node"&&Z.node.path===i);U>=0&&M.scrollToIndex(U,{align:"auto"})},[i,A]);const L=U=>Array.from({length:U},(Z,X)=>o.jsx("span",{className:"tguide",style:{left:8+X*13+5},"aria-hidden":"true"},X)),H=(U,Z)=>({position:"absolute",top:0,left:0,right:0,transform:`translateY(${U}px)`,paddingLeft:8+Z*13});return o.jsx("nav",{id:"tree","aria-label":"Files",ref:y,onScroll:U=>{!x&&!S||Math.abs(U.currentTarget.scrollTop-_.current)<28||(x&&j(null),S&&document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0})))},children:o.jsx("div",{style:{height:M.getTotalSize(),position:"relative"},children:M.getVirtualItems().map(U=>{const Z=A[U.index];if(Z.kind==="more"){const q=()=>w(V=>new Set(V).add(Z.parent));return o.jsxs("div",{className:"row tmore",role:"button",tabIndex:0,"data-more":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsxs("span",{className:"label",children:["Show ",Z.hidden," more"]})]},U.key)}if(Z.kind==="system"){const q=()=>r(eN(Z.parent));return o.jsxs("div",{className:"row dir tsystem"+(Z.open?"":" collapsed"),role:"button",tabIndex:0,"aria-expanded":Z.open,"data-system":Z.parent,style:H(U.start,Z.depth),onClick:q,onKeyDown:Sp(q),children:[L(Z.depth),o.jsx("span",{className:"chev",children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"system"})}),o.jsx("span",{className:"label",children:"System files"}),o.jsx("span",{className:"tmeta",children:Z.count})]},U.key)}const{node:X,depth:Q,conflicts:ae,fresh:le}=Z,be=X.dir?n.has(X.path):!1,$=()=>{if(R.current===X.path){R.current=null;return}if(X.dir&&i===X.path&&l){r(X.path);return}m.open(X.path),X.dir||fs()};return o.jsxs(UV,{modal:!1,onOpenChange:q=>{q?(T(),N.current&&N.current!=="mouse"&&(R.current=X.path)):R.current===X.path&&(R.current=null),E(V=>q?X.path:V===X.path?null:V)},children:[o.jsxs(Wv,{open:x===X.path,onOpenChange:q=>{q&&T(),j(q?X.path:null)},children:[o.jsx(VV,{asChild:!0,children:o.jsxs("div",{className:"row "+(X.dir?"dir":"file")+(i===X.path?" active":"")+(X.dir&&!be?" collapsed":"")+(x===X.path||S===X.path?" menu-open":""),"data-path":X.path,tabIndex:0,role:"button",title:X.name,"aria-expanded":X.dir?be:void 0,style:H(U.start,Q),onPointerDown:q=>{N.current=q.pointerType,R.current=null},onContextMenu:()=>{N.current==="touch"&&(R.current=X.path)},onClick:$,onKeyDown:q=>{if(q.target===q.currentTarget){if(q.key==="F10"&&q.shiftKey||q.key==="ContextMenu"){q.preventDefault(),wH(q.currentTarget);return}Sp($)(q)}},children:[L(Q),o.jsx("span",{className:"chev",onClick:q=>{X.dir&&(q.stopPropagation(),r(X.path))},children:o.jsx(ge,{name:"chevd"})}),o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:X.dir?"folder":X.link?"link":"doc"})}),o.jsx("span",{className:"label",title:X.link?`${X.name} → ${X.link}`:void 0,children:X.name}),ae>0&&o.jsxs("span",{className:"tconflicts",children:["· ",ae," conflict",ae===1?"":"s"]}),X.dir&&le>0&&o.jsxs("span",{className:"tmeta tnew",children:[le," new"]}),X.dir&&u.has(X.path)&&o.jsx("span",{className:"trestricted",role:"img","aria-label":X.name+" is a restricted folder",title:"Restricted — not everyone in the workspace has the same access here",children:o.jsx(ge,{name:"lock"})}),o.jsxs("span",{className:"thover",children:[X.dir&&m.newFile&&(m.canCreateIn?.(X.path)??!0)&&o.jsx("button",{className:"tact","aria-label":"New file in "+X.name,title:"New file",tabIndex:-1,onClick:q=>{q.stopPropagation(),m.newFile(X.path)},children:o.jsx(ge,{name:"plus"})}),o.jsx(Jv,{asChild:!0,children:o.jsx("button",{className:"tact","aria-label":"Actions for "+X.name,title:"More actions",tabIndex:-1,onClick:q=>q.stopPropagation(),children:o.jsx(ge,{name:"dots"})})})]})]})}),o.jsx(ey,{className:"row-menu",align:"start",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:xH})})]}),o.jsx(HV,{className:"row-menu",onClick:q=>q.stopPropagation(),children:o.jsx(lS,{path:X.path,dir:!!X.dir,actions:m,kit:bH})})]},U.key)})})})}const jH=5,jp=8;function CH(e){const{query:t,onOpen:n}=e,{sel:r}=ly(),[i,l]=b.useState(!1);b.useEffect(()=>l(!1),[t]);const{folders:u,files:f,folderCount:h,fileCount:m}=b.useMemo(()=>yH(t,e.dirs,e.files),[t,e.dirs,e.files]),y=u.slice(0,jH),g=i?f:f.slice(0,jp),w=[...y,...g],x=t.trim();b.useEffect(()=>{DU(w.length+1,E=>{E{j.current?.querySelector(".fhit.sel")?.scrollIntoView({block:"nearest"})},[r]);const S=(E,_)=>o.jsxs("div",{className:"fhit"+(_===r?" sel":""),role:"option","aria-selected":_===r,"data-path":E.path,onMouseEnter:()=>J1(_),onClick:()=>{n(E.path),E.dir||fs()},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:E.dir?"folder":"doc"})}),o.jsxs("span",{className:"fhit-text",children:[o.jsx(Ng,{className:"fhit-name",text:E.name,ranges:E.ranges,tag:"mark"}),o.jsx("span",{className:"fhit-path",children:tN(E.path)||"/"})]}),_===r&&o.jsx("span",{className:"fhit-enter","aria-hidden":"true",children:"↵"})]},(E.dir?"d:":"f:")+E.path);return o.jsxs("nav",{id:"tree-filter","aria-label":"Matching files",ref:j,role:"listbox",children:[y.length>0&&o.jsxs("div",{className:"fgroup",children:["Folders · ",h]}),y.map((E,_)=>S(E,_)),g.length>0&&o.jsxs("div",{className:"fgroup",children:["Files · ",m]}),g.map((E,_)=>S(E,y.length+_)),!i&&f.length>jp&&o.jsxs("button",{className:"fmore",onClick:()=>l(!0),children:["Show ",f.length-jp," more files"]}),w.length===0&&o.jsx("div",{className:"fempty",children:"No file or folder names match"}),o.jsxs("div",{className:"fhit fcontents"+(r===w.length?" sel":""),role:"option","aria-selected":r===w.length,onMouseEnter:()=>J1(w.length),onClick:()=>Co(x),children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:"search"})}),o.jsxs("span",{className:"fhit-name",children:["More results for “",x,"”"]}),o.jsx("kbd",{children:Xl?"⌘↵":"Ctrl+↵"})]})]})}function _H(e){const t=e.split("/"),n=[];let r="";for(let i=0;ie+" "+t+(e===1?"":"s");function EH(e){const{pins:t,badges:n,exists:r,currentPath:i,onOpen:l,onUnpin:u}=e;return t.length?o.jsxs("section",{id:"pinned","aria-label":"Pinned",children:[o.jsx("div",{className:"sb-section",children:"Pinned"}),t.map(f=>{const h=f.slice(f.lastIndexOf("/")+1),m=n.comments.get(f)||0,y=n.conflicts.get(f)||0,g=!r(f);return o.jsxs("div",{className:"row pin"+(f===i?" active":"")+(g?" gone":""),"data-pin":f,role:"button",tabIndex:0,title:g?f+" — no longer in this project":f,onClick:()=>!g&&l(f),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&!g&&(w.preventDefault(),l(f))},children:[o.jsx(ge,{name:"star"}),o.jsx("span",{className:"label",children:h}),m>0&&o.jsx("span",{className:"pin-badge",children:Id(m,"comment")}),y>0&&o.jsx("span",{className:"pin-badge danger",children:Id(y,"conflict")}),o.jsx("button",{className:"tact pin-x","aria-label":"Unpin "+h,title:"Unpin",tabIndex:-1,onClick:w=>{w.stopPropagation(),u(f)},children:o.jsx(ge,{name:"x"})})]},f)})]}):null}function NH(e){const{pins:t,badges:n,onOpen:r}=e;return t.length?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-sep"}),t.map(i=>{const l=i.slice(i.lastIndexOf("/")+1),u=n.comments.get(i)||0,f=n.conflicts.get(i)||0,h=[u&&Id(u,"comment"),f&&Id(f,"conflict")].filter(Boolean).join(" · ");return o.jsx(Cv,{icon:"doc",label:l,hint:h||void 0,badge:f||u||void 0,danger:f>0,onClick:()=>r(i)},i)})]}):null}function kH({path:e,onOpenFolder:t}){const n=e.split("/");let r="";return o.jsx("span",{className:"crumbs",title:e,children:n.map((i,l)=>{r=r?r+"/"+i:i;const u=r,f=l===n.length-1,h=l>0&&!f;return o.jsxs("span",{className:"crumb",children:[l>0&&o.jsx("span",{className:"crumb-sep","aria-hidden":"true",children:"›"}),f?o.jsx("span",{className:"crumb-last",children:i}):o.jsx("span",{className:"crumb-seg"+(h?" crumb-mid":""),title:u,onClick:()=>t(u),children:i})]},u)})})}const Pd={today:"Today","7d":"Last 7 days","30d":"Last 30 days"},dy={today:1,"7d":7,"30d":30},cS=e=>String(e).padStart(2,"0");function ui(e){return e.getFullYear()+"-"+cS(e.getMonth()+1)+"-"+cS(e.getDate())}function kg(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function RH(e,t=new Date){const n=e?.range?dy[e.range]:void 0;if(n)return{since:new Date(t.getFullYear(),t.getMonth(),t.getDate()-n+1)};const r={},i=e?.since?kg(e.since):null,l=e?.until?kg(e.until):null;return i&&(r.since=i),l&&(r.until=new Date(l.getFullYear(),l.getMonth(),l.getDate()+1)),r}function MH(e){return new Date(e.getTime()-1).toISOString().replace(/\.(\d{3})Z$/,".$1999999Z")}function nN(e,t=new Date){const n=new URLSearchParams;for(const l of["q","user","actor","device"])e?.[l]&&n.set(l,e[l]);const r=RH(e,t);r.since&&n.set("since",r.since.toISOString()),r.until&&n.set("until",MH(r.until));const i=n.toString();return i?"&"+i:""}function TH(e){return!(e?.range&&dy[e.range])&&!e?.since&&!e?.until}function OH(e){return e?.range&&dy[e.range]||30}function AH(e){return e?.range&&Pd[e.range]?Pd[e.range]:e?.since||e?.until?"Custom range":"All time"}function fy(e,t=new Date){if(e===ui(t))return"Today";if(e===ui(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1)))return"Yesterday";const n=kg(e);return n?n.toLocaleDateString([],{weekday:"long",month:"short",day:"numeric"}):e}function sN(e,t){return t||(e==="add"?"":void 0)}function yi(e){return!!e.session}function Rf(e){const t=/^([a-z0-9][a-z0-9-]*) session \S+$/i.exec((e||"").trim());return t?t[1].split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"Agent"}function DH(e){const t=Math.round(e/6e4);return t<1?"":t<60?t+" min":Math.floor(t/60)+" h"+(t%60?" "+t%60+" min":"")}function uS(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const zH=4e6;function LH(e,t){let n=0;for(;ni.push({op:"-",line:l[g],an:n+g+1}),y=g=>i.push({op:"+",line:u[g],bn:n+g+1});if(f*h>zH){for(let g=0;g=0;j--)for(let S=h-1;S>=0;S--)g[j][S]=l[j]===u[S]?g[j+1][S+1]+1:Math.max(g[j+1][S],g[j][S+1]);let w=0,x=0;for(;w=g[w][x+1]?m(w++):y(x++);for(;wr.op==="+").length,del:n.filter(r=>r.op==="-").length}}function $H(e){if(!e)return[];const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("h2[id], h3[id]")){const i=r.textContent?.trim()??"";i&&n.push({id:r.id,text:i,level:r.tagName==="H2"?2:3})}return n}function dS(e,...t){for(const n of t){const r=e?.find(i=>i.key.toLowerCase()===n);if(r&&!r.code&&r.value.trim())return r.value.trim()}return""}const hy=()=>b.useSyncExternalStore(e=>{const t=window.matchMedia(Kp);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>window.matchMedia(Kp).matches);function FH({doc:e,heat:t}){const n=dS(e.frontmatter,"type"),r=dS(e.frontmatter,"okf_version","okf-version","okf"),i=t?Ps(t):0,l=_2(t,e.time),u=iy(e.time),f=e.user_name||e.user||e.author?ff(e):"",h=f?xv(e):"";return o.jsxs("header",{className:"fv-head","data-bd-ignore":"",children:[o.jsxs("div",{className:"fv-chips",children:[n&&o.jsxs("span",{className:"fv-chip accent",children:[o.jsx(ge,{name:"shield"})," ",n]}),r&&o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"tag"})," OKF v",r.replace(/^v/i,"")]}),o.jsxs("span",{className:"fv-chip",children:[o.jsx(ge,{name:"doc"})," Markdown · ",mi(e.size)]})]}),o.jsxs("div",{className:"fv-meta",children:[l&&o.jsxs("span",{className:"meta-stale",title:l,children:[o.jsx("span",{"aria-hidden":"true",children:"⚠ "}),l]}),f&&o.jsxs("span",{className:"fv-who",title:f,children:[o.jsx("span",{className:"fv-avatar","aria-hidden":"true",children:h.trim()[0]?.toUpperCase()}),h," edited",u!==null?" "+(u<1?"today":oy(u)):""]}),e.device&&o.jsxs("span",{children:[o.jsx(ge,{name:"laptop"})," ",e.device]}),e.time&&o.jsxs("span",{className:"fv-when",children:[o.jsx(ge,{name:"calendar"})," ",q_(e.time)]}),i>0&&o.jsxs("span",{className:"fv-reads",title:Ir,children:[o.jsx(ge,{name:"eye"})," ",i," ",i===1?"read":"reads"," / 30d",o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]})]})]})}function IH(e){const{html:t,frontmatter:n,heat:r,insightsHref:i}=e,l=b.useMemo(()=>$H(t),[t]),u=hy(),[f,h]=b.useState(!1),m=UH(l),y=r?Ps(r):0;if(!l.length&&!n?.length&&!y)return null;const g=o.jsxs(o.Fragment,{children:[l.length>0&&o.jsxs("section",{className:"fv-sec fv-toc","aria-label":"On this page",children:[o.jsx("p",{className:"fv-sec-h",children:"On this page"}),o.jsx("ul",{children:l.map(w=>o.jsx("li",{className:(w.level===3?"sub":"")+(w.id===m?" on":""),children:o.jsx("a",{href:"#"+w.id,"aria-current":w.id===m?"location":void 0,onClick:x=>{x.button!==0||x.metaKey||x.ctrlKey||x.shiftKey||x.altKey||(x.preventDefault(),document.getElementById(w.id)?.scrollIntoView({block:"start",behavior:"smooth"}),history.replaceState(history.state,"",location.pathname+location.search+"#"+w.id))},children:w.text})},w.id))})]}),r&&y>0&&o.jsx(PH,{heat:r,insightsHref:i}),n?.length?o.jsxs("section",{className:"fv-sec fv-props","aria-label":"Properties",children:[o.jsx("p",{className:"fv-sec-h",children:"Properties"}),o.jsx("dl",{children:n.map(w=>o.jsxs("div",{children:[o.jsx("dt",{children:w.key}),o.jsx("dd",{children:w.code?o.jsx("code",{children:w.value}):w.value})]},w.key))})]}):null]});return u?o.jsx("aside",{className:"fv-rail","data-bd-ignore":"","aria-label":"About this file",children:o.jsx("div",{className:"fv-rail-in",children:g})}):o.jsxs("details",{className:"fv-rail narrow","data-bd-ignore":"",open:f,children:[o.jsx("summary",{onClick:w=>{w.preventDefault(),h(!f)},children:"Page info"}),o.jsx("div",{className:"fv-rail-in",children:g})]})}function PH({heat:e,insightsHref:t}){const n=Ps(e),r=[{k:"agent",n:e.agent||0,label:"agent"},{k:"human",n:e.human||0,label:"human"},{k:"share",n:e.share||0,label:"shared"}].filter(i=>i.n>0);return o.jsxs("section",{className:"fv-sec fv-readcard","aria-label":"Reads, last 30 days",children:[o.jsxs("p",{className:"fv-sec-h",children:["Reads · 30 days",t&&o.jsx("a",{className:"fv-sec-link",href:t,children:"Insights →"})]}),o.jsxs("div",{className:"fv-big",title:Ir,children:[n,o.jsxs("span",{className:"sr-only",children:[" — ",Ir]})]}),o.jsx("div",{className:"fv-split",role:"img","aria-label":r.map(i=>`${i.n} ${i.label}`).join(", "),children:r.map(i=>o.jsx("span",{className:"fv-split-"+i.k,style:{flexGrow:i.n}},i.k))}),o.jsx("div",{className:"fv-legend",children:r.map(i=>o.jsxs("span",{children:[o.jsx("i",{className:"fv-sw fv-split-"+i.k})," ",i.n," ",i.label]},i.k))}),(e.readers||e.last_read)&&o.jsxs("p",{className:"fv-readnote",children:[e.readers?`${e.readers} distinct reader${e.readers===1?"":"s"}`:"",e.readers&&e.last_read?" · ":"",e.last_read?"last read "+new Date(e.last_read).toLocaleDateString():""]})]})}function UH(e){const[t,n]=b.useState(e[0]?.id??null);return b.useEffect(()=>{const r=document.getElementById("content");if(!r||!e.length)return;let i=0;const l=()=>{i=0;const f=r.getBoundingClientRect().top+r.clientHeight*.2;let h=e[0].id;for(const m of e){const y=document.getElementById(m.id);y&&y.getBoundingClientRect().top<=f&&(h=m.id)}r.scrollTop>0&&r.scrollTop+r.clientHeight>=r.scrollHeight-2&&(h=e[e.length-1].id),n(h)},u=()=>{i||(i=requestAnimationFrame(l))};return l(),r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),cancelAnimationFrame(i)}},[e]),t}const rN=5e3;function VH(e,t,n=rN){const r=[];let i=[],l="",u=!1,f=0;const h=()=>{i.push(l),l="",r.length1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-CeIX9UEc.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-D6HKLJJk.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` +`)continue;l+=y}}return u||((l!==""||i.length)&&h(),!r.length)||r[0].length<2?null:{rows:r,truncated:f}}const HH={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function qH(e){return`${HH[e.rule]??e.rule} (line ${e.line})`}function aN(e){const t=e.map(qH);return t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"}function BH(e=[]){return`BearDrive found ${aN(e)} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function GH(e=[]){return`This file contains ${aN(e)}.`}const fS=6;function KH(e){const{apiBase:t,path:n,text:r,meeting:i}=e,l=hy(),[u,f]=b.useState(!1),h=b.useMemo(()=>gV(r),[r]),m=b.useMemo(()=>i?uy(r):[],[r,i]),y=o.jsxs(o.Fragment,{children:[i&&m.length>0&&o.jsx(ZH,{...e,secs:m}),o.jsxs("section",{className:"fv-sec er-items","aria-label":"Action items",children:[o.jsxs("h4",{children:["Action items · ",h.filter(g=>!g.done).length,h.length>0&&o.jsx("button",{type:"button",className:"fv-sec-link er-copy",onClick:async()=>{const g=await Mn(vV(h));Ne(g?"Copied — paste into Linear or any tracker.":"Could not copy.",!g)},children:"Copy as markdown"})]}),h.length===0?o.jsxs("p",{className:"er-empty",children:["None yet. Type ",o.jsx("kbd",{children:"/"})," and pick Action item, or write ",o.jsx("code",{children:"- [ ] … @owner"}),"."]}):o.jsx("ul",{className:"er-list",children:h.map(g=>o.jsxs("li",{className:g.done?"done":"","data-owner":g.owner,children:[o.jsx("span",{className:"er-box","aria-hidden":"true",children:g.done?"✓":""}),o.jsxs("span",{className:"er-text",children:[g.text||"(untitled)",o.jsxs("small",{children:[g.owner?"@"+g.owner:"no owner",g.section?" · "+g.section:""]})]})]},g.line))})]}),e.versions&&o.jsx(YH,{apiBase:t,path:n,onRestored:e.onRestored,size:new TextEncoder().encode(r).length})]});return l?o.jsx("aside",{className:"fv-rail er-rail","data-bd-ignore":"","aria-label":"About this note",children:o.jsx("div",{className:"fv-rail-in",children:y})}):o.jsxs("details",{className:"fv-rail narrow er-rail","data-bd-ignore":"",open:u,children:[o.jsx("summary",{onClick:g=>{g.preventDefault(),f(!u)},children:"Action items, versions"}),o.jsx("div",{className:"fv-rail-in",children:y})]})}function ZH(e){const t=e.secs.filter(r=>r.name.split(/\s+/).length<=3&&!/discussion|agenda|notes?$/i.test(r.name)),n=t.filter(r=>r.body).length;return o.jsxs("section",{className:"fv-sec er-att","aria-label":"Attendees",children:[o.jsxs("h4",{children:["Attendees · ",n," of ",t.length]}),o.jsx("div",{className:"er-bar",role:"img","aria-label":`${n} of ${t.length} have written`,children:o.jsx("span",{style:{width:t.length?n/t.length*100+"%":0}})}),o.jsx("ul",{className:"er-people",children:t.map(r=>{const i=Sg(r.name,e.me),l=e.typing.has(r.name),u=e.editors.some(f=>Sg(r.name,f));return o.jsxs("li",{children:[o.jsx(G2,{name:r.name}),o.jsx("span",{className:"er-name",children:r.name}),o.jsx("span",{className:"er-state "+(l?"typing":r.body?"done":"none"),children:i&&u?"You · editing":l?"Typing…":r.body?"Done":"Not started"})]},r.name+r.from)})})]})}function YH({apiBase:e,path:t,size:n,onRestored:r}){const i=mn(),[l,u]=b.useState(""),{data:f}=rt({queryKey:["history",e,"edit-rail",t],queryFn:()=>We(e+"history?path="+encodeURIComponent(t)+"&n="+(fS+1))}),h=(f?.entries??[]).filter(g=>g.path===t&&g.blob&&g.kind!=="delete"),m=h[0]?.blob,y=async g=>{const w=new Date(g.time).toLocaleString();u(g.blob);try{const x=await Sn(e+"restore",{path:t,sha:g.blob});Ne("Restored the version from "+w+"."),i.invalidateQueries({queryKey:["history",e]}),await r?.(!!x?.folded)}catch(x){Ne("Could not restore: "+x.message,!0)}finally{u("")}};return o.jsxs("section",{className:"fv-sec er-versions","aria-label":"Recent versions",children:[o.jsx("h4",{children:"Recent versions"}),o.jsxs("ul",{className:"er-vlist",children:[o.jsxs("li",{className:"now",children:[o.jsx("i",{className:"er-dot live","aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",children:"Now"}),o.jsx("span",{className:"er-vwho",children:"Live"}),o.jsxs("span",{className:"er-vsize",children:[n.toLocaleString()," B"]})]}),h.slice(0,fS).map(g=>{const w=(g.size??0)===0;return o.jsxs("li",{className:w?"empty":"","data-sha":g.blob,children:[o.jsx("i",{className:"er-dot"+(w?" bad":""),"aria-hidden":"true"}),o.jsx("span",{className:"er-vtime",title:new Date(g.time).toLocaleString(),children:new Date(g.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),o.jsx("span",{className:"er-vwho",children:g.user_name||g.user||g.author||g.device?.name||""}),o.jsxs("span",{className:"er-vsize",children:[(g.size??0).toLocaleString()," B"]}),g.blob!==m&&o.jsx("button",{type:"button",className:"er-restore",disabled:!!l,title:"Restore this version as a new version",onClick:()=>{y(g)},children:l===g.blob?"Restoring…":"Restore"})]},g.time+g.blob)})]}),o.jsx("p",{className:"er-note",children:"Restoring creates a new version — nothing is deleted."})]})}let iN=null,oN=null,hS=null,mS=null;const lN=()=>hS??=US(()=>import("./Editor-Cp12kr6p.js"),__vite__mapDeps([0,1,2,3])).then(e=>iN=e).catch(e=>{throw hS=null,e}),cN=()=>mS??=US(()=>import("./VisualEdit-DbM9aXAX.js"),__vite__mapDeps([4,1,2,3])).then(e=>oN=e).catch(e=>{throw mS=null,e});function pS(e,t){const[n,r]=b.useState(e),[i,l]=b.useState(!1),[u,f]=b.useState(0);return b.useEffect(()=>{if(n)return;let h=!0;return t().then(m=>h&&r(m),()=>h&&l(!0)),()=>{h=!1}},[n,t,u]),{mod:n,failed:i,retry:()=>{l(!1),f(h=>h+1)}}}function Cp(){lN(),cN()}const QH=2e3;function gS(e,t,n){const r=Mo(t,n);e.prefetchQuery({queryKey:["text",r],queryFn:()=>kf(r)})}function XH(e){const{apiBase:t,path:n,version:r,onMeta:i}=e,l=Mo(t,n,r);b.useEffect(()=>()=>i(""),[n,i]);const u=e.flatFiles.find(f=>f.path===n)?.link;return u?o.jsx(n7,{path:n,target:u,flatFiles:e.flatFiles,onOpenFile:e.onOpenFile,onRendered:e.onRendered}):e.editing?o.jsx(s7,{...e}):ii.test(n)?o.jsx(a7,{...e}):Dr.test(n)?o.jsx(WH,{...e,fileURL:l}):ad.test(n)?o.jsx("iframe",{className:"pdfview",src:l,title:n,onLoad:e.onRendered}):P_.test(n)?o.jsx(o7,{src:l,alt:n,version:r,onRendered:e.onRendered}):U_.test(n)?o.jsx(vS,{...e,fileURL:l,delim:/\.tsv$/i.test(n)?" ":","}):s3.test(n)?o.jsx(vS,{...e,fileURL:l}):o.jsx(JH,{...e,fileURL:l})}function WH(e){const{apiBase:t,path:n,version:r,onRendered:i}=e,l=V2(t,n,e.fileURL,r),u=l.url,f=b.useRef(l.fresh);f.current=l.fresh;const[h,m]=b.useState(0);return b.useEffect(()=>{const y=g=>{g.detail?.includes(n)&&f.current().finally(()=>m(w=>w+1))};return window.addEventListener("bdrive:changed",y),()=>window.removeEventListener("bdrive:changed",y)},[n]),u?o.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts allow-downloads",src:e.commentable?u+(u.includes("?")?"&":"?")+"comment=1":u,title:n,onLoad:i},h):null}function JH(e){const{apiBase:t,path:n,version:r,fileURL:i,onRendered:l}=e,{data:u,error:f}=cy(i,["text",i],!0,!!r);return b.useEffect(()=>{u&&l?.()},[u,l]),f?o.jsx(Mf,{version:r,err:f}):u?u.kind==="text"?o.jsx("pre",{className:"plain",children:u.text},n):o.jsx(e7,{apiBase:t,path:n,version:r,fileURL:i,children:u.kind==="too-large"?`Too large to preview (${mi(u.size)}).`:"No preview for this file type."}):null}function e7(e){const{apiBase:t,path:n,version:r,fileURL:i}=e;return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"name",children:n.split("/").pop()}),o.jsx("p",{children:e.children}),o.jsx("a",{className:"btn",download:!0,href:r?i+"&download=1":t+"download?path="+encodeURIComponent(n),children:"Download"})]})}function t7(e,t){if(t.startsWith("/"))return null;const n=e.split("/").slice(0,-1);for(const r of t.split("/"))if(!(r===""||r==="."))if(r===".."){if(!n.length)return null;n.pop()}else n.push(r);return n.join("/")}function n7(e){const{path:t,target:n,flatFiles:r,onOpenFile:i,onRendered:l}=e;b.useEffect(()=>l?.(),[l]);const u=t7(t,n),f=u!==null&&r.some(h=>h.path===u);return o.jsxs("div",{className:"filecard",children:[o.jsx("div",{className:"sb-icon",style:{justifyContent:"center",color:"var(--text-dim)",marginBottom:6},children:o.jsx(ge,{name:"link"})}),o.jsx("div",{className:"name",children:t.split("/").pop()}),o.jsx("p",{children:"This is a symbolic link. BearDrive shows the link and never follows it."}),o.jsxs("p",{children:["Target:"," ",f?o.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),i(u)},children:o.jsx("code",{children:n})}):o.jsx("code",{children:n}),!f&&o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{style:{color:"var(--text-dim)"},children:"Points outside this project — no content is served here."})]})]})]})}function s7(e){const{apiBase:t,path:n,onMeta:r}=e,i=Dr.test(n)&&!e.editSource,l=Mo(t,n),u=V2(t,n,l).url,f=cy(l,["text",l],!0,!1),{error:h}=f,m=b.useMemo(()=>Date.now(),[l]),[y,g]=b.useState(null),{refetch:w}=f;b.useEffect(()=>{let Fe=!0;return w({cancelRefetch:!0}).then(ot=>{Fe&&ot.status==="success"&&!ot.isRefetchError&&g(l)}),()=>{Fe=!1}},[w,l]);const x=y===l?f.data:void 0,j=f.data&&f.dataUpdatedAt>=m-QH?f.data:void 0,S=pS(iN,lN),E=pS(oN,cN),_=S.mod?.Editor,N=E.mod?.VisualEdit,R=i?E:S,[T,A]=b.useState("clean"),[M,L]=b.useState("connecting"),H=ii.test(n),U=pV(n),[Z,X]=b.useState(H?"write":"markdown"),[Q,ae]=b.useState(null),[le,be]=b.useState(0),[$,q]=b.useState(null),[,V]=b.useState(0),[ee,K]=b.useState([]),[O,D]=b.useState(new Set);b.useEffect(()=>{const Fe=setInterval(()=>V(ot=>ot+1),5e3);return()=>clearInterval(Fe)},[]),b.useEffect(()=>{T==="clean"&&q(Date.now())},[T]);const B=Q?.collab??null,P=b.useRef("");P.current=Q?.text??"",b.useEffect(()=>{if(!B)return;const Fe=()=>{const ot=[];B.awareness.getStates().forEach(sn=>{const Ct=sn.user?.name;Ct&&ot.push(Ct)}),K([...new Set(ot)]);const Yt=uy(P.current),jt=new Set;for(const sn of B.remoteCursors()){const Ct=H2(Yt,sn.pos);Ct&&jt.add(Ct.name)}D(jt)};return Fe(),B.awareness.on("change",Fe),()=>B.awareness.off("change",Fe)},[B]);const[I,re]=b.useState(!1),he=b.useRef(0),we=mn(),Se=b.useRef(null),ve=async Fe=>{try{const ot=await kf(l),Yt=Se.current;if(ot.kind==="text"&&Yt){const jt=Yt.merge(ot.text,ot.sha,{held:Fe});re(jt==="blocked")}}catch{}we.invalidateQueries({queryKey:["text",l]}),we.invalidateQueries({queryKey:["render",t,n]})},{flushRef:Me}=e;b.useEffect(()=>{if(!Me)return;const Fe=async()=>{for(;;){const ot=Se.current;if(!ot)return!0;let Yt=!1;try{Yt=await ot.saveNow()}catch{return!1}if(!Yt||ot.askingShrink())return!1;if(!(Se.current&&Se.current!==ot))break}return we.invalidateQueries({queryKey:["render",t,n]}),we.invalidateQueries({queryKey:["text",l]}),!0};return Me.current=Fe,()=>{Me.current===Fe&&(Me.current=null)}},[Me,we,t,n,l]);const Ye=b.useRef(0),ht=Fe=>{Ne("Someone else saved this file first. Your version is beside it as "+(Fe.split("/").pop()??Fe))};b.useEffect(()=>{const Fe=ot=>{if(ot.detail?.includes(n)&&i){if(he.current>0){he.current--;return}Ye.current>0||re(!0)}};return window.addEventListener("bdrive:changed",Fe),()=>window.removeEventListener("bdrive:changed",Fe)},[n,i]);const tt=M==="offline",es=tt&&le>0?`Offline · ${le} ${le===1?"edit":"edits"} pending`:tt?"Offline · reconnecting":T==="saving"?"Saving…":T==="dirty"?M==="live"?"Live · unsaved":"Unsaved":T==="error"?"Not saved — still trying":(M==="live"?"Live · ":"")+"saved"+($?" "+wV($):"");return b.useEffect(()=>{r(o.jsxs(o.Fragment,{children:[o.jsxs("span",{id:"editor-state",className:"ed-state","data-state":T,"data-collab":M,"data-pending":le,children:[o.jsx("i",{"aria-hidden":"true"}),es]}),ee.length>0&&o.jsxs("span",{className:"ed-editors","aria-label":"People editing this file",children:[ee.slice(0,5).map(Fe=>o.jsx(G2,{name:Fe,title:Fe+" is editing"},Fe)),ee.length>5&&o.jsxs("span",{className:"ed-more",children:["+",ee.length-5]})]})]}))},[T,M,es,le,ee,r]),b.useEffect(()=>()=>r(""),[r]),h&&!x?o.jsxs("div",{className:"empty",children:["Could not open ",n," for editing."]}):x?x.kind!=="text"?o.jsx("div",{className:"empty",children:"This file is not text, so it cannot be edited here."}):o.jsxs(o.Fragment,{children:[h&&o.jsx("div",{id:"read-stale",className:"banner",children:"Could not check this file for changes just now — your work is untouched and still saving. Retrying."}),I&&o.jsx("div",{id:"peer-wrote",className:"banner",children:"Someone else changed this file while you were editing. Your buffer is unchanged — saving keeps your version and theirs stays in history."}),tt&&o.jsxs("div",{id:"ed-offline",className:"banner ed-offline",role:"status",children:[o.jsx("b",{children:"Reconnecting…"})," ",le>0?`Your ${le} ${le===1?"edit is":"edits are"} kept in this tab and will merge when you're back.`:"Edits you make are kept in this tab and merge when you're back.",U&&" Only your own section can be edited until then."]}),!i&&H&&o.jsx("div",{className:"ed-modes",role:"tablist","aria-label":"Editor mode",children:["write","markdown","preview"].map(Fe=>o.jsxs("button",{type:"button",role:"tab",id:"mode-"+Fe,"aria-selected":Z===Fe,className:Z===Fe?"on":"",onClick:()=>X(Fe),children:[o.jsx(ge,{name:Fe==="write"?"pencil":Fe==="markdown"?"code":"eye"}),Fe==="write"?"Write":Fe==="markdown"?"Markdown":"Preview"]},Fe))}),H&&!i&&o.jsx(KH,{apiBase:t,path:n,text:Q?.text??x.text,meeting:U,editors:ee,me:e.me?.name??"",typing:O,versions:!!e.projectId,onRestored:ve}),R.failed?o.jsxs("div",{className:"empty",children:["Could not load the editor."," ",o.jsx(Ie,{variant:"toolbar",onClick:R.retry,children:"Try again"})]}):i?!N||!u?o.jsx("div",{className:"empty",children:"Loading editor…"}):o.jsx(N,{apiBase:t,fileURL:u,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me,onRendered:e.onRendered,handle:Se}):_?o.jsx("div",{className:"ed-surface",hidden:Z==="preview",children:o.jsx(_,{apiBase:t,mode:Z==="preview"?"write":Z,meeting:U,files:e.flatFiles.map(Fe=>Fe.path),onInfo:ae,onPending:be,handle:Se,path:n,initial:x.text,baseSha:x.sha,onConflictCopy:ht,onExternal:Fe=>{re(Fe==="blocked"),Fe==="merged"&&Ne("Folded in a change from outside this editor.")},onWriting:()=>{he.current++},onStateChange:A,onCollab:L,onPeers:Fe=>{Ye.current=Fe},me:e.me})}):o.jsx("div",{className:"empty",children:"Loading editor…"}),Z==="preview"&&!i&&o.jsx(r7,{...e}),!i&&o.jsxs("div",{className:"ed-statusbar",id:"ed-statusbar",children:[o.jsxs("span",{children:[H?"Markdown":"Text"," · ",mi(xV(Q?.text??x.text))," ·"," ",bV(Q?.text??x.text).toLocaleString()," words"]}),o.jsxs("span",{className:"ed-guard",title:"A save that would empty the file or cut most of it asks first",children:[o.jsx(ge,{name:"shield"})," Empty-save protection on"]}),Q&&o.jsxs("span",{className:"ed-pos",children:["Ln ",Q.line,", Col ",Q.col]})]})]}):j?.kind==="text"?o.jsx("pre",{className:"cm-preview cm-mode-"+(Z==="preview"?"write":Z),"aria-busy":"true",children:j.text}):o.jsx("div",{className:"empty",children:"Loading…"})}function my(e,t,n){return{queryKey:["render",e,t,n||""],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+(n?"&sha="+n:"")),retry:n?!1:void 0}}function r7(e){const{apiBase:t,path:n,flatFiles:r,projectId:i,onOpenFile:l}=e,{data:u}=rt(my(t,n)),f=b.useMemo(()=>u?gy(u.html,n,t,r,i):"",[u,n,t,r,i]);return u?o.jsx("div",{id:"ed-preview",className:"fv-prose",dangerouslySetInnerHTML:{__html:f},onClick:h=>py(h,n,l)}):o.jsx("div",{className:"empty",children:"Loading preview…"})}function a7(e){const t=hy(),{apiBase:n,path:r,version:i,heatMap:l,flatFiles:u,projectId:f,onOpenFile:h,onRendered:m}=e,{data:y,error:g}=rt(my(n,r,i)),w=b.useMemo(()=>y?gy(y.html,r,n,u,f):"",[y,r,n,u,f]),{theme:x}=Ev(),[j,S]=b.useState(null),E=b.useRef(null);if(b.useEffect(()=>{if(E.current!==w&&S(null),E.current=w,!PR(w))return;let R=!1;return UR(w,x==="light"?VR:HR).then(T=>{R||S(T)}),()=>{R=!0}},[w,x]),b.useEffect(()=>{w&&m?.()},[w,j,m]),g)return o.jsx(Mf,{version:i,err:g});if(!y)return o.jsx(uN,{});const _=i?null:l&&l[y.path]||null,N=o.jsx(IH,{html:w,frontmatter:y.frontmatter,heat:_,insightsHref:f?un("dashboard",f,r):void 0});return o.jsxs(o.Fragment,{children:[o.jsx(i7,{findings:y.findings}),!t&&N,o.jsx(FH,{doc:y,heat:_}),o.jsx("div",{className:"fv-prose",dangerouslySetInnerHTML:{__html:j??w},onClick:R=>py(R,r,h)}),t&&N]})}function uN(){return o.jsxs("div",{className:"fskel","aria-busy":"true","aria-label":"Loading file","data-bd-ignore":"",children:[o.jsxs("div",{className:"fskel-main",children:[o.jsx("span",{className:"fskel-title"}),o.jsxs("span",{className:"fskel-meta",children:[o.jsx("span",{style:{width:120}}),o.jsx("span",{style:{width:90}}),o.jsx("span",{style:{width:150}})]}),[96,88,92,70,84,52].map((e,t)=>o.jsx("span",{className:"fskel-line",style:{width:e+"%"}},t))]}),o.jsxs("div",{className:"fskel-rail","aria-hidden":"true",children:[o.jsx("span",{style:{width:"40%"}}),o.jsx("span",{style:{width:"80%"}}),o.jsx("span",{style:{width:"65%"}}),o.jsx("span",{style:{width:"72%"}})]})]})}function i7({findings:e}){return e?.length?o.jsxs("div",{className:"sbadge",role:"status",children:[o.jsx("span",{className:"sb-icon",children:o.jsx(ge,{name:"shield"})}),o.jsxs("div",{className:"sb-text",children:[o.jsx("b",{children:GH(e)}),o.jsx("span",{children:"Checked when this page loaded. Sharing the file asks you to confirm first."})]})]}):null}function py(e,t,n){const r=e.target.closest("a");if(!r||!e.currentTarget.contains(r)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const i=r.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=r.getAttribute("data-wiki");u!==null?(e.preventDefault(),n(u)):/^([a-z]+:|\/|#)/i.test(i)||(e.preventDefault(),n(V_(l,decodeURIComponent(i))))}function gy(e,t,n,r,i){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=h=>n+"file?path="+encodeURIComponent(h),f=new DOMParser().parseFromString(e,"text/html");for(const h of f.querySelectorAll("img")){const m=h.getAttribute("src")||"";/^\s*data:image\/svg/i.test(m)?h.removeAttribute("src"):/^([a-z]+:|\/)/i.test(m)||h.setAttribute("src",u(V_(l,m)))}for(const h of f.querySelectorAll("a")){const m=h.getAttribute("href")||"";if(m.startsWith("wiki:")){const y=r3(decodeURIComponent(m.slice(5)),r);y?(h.setAttribute("href",$n(y.path,i)),h.setAttribute("data-wiki",y.path)):(h.removeAttribute("href"),h.classList.add("wiki-missing"),h.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(m)?h.removeAttribute("href"):/^https?:/i.test(m)&&(h.setAttribute("target","_blank"),h.setAttribute("rel","noopener"))}return f.body.innerHTML}function o7(e){const[t,n]=b.useState(!1);return t?o.jsx(Mf,{version:e.version,err:new Error("could not be loaded")}):o.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>n(!0)})}function Mf({version:e,err:t}){return o.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function vS(e){const{path:t,version:n,fileURL:r,delim:i,onRendered:l}=e,{data:u,error:f}=rt({queryKey:["text",r],queryFn:async()=>{const m=await fetch(r);if(!m.ok)throw new Error(await m.text());return m.text()},retry:n?!1:void 0});b.useEffect(()=>{u!=null&&l?.()},[u,l]);const h=b.useMemo(()=>i&&u!=null?VH(u,i,rN):null,[u,i]);return f?o.jsx(Mf,{version:n,err:f}):u==null?null:h?o.jsx(l7,{csv:h},t):o.jsx("pre",{className:"plain",children:u},t)}function l7({csv:e}){const[t,...n]=e.rows,r=e.rows.reduce((l,u)=>Math.max(l,u.length),0),i=Array.from({length:r},(l,u)=>u);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"csvbox",children:o.jsxs("table",{className:"csvview",children:[o.jsx("thead",{children:o.jsx("tr",{children:i.map(l=>o.jsx("th",{children:t[l]??""},l))})}),o.jsx("tbody",{children:n.map((l,u)=>o.jsx("tr",{children:i.map(f=>o.jsx("td",{children:l[f]??""},f))},u))})]})}),e.truncated>0&&o.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}function Mg(e){return e.slice(e.lastIndexOf("/")+1)}function c7({apiBase:e,path:t,prev:n,cur:r}){const i=Mg(t);return o.jsxs("span",{className:"dv-dl",children:[o.jsx("a",{href:nc(e,n,i,!0),children:"download previous"}),o.jsx("a",{href:nc(e,r,i,!0),children:"download this version"})]})}function dN({apiBase:e,path:t,prev:n,cur:r}){const i=sc(e,n,!0),l=sc(e,r,!0),u=i.data?.kind==="text"&&l.data?.kind==="text",f=b.useMemo(()=>i.data?.kind==="text"&&l.data?.kind==="text"?Rg(i.data.text,l.data.text):null,[i.data,l.data]);if(i.error||l.error)return o.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!i.data||!l.data)return o.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const g=i.data.kind==="too-large"||l.data.kind==="too-large";return o.jsxs("div",{className:"dv dv-msg",children:[g?"Too large to diff — download to compare.":"Binary file — no diff available.",o.jsx(c7,{apiBase:e,path:t,prev:n,cur:r})]})}const{lines:h,add:m,del:y}=f;return o.jsxs("div",{className:"dv",children:[o.jsxs("div",{className:"dv-head",children:[o.jsxs("span",{className:"dv-stat",children:[o.jsxs("span",{className:"dv-add",children:["+",m]})," ",o.jsxs("span",{className:"dv-del",children:["−",y]})]}),m===0&&y===0&&o.jsx("span",{className:"dv-same",children:"No line changes"})]}),o.jsx("div",{className:"dv-body",children:h.map((g,w)=>o.jsxs("div",{className:"dv-line dv-"+(g.op==="="?"ctx":g.op==="+"?"ins":"rm"),children:[o.jsx("span",{className:"dv-n",children:g.an??""}),o.jsx("span",{className:"dv-n",children:g.bn??""}),o.jsx("span",{className:"dv-mark",children:g.op==="="?" ":g.op}),o.jsx("span",{className:"dv-text",children:g.line||" "})]},w))})]})}function u7(e,t,n,r){const i=sc(e,t,r&&!!t),l=sc(e,n,r&&t!==void 0);return b.useMemo(()=>t===void 0||l.data?.kind!=="text"?null:t?i.data?.kind!=="text"?null:Rg(i.data.text,l.data.text):Rg("",l.data.text),[i.data,l.data,t])}function d7({add:e,del:t}){return o.jsxs("span",{className:"hstat",children:[e>0&&o.jsxs("span",{className:"dv-add",children:["+",e]}),t>0&&o.jsxs("span",{className:"dv-del",children:["−",t]})]})}const f7=[["changes","Changes"],["rendered","Rendered"],["full","Full file"]];function h7({apiBase:e,path:t,kind:n,prev:r,cur:i,flatFiles:l,projectId:u,onOpenFile:f}){const[h,m]=b.useState("changes"),y=i||r;return o.jsxs("div",{className:"dtabs",children:[o.jsx("div",{className:"dtabs-bar",role:"tablist",children:f7.map(([g,w])=>o.jsx("button",{type:"button",role:"tab","aria-selected":h===g,onClick:()=>m(g),children:w},g))}),o.jsxs("div",{className:"dtabs-body",children:[h==="changes"&&(i&&r?o.jsx(dN,{apiBase:e,path:t,prev:r,cur:i}):o.jsx("div",{className:"dv dv-msg",children:i?sN(n,r)===""?"First version — nothing to compare against.":"Earlier version not loaded — nothing to compare against here.":"This change deleted the file."})),h==="rendered"&&y&&o.jsx(m7,{apiBase:e,path:t,sha:y,flatFiles:l,projectId:u,onOpenFile:f}),h==="full"&&y&&o.jsx(p7,{apiBase:e,sha:y})]})]})}function m7({apiBase:e,path:t,sha:n,flatFiles:r,projectId:i,onOpenFile:l}){const u=/\.(md|markdown)$/i.test(t),f=/\.(png|jpe?g|gif|webp|svg)$/i.test(t),{data:h,error:m}=rt({queryKey:["render",e,t,n],queryFn:()=>We(e+"render?path="+encodeURIComponent(t)+"&sha="+n),enabled:u,retry:!1}),y=b.useMemo(()=>h?gy(h.html,t,e,r,i):"",[h,t,e,r,i]);return f?o.jsx("img",{className:"dtabs-img",alt:Mg(t),src:nc(e,n,Mg(t))}):u?m?o.jsx("div",{className:"dv dv-msg",children:"Could not render this version."}):h?o.jsx("div",{className:"md dtabs-md",dangerouslySetInnerHTML:{__html:y},onClick:g=>py(g,t,l)}):o.jsx("div",{className:"dv dv-msg",children:"Rendering…"}):o.jsx("div",{className:"dv dv-msg",children:"No rendered view for this file type — see Full file."})}function p7({apiBase:e,sha:t}){const n=sc(e,t,!0);return n.error?o.jsx("div",{className:"dv dv-msg",children:"Could not load this version."}):n.data?n.data.kind!=="text"?o.jsx("div",{className:"dv dv-msg",children:n.data.kind==="too-large"?"Too large to show.":"Binary file."}):o.jsx("div",{className:"dv",children:o.jsx("div",{className:"dv-body",children:n.data.text.split(` `).map((r,i)=>o.jsxs("div",{className:"dv-line dv-ctx",children:[o.jsx("span",{className:"dv-n",children:i+1}),o.jsx("span",{className:"dv-text",children:r||" "})]},i))})}):o.jsx("div",{className:"dv dv-msg",children:"Loading…"})}const g7={add:"added",edit:"edited",delete:"deleted"};function fN({text:e}){return o.jsx(o.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,n)=>/^https?:\/\//.test(t)?o.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},n):t)})}function vy({entry:e,apiBase:t,onOpen:n,diff:r,restore:i,remove:l,restoreSha:u,recreates:f,inRun:h,read:m,selected:y,onSelect:g,stat:w,idx:x}){const[j,S]=b.useState(!1),[E,_]=b.useState(!1),N=e.kind==="put"?"edit":e.kind,R=ff(e),T=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),A=N!=="delete",M=!!r&&N!=="delete"&&!!e.blob,L=!!h&&N==="add",H=!!i&&!!u&&!L,U=!!l&&L,Z=!!i?.busy&&i.busy===e.path+u,X=!!l?.busy&&l.busy===e.path,Q=A&&!!e.blob,ae=e.path.split("/").pop()||e.path,le=q_(e.time),be=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(ae)+"&download=1",$=()=>_(!E),q=u7(t,sN(N,r?.prev),e.blob,!!w&&N!=="delete"&&!!e.blob),V=N!=="delete"?Vr(e.path):null,ee=K=>{K.target.tagName!=="A"&&A&&n(e.path,e.blob)};return o.jsxs("div",{className:"hentry "+N+(A?" clickable":"")+(y?" sel":""),"data-agent":yi(e)?"":void 0,"data-hidx":x,tabIndex:A?0:void 0,role:A?"button":void 0,onClick:ee,onKeyDown:K=>{A&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),n(e.path,e.blob))},children:[o.jsxs("div",{className:"hline",children:[o.jsx("span",{className:"hkind",children:g7[N]||N}),m&&o.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),o.jsx("span",{className:"hpath",children:e.path}),q&&o.jsx(d7,{add:q.add,del:q.del}),o.jsx("span",{className:"htime",title:le,children:new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsxs("div",{className:"hmeta",children:[o.jsx("span",{className:"hwho",title:R,children:xv(e)}),o.jsx("span",{className:"hdev",children:T}),o.jsx("span",{className:"hsize",children:e.size?mi(e.size):""}),N==="delete"&&H&&o.jsx("span",{className:"hgone",children:"can be restored"}),V&&o.jsx("button",{type:"button",className:"pbtn hresolve-btn",title:`Two devices edited ${V.original} at once — review and keep one`,onClick:K=>{K.stopPropagation(),n(e.path)},onKeyDown:K=>K.stopPropagation(),children:"Resolve"}),g&&o.jsx("button",{type:"button",className:"hsel-btn","aria-pressed":!!y,title:"Show this change in the side panel (J / K to move)",onClick:K=>{K.stopPropagation(),g()},onKeyDown:K=>K.stopPropagation(),children:"Details"}),H&&o.jsxs("button",{type:"button",className:"hrestore-btn",disabled:Z,title:"Put this version of "+e.path+" back as a new change",onClick:K=>{K.stopPropagation(),i.onRestore(e.path,u,!!f)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"hist"}),Z?"restoring…":"restore"]}),U&&o.jsxs("button",{type:"button",className:"hremove-btn",disabled:X,title:"Remove "+e.path+" — this run created it",onClick:K=>{K.stopPropagation(),l.onRemove(e.path)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"trash"}),X?"removing…":"undo — remove file"]})]}),e.note&&!h&&o.jsx("div",{className:"hnote"+(j?" open":""),tabIndex:0,role:"button",title:j?"Collapse note":"Show full note","aria-expanded":j,onClick:K=>{K.stopPropagation(),K.target.tagName!=="A"&&S(!j)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),S(!j))},children:o.jsx(fN,{text:e.note})}),(M||Q)&&o.jsxs("div",{className:"hactions",children:[M&&(r.prev?o.jsxs("button",{type:"button",className:"hdiff-btn"+(E?" open":""),"aria-expanded":E,onClick:K=>{K.stopPropagation(),$()},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:E?"chevd":"chev"}),E?"hide changes":"show changes"]}):o.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),Q&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${ae} as of ${le}`,onClick:K=>{K.stopPropagation(),n(e.path,e.blob)},onKeyDown:K=>K.stopPropagation(),children:[o.jsx(ge,{name:"clock"}),"Open this version"]}),o.jsxs("a",{className:"hver-btn",download:!0,href:be,"aria-label":`Download ${ae} as of ${le}`,onClick:K=>K.stopPropagation(),onKeyDown:K=>{K.stopPropagation(),K.key===" "&&(K.preventDefault(),K.currentTarget.click())},children:[o.jsx(ge,{name:"download"}),"Download"]})]})]}),M&&r.prev&&E&&o.jsx("div",{onClick:K=>K.stopPropagation(),children:o.jsx(dN,{apiBase:r.apiBase,path:e.path,prev:r.prev,cur:e.blob})})]})}function hN(e){const{node:t,heatMap:n,folders:r,onOpen:i}=e,l=(t.children||[]).slice().sort((g,w)=>Number(w.dir||!1)-Number(g.dir||!1)||g.name.localeCompare(w.name)),u=l.filter(g=>g.dir).length,f=l.length-u,h=[];u&&h.push(u+(u===1?" folder":" folders")),f&&h.push(f+(f===1?" file":" files"));const m=fd(n,t.path,!0);m&&h.push(Xu(m)+" in 30 days");const y=!!m||l.some(g=>fd(n,g.path,!!g.dir));return o.jsxs("div",{className:"dirlist",children:[o.jsxs("h1",{className:"dl-title",children:[o.jsx("span",{className:"dl-title-icon",children:o.jsx(ge,{name:"folder"})}),o.jsx("span",{children:t.name})]}),o.jsx("p",{className:"dl-sub",children:h.join(" · ")||"Empty folder"}),y&&o.jsx("p",{className:"dl-heatnote",children:Ir}),l.length===0?o.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):o.jsx("div",{className:"dl-items",children:l.map(g=>{let w="";if(g.dir){const _=(g.children||[]).length;w=_+(_===1?" item":" items")}else w=[g.size?mi(g.size):"",g.time?new Date(g.time).toLocaleDateString():""].filter(Boolean).join(" · ");const x=fd(n,g.path,!!g.dir);x&&(w=Xu(x)+(w?" · "+w:""));const j=g.dir?null:Vr(g.path),S=g.dir?r.find(_=>_.prefix===g.path+"/"):void 0,E=g.dir?"":_2(x,g.time);return o.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:g.path,onClick:()=>i(g.path),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),i(g.path))},children:[o.jsx("span",{className:"ticon",children:o.jsx(ge,{name:g.dir?"folder":"doc"})}),o.jsx("span",{className:"dl-name",children:g.name}),S&&o.jsx("span",{className:"dl-restricted","aria-label":S.default==="none"?"Restricted folder: not shared with everyone in this workspace.":"Restricted folder: everyone in this workspace can "+(S.default||"read")+" here.",title:S.default==="none"?"Not shared with everyone — only the people on its list.":"Everyone in this workspace can "+(S.default||"read")+" here.",children:S.default==="none"?"restricted":S.default||"shared"}),j&&o.jsx("span",{className:"dl-conflict","aria-label":"Conflict copy: a concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",title:"A concurrent edit from "+(j.device||"another device")+" that beardrive preserved instead of dropping.",children:"conflict copy"}),E&&o.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+E,title:"Read often, but "+E,children:"⚠"}),x&&o.jsx("span",{className:"heatdot lvl"+bU(x),role:"img","aria-label":Xu(x)+" in 30 days. "+Ir,title:Xu(x)+" in 30 days. "+Ir}),o.jsx("span",{className:"dl-meta",children:w})]},g.path)})}),e.hub&&o.jsx(v7,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function v7(e){const t=TU(e.apiBase,e.prefix,!0),{onRendered:n}=e;return b.useEffect(()=>{t&&t.length&&n&&n()},[t,n]),!t||t.length===0?null:o.jsxs("div",{className:"dl-history",children:[o.jsx("h3",{className:"dl-h3",children:"Recent changes"}),o.jsx("div",{className:"history dl-hlist",children:t.map((r,i)=>o.jsx(vy,{entry:r,apiBase:e.apiBase,onOpen:e.onOpen},i))}),o.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const y7=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}],mN=[{value:"",label:"Same as the project"},{value:"write",label:"Write"},{value:"read",label:"Read"},{value:"none",label:"No access"}],yS=mN.filter(e=>e.value!=="");function x7({project:e,path:t,isDir:n,shares:r,onChanged:i,onOpenFolder:l,onClose:u}){const f=mn(),{data:h}=hE(e.id),{data:m}=kv(e.id),{data:y}=fE(!!e.org),g=y?.find(P=>P.id===e.org)?.name||"this workspace",w=In(e.perm,"admin"),x=In(e.perm,"write"),j=n?t+"/":t,S=b.useMemo(()=>h?.folders||[],[h]),E=n?S.find(P=>P.prefix===j):void 0,_=K2(S,j),[N,R]=b.useState(null),T=r.find(P=>P.path===t)||N||void 0,[A,M]=b.useState(!1),[L,H]=b.useState(""),[U,Z]=b.useState("read"),[X,Q]=b.useState(null),[ae,le]=b.useState(""),be=b.useRef(null),$=()=>{f.invalidateQueries({queryKey:["folders",e.id]}),i()},q=async(P,I)=>{M(!0);try{await P(),Ne(I)}catch(re){Ne(re.message,!0)}finally{M(!1),$()}},V=P=>{const I=P.perms??Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level])),re=P.level??E?.default??"";return re===""&&Object.keys(I).length===0?en("DELETE",`/api/p/${e.id}/folders?prefix=${encodeURIComponent(j)}`):en("PUT",`/api/p/${e.id}/folders`,{prefix:j,default:re,perms:I})};async function ee(P){M(!0);try{const I=await fetch(`/api/p/${e.id}/shares`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P?{path:t,confirm:!0}:{path:t})});if(I.status===409){const{findings:we}=await I.json();Q(we||[]);return}if(!I.ok)throw new Error(await I.text());const re=await I.json();R({token:re.token,url:re.url,path:t,project:e.id}),Q(null),nj("share_created");const he=await Mn(re.url);Ne(he?"Link created and copied.":"Link created."),i()}catch(I){Ne("Share failed: "+I.message,!0)}finally{M(!1)}}async function K(P){if(P==="public")return ee(!1);Q(null),R(null),T&&await q(()=>en("DELETE",`/api/shares/${T.token}`),"Link revoked — the URL no longer works.")}async function O(P){if(!T)return;const I=ae;le(P);try{await en("PATCH",`/api/shares/${T.token}`,{expires_in:P}),i()}catch(re){Ne(re.message,!0),le(I)}}const D=S.filter(P=>P.prefix!==j&&P.prefix.startsWith(j)),B=`Share "${t.split("/").pop()||e.name}"`;return o.jsx(uc,{open:!0,onOpenChange:P=>!P&&u(),children:o.jsxs(dc,{className:"modal modal-wide",showCloseButton:!1,onOpenAutoFocus:P=>{P.preventDefault(),be.current?.focus()},children:[o.jsx(zo,{asChild:!0,children:o.jsx("h3",{children:B})}),o.jsx("h4",{className:"sd-head",children:"Who can open this"}),n?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsxs("span",{children:["Everyone in ",g," can"]}),o.jsx("select",{"aria-label":"Access for everyone in the workspace",disabled:!w||A,value:E?.default??"",onChange:P=>q(()=>V({level:P.target.value}),"Folder access updated."),children:mN.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),!E?.default&&m&&o.jsxs("span",{className:"ai-tag",children:["the project default is ",m.default]})]}),E?.default==="none"&&o.jsxs("p",{className:"ps-note",children:["A folder set to ",o.jsx("b",{children:"no access"})," is not synced to anyone outside the list below, and disappears from their file tree, history and search. Older share links into it stop working. Its ",o.jsx("i",{children:"name"})," stays visible to project members — their devices have to know not to write there. If the name has to be secret too, use a separate project."]}),D.length>0&&o.jsx("p",{className:"ps-note",children:D.length===1?`${D[0].prefix} has its own rule and keeps it — this does not reach inside it.`:`${D.length} folders inside have their own rules and keep them — this does not reach inside them.`}),(E?.grants.length||w)&&o.jsxs("div",{className:"admin-list sd-people",children:[(E?.grants||[]).map(P=>o.jsxs("div",{className:"admin-item",children:[o.jsx("span",{className:"avatar sd-avatar",style:{background:z2(P.email)},"aria-hidden":"true",children:(P.email.trim()[0]||"?").toUpperCase()}),o.jsx("span",{className:"ai-main",title:P.email,children:P.email}),o.jsx("span",{className:"role-cell",children:o.jsx("select",{"aria-label":`Access to this folder for ${P.email}`,disabled:!w||A,value:P.level,onChange:I=>{const re=Object.fromEntries((E?.grants||[]).map(he=>[he.email,he.level]));re[P.email]=I.target.value,q(()=>V({perms:re}),`${P.email} updated.`)},children:yS.map(I=>o.jsx("option",{value:I.value,children:I.label},I.value))})})]},P.email)),w&&o.jsxs("div",{className:"admin-item sd-add",children:[o.jsx("input",{className:"sd-add-input",placeholder:"Email of a workspace member","aria-label":"Add someone to this folder",value:L,disabled:A,onChange:P=>H(P.target.value)}),o.jsxs("span",{className:"role-cell",children:[o.jsx("select",{"aria-label":"Access for the person being added",value:U,disabled:A,onChange:P=>Z(P.target.value),children:yS.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx(Ie,{variant:"subtle",disabled:!L.trim()||A,onClick:()=>{const P=Object.fromEntries((E?.grants||[]).map(re=>[re.email,re.level]));P[L.trim().toLowerCase()]=U;const I=L.trim();H(""),q(()=>V({perms:P}),`${I} added.`)},children:"Add"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"ps-row",children:_?o.jsxs("span",{children:["Access comes from the rule on ",o.jsx("b",{children:_.prefix})," — you can"," ",o.jsx("b",{children:_.me})," here."]}):o.jsxs("span",{children:["Everyone in ",g," with access to this project can open it",m&&o.jsxs(o.Fragment,{children:[" — the project default is ",o.jsx("b",{children:m.default})]}),"."]})}),_&&o.jsx("p",{className:"ps-row",children:o.jsxs(Ie,{variant:"subtle",onClick:()=>l(_.prefix.replace(/\/$/,"")),children:["Open sharing for ",_.prefix]})})]}),o.jsx("h4",{className:"sd-head",children:"Public link"}),n?o.jsx("p",{className:"ps-note",children:"Public links are per file — open a file inside this folder to share it with someone who has no account."}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"ps-row",children:[o.jsx("span",{children:o.jsx(ge,{name:T?"globe":"lock"})}),o.jsxs("select",{"aria-label":"Public link",id:"share-public",disabled:!x||A,value:T?"public":"restricted",onChange:P=>K(P.target.value),children:[o.jsx("option",{value:"restricted",children:"Restricted — only people with access"}),o.jsx("option",{value:"public",children:"Anyone with the link can view"})]})]}),X&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sd-warn",children:o.jsx("b",{children:"This file may contain credentials"})}),o.jsx("p",{className:"ps-note",children:BH(X)}),o.jsxs("p",{className:"ps-row",children:[o.jsx(Ie,{variant:"primary",disabled:A,onClick:()=>ee(!0),children:"Share anyway"}),o.jsx(Ie,{variant:"subtle",disabled:A,onClick:()=>Q(null),children:"Cancel"})]})]}),T&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"modal-url",children:T.url}),o.jsxs("div",{className:"modal-expiry",children:[o.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),o.jsx("select",{id:"share-expiry",value:ae,disabled:!x||A,onChange:P=>O(P.target.value),children:y7.map(P=>o.jsx("option",{value:P.value,children:P.label},P.value))}),o.jsx("span",{className:"modal-expiry-note",children:p2(T.expires)})]})]})]}),o.jsxs("div",{className:"modal-actions",children:[o.jsx(Ie,{ref:be,variant:"primary",onClick:()=>Mn(T?T.url:window.location.href).then(P=>Ne(P?"Copied.":"Select and copy the link above.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:u,children:"Done"})]})]})})}function b7({shares:e,canRevoke:t,onChanged:n}){return e.length===0?null:o.jsxs("div",{className:"share-banner",role:"status",children:[o.jsxs("div",{className:"sb-head",children:[o.jsx(ge,{name:"share"}),o.jsx("b",{children:"Publicly shared"}),o.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),o.jsxs("p",{className:"sb-note",children:[o.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(r=>r.opens!==void 0)&&o.jsxs(o.Fragment,{children:[" ",v2]})]}),e.map(r=>o.jsxs("div",{className:"sb-link",children:[o.jsx("span",{className:"sb-url mono",title:r.url,children:r.url}),o.jsx("span",{className:"sb-meta",children:g2(r,!1)}),o.jsxs("span",{className:"sb-actions",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>Mn(r.url).then(i=>Ne(i?"Copied.":"Select and copy the link.")),children:"Copy link"}),o.jsx(Ie,{variant:"subtle",onClick:()=>window.open(r.url,"_blank"),children:"Open"}),t&&o.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${r.path}`,onClick:()=>x2(r,n),children:"Revoke"})]})]},r.token))]})}function w7(e,t,n){return rt({queryKey:["comments",e,t],queryFn:()=>We(e+"comments?status=all&path="+encodeURIComponent(t)),enabled:n&&!!t,select:r=>r.comments||[]})}function pN(e){const t=mn(),n=()=>{t.invalidateQueries({queryKey:["comments",e]})},r=(i,l)=>{for(const[u,f]of t.getQueriesData({queryKey:["comments",e]})){if(!f||u.length!==3)continue;const h=u[2];let m=(f.comments||[]).filter(y=>y.id!==l);if(i){const y=m.findIndex(g=>g.id===i.id);y>=0?m=m.map((g,w)=>w===y?i:g):i.path===h&&(m=[...m,i])}t.setQueryData(u,{...f,comments:m})}};return{create:async(i,l,u,f)=>{const h=await Sn(e+"comments",{path:i,body:l,anchor:u,sha:f});return r(h.comment),n(),h.comment},act:async(i,l,u="")=>{const f=await Sn(e+"comments/"+i,{action:l,body:u});f?.comment&&r(f.comment),n()},remove:async i=>{r(null,i);try{await en("DELETE",e+"comments/"+i)}finally{n()}}}}const xS=48;function Il(e){let t="";const n=[];for(let r=0;r=0&&e[u-m]===n[n.length-m];m++)f++;const h=u+t.length;for(let m=0;ml&&(i=u,l=f)}return i}function j7(e,t){const n=Il(t.quote||"").text;if(!n)return null;const{text:r,map:i}=Il(e),l=S7(r,n,Il(t.prefix||"").text,Il(t.suffix||"").text);return l<0?null:[i[l],i[l+n.length-1]+1]}function C7(e,t,n){const r=i=>i.replace(/\s+/g," ");return{prefix:r(e.slice(Math.max(0,t-xS),t)).trimStart(),suffix:r(e.slice(n,n+xS)).trimEnd()}}const _7=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TEXTAREA"]);function gN(e){const t=[],n=[];let r="";const l=(e.ownerDocument||e).createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(u){for(let f=u.parentElement;f&&f!==e;f=f.parentElement)if(_7.has(f.tagName)||f.hasAttribute("data-bd-ignore"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}});for(let u=l.nextNode();u;u=l.nextNode())t.push(u),n.push(r.length),r+=u.data;return{all:r,nodes:t,starts:n}}function bS(e,t,n){if(!e.nodes.length)return null;let r=0,i=e.nodes.length-1;for(;r>1;e.starts[l]=0)return e.starts[r]+n;const l=t.ownerDocument.createRange();l.setStart(t,n);for(let u=0;u=0)return e.starts[u];return e.all.length}function SS(e,t,n,r=!1){const i=gN(e),l=wS(i,t.startContainer,t.startOffset),u=wS(i,t.endContainer,t.endOffset);if(u<=l)return null;const f=(n||i.all.slice(l,u)).trim();if(!Il(f).text)return null;const h={quote:f,...C7(i.all,l,u)};return r&&(h.line=i.all.slice(0,l).split(` `).length),h}function N7(e,t,n,r){const i=e;let l=null,u=0;if(i.caretPositionFromPoint){const f=i.caretPositionFromPoint(t,n);f&&([l,u]=[f.offsetNode,f.offset])}else if(e.caretRangeFromPoint){const f=e.caretRangeFromPoint(t,n);f&&([l,u]=[f.startContainer,f.startOffset])}if(!l)return null;for(const[f,h]of r)try{if(h.isPointInRange(l,u)&&!(h.endContainer===l&&h.endOffset===u))return f}catch{}return null}const jS="bd-comment",Ju="bd-comment-active";function k7(e){const{apiBase:t,path:n,framed:r,lines:i,threads:l,focus:u,onFocus:f,onOpenPanel:h,picking:m,onPicking:y}=e,g=b.useRef(null),[w,x]=b.useState(null);b.useLayoutEffect(()=>x(g.current?.parentElement??null),[]);const[j,S]=b.useState(null),[E,_]=b.useState(""),[N,R]=b.useState(!1),T=pN(t),A=b.useMemo(()=>yN(l),[l]),M=b.useMemo(()=>A.filter(V=>!V.resolved&&!V.missing),[A]);b.useEffect(()=>{S(null),_("")},[n]);const L=b.useRef(new Map),[H,U]=b.useState([]),[Z,X]=b.useState(0);b.useEffect(()=>{if(r||!w)return;let V=0;const ee=()=>{V||(V=requestAnimationFrame(()=>{V=0,X(D=>D+1)}))},K=new MutationObserver(D=>{D.some(B=>!ed(B.target))&&ee()});K.observe(w,{childList:!0,subtree:!0,characterData:!0});const O=new ResizeObserver(ee);return O.observe(w),()=>{K.disconnect(),O.disconnect(),cancelAnimationFrame(V)}},[r,w]),b.useLayoutEffect(()=>{if(r||!w)return;const V=new Map;for(const B of M){const P=B.anchor.quote?E7(w,B.anchor):null;P&&V.set(B.id,P)}L.current=V;const ee=td();if(ee){ee.set(jS,new Highlight(...[...V].filter(([P])=>P!==u).map(([,P])=>P)));const B=u?V.get(u):void 0;B?ee.set(Ju,new Highlight(B)):ee.delete(Ju)}const K=w.getBoundingClientRect(),O=[],D=new Map;for(const B of M){const P=V.get(B.id)?.getClientRects()[0];if(!P)continue;const I=Math.round(P.top-K.top+P.height/2),re=D.get(I)??0;D.set(I,re+1),O.push({id:B.id,n:B.n,c:B.messages.length,k:re,x:-38,y:I})}U(O)},[M,u,Z,r,w]);const Q=b.useRef(null);b.useEffect(()=>{const V=td();!V||r||(j?.composing&&Q.current?V.set(Ju,new Highlight(Q.current)):X(ee=>ee+1))},[j?.composing,r]),b.useEffect(()=>()=>{td()?.delete(jS),td()?.delete(Ju)},[]),b.useEffect(()=>{if(!u||r)return;L.current.get(u)?.startContainer.parentElement?.scrollIntoView({block:"center",behavior:"smooth"})},[u,r]),b.useLayoutEffect(()=>{if(r||!w)return;const V=K=>{ed(K.target)||K instanceof KeyboardEvent&&!K.shiftKey||setTimeout(()=>{const O=getSelection();if(!O||O.isCollapsed||!O.rangeCount){S(re=>re?.composing?re:null);return}const D=O.getRangeAt(0);if(!w.contains(D.commonAncestorContainer)||ed(D.commonAncestorContainer))return;const B=i?D.startContainer.parentElement?.closest("pre.plain")??null:null,P=B&&B.contains(D.endContainer)?SS(B,D,O.toString(),!0):SS(w,D,O.toString());if(!P)return;const I=D.getBoundingClientRect();Q.current=D.cloneRange(),S({anchor:P,x:I.right,y:I.bottom,composing:!1})},0)},ee=K=>{if(ed(K.target))return;const O=getSelection();if(O&&!O.isCollapsed)return;const D=N7(document,K.clientX,K.clientY,L.current);D&&(f(D),h())};return w.addEventListener("mouseup",V),w.addEventListener("keyup",V),w.addEventListener("click",ee),()=>{w.removeEventListener("mouseup",V),w.removeEventListener("keyup",V),w.removeEventListener("click",ee)}},[r,w,i,f,h]);const ae=b.useCallback(()=>w?.querySelector("iframe.htmlview")??null,[w]),le=b.useCallback(V=>{ae()?.contentWindow?.postMessage(V,"*")},[ae]),be=b.useCallback(()=>{le({type:"bd-comment:anchors",anchors:M.map(V=>({id:V.id,n:V.n,...V.anchor})),active:u})},[M,u,le]);b.useEffect(()=>{r&&be()},[r,be]),b.useEffect(()=>{r&&le({type:"bd-comment:pick",on:m})},[r,m,le]),b.useEffect(()=>{r&&u&&le({type:"bd-comment:focus",id:u})},[r,u,le]),b.useEffect(()=>{if(!r)return;const V=ee=>{const K=ae();if(!K||ee.source!==K.contentWindow)return;const O=ee.data;if(!O||typeof O!="object")return;const D=K.getBoundingClientRect();switch(O.type){case"bd-comment:ready":be(),le({type:"bd-comment:pick",on:m});break;case"bd-comment:select":!O.anchor||!O.rect?S(B=>B?.composing?B:null):S({anchor:O.anchor,x:D.left+O.rect.x+O.rect.w,y:D.top+O.rect.y+O.rect.h,composing:!1});break;case"bd-comment:picked":y(!1),S({anchor:O.anchor,x:D.left+O.rect.x+Math.min(O.rect.w,320),y:D.top+O.rect.y+Math.min(O.rect.h,60),composing:!0});break;case"bd-comment:open":typeof O.id=="string"&&(f(O.id),h());break;case"bd-comment:pickoff":y(!1);break}};return addEventListener("message",V),()=>removeEventListener("message",V)},[r,ae,be,le,m,y,f,h]),b.useEffect(()=>{const V=document.getElementById("content"),ee=()=>S(K=>K?.composing?K:null);return V?.addEventListener("scroll",ee,{passive:!0}),()=>V?.removeEventListener("scroll",ee)},[]);const $=async()=>{if(!(!j||!E.trim()||N)){R(!0);try{const V=await T.create(n,E,j.anchor);S(null),_(""),getSelection()?.removeAllRanges(),r&&le({type:"bd-comment:clear"}),f(V.id),h()}catch(V){Ne("Could not save the comment: "+V.message)}finally{R(!1)}}},q=j?O7(j.x,j.y,j.composing?320:120,j.composing?170:34):null;return o.jsxs(o.Fragment,{children:[e.children,o.jsx("span",{ref:g,hidden:!0,"data-bd-ignore":""}),!r&&H.map(V=>o.jsxs("button",{"data-bd-ignore":"",className:"cm-pin"+(V.id===u?" active":""),style:{left:V.x,top:V.y,"--k":V.k},title:`Comment ${V.n} · ${V.c} message${V.c===1?"":"s"}`,"aria-label":`Open comment ${V.n}`,onClick:()=>{f(V.id),h()},children:[o.jsx(ge,{name:"comment"}),V.n]},V.id)),j&&q&&!j.composing&&o.jsxs("button",{"data-bd-ignore":"",className:"cm-float",style:{left:q.x,top:q.y},onMouseDown:V=>V.preventDefault(),onClick:()=>S({...j,composing:!0}),children:[o.jsx(ge,{name:"comment"})," Comment"]}),j&&q&&j.composing&&o.jsxs("div",{"data-bd-ignore":"",className:"cm-compose",style:{left:q.x,top:q.y},role:"dialog","aria-label":"New comment",children:[o.jsx(vN,{a:j.anchor}),o.jsx("textarea",{autoFocus:!0,value:E,placeholder:"Leave feedback… (⌘↵ to post)",onChange:V=>_(V.target.value),onKeyDown:V=>{V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&$(),V.key==="Escape"&&(S(null),_(""))}}),o.jsxs("div",{className:"cm-row",children:[o.jsx(Ie,{variant:"subtle",onClick:()=>{S(null),_("")},children:"Cancel"}),o.jsx(Ie,{variant:"primary",disabled:!E.trim()||N,onClick:()=>{$()},children:"Comment"})]})]})]})}function R7(e){const{apiBase:t,path:n,threads:r,focus:i,onFocus:l,onClose:u,framed:f,picking:h,onPicking:m,me:y,admin:g}=e,w=pN(t),x=b.useMemo(()=>yN(r),[r]),j=x.filter(U=>!U.resolved),S=x.filter(U=>U.resolved),[E,_]=b.useState("open"),N=!!i&&S.some(U=>U.id===i);b.useEffect(()=>{N&&_("resolved")},[i,N]);const R=E==="open"?j:S,[T,A]=b.useState(""),[M,L]=b.useState(!1),H=async()=>{if(!(!T.trim()||M)){L(!0);try{const U=await w.create(n,T);A(""),_("open"),l(U.id)}catch(U){Ne("Could not save the comment: "+U.message)}finally{L(!1)}}};return o.jsxs("aside",{className:"cm-panel","aria-label":"Comments",children:[o.jsxs("header",{className:"cm-head",children:[o.jsx("b",{children:"Comments"}),o.jsxs("div",{className:"cm-tabs",role:"tablist",children:[o.jsxs("button",{role:"tab","aria-selected":E==="open",onClick:()=>_("open"),children:["Open",j.length>0&&o.jsxs("span",{children:[" · ",j.length]})]}),o.jsxs("button",{role:"tab","aria-selected":E==="resolved",onClick:()=>_("resolved"),children:["Resolved",S.length>0&&o.jsxs("span",{children:[" · ",S.length]})]})]}),o.jsx("button",{className:"cm-x",onClick:u,"aria-label":"Close comments",title:"Close",children:o.jsx(ge,{name:"x"})})]}),f&&o.jsx("div",{className:"cm-pickbar",children:o.jsxs(Ie,{variant:"toolbar","aria-pressed":h,onClick:()=>m(!h),children:[o.jsx(ge,{name:"plus"})," ",h?"Click an element on the page… (esc)":"Pick an element"]})}),o.jsxs("div",{className:"cm-list",children:[R.length===0&&o.jsx("p",{className:"cm-empty",children:E==="open"?f?"No open comments. Select text on the page, or pick an element, to leave one.":"No open comments. Select text on the page to leave one.":"Nothing resolved yet."}),R.map(U=>o.jsx(M7,{t:U,active:U.id===i,onFocus:()=>l(U.id===i?null:U.id),onJump:()=>{l(null),requestAnimationFrame(()=>l(U.id))},actions:w,canDelete:g||!!y&&U.author===y.toLowerCase()},U.id))]}),o.jsxs("footer",{className:"cm-foot",children:[o.jsx("textarea",{value:T,placeholder:"Comment on the whole file…",onChange:U=>A(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&H()}}),o.jsxs("div",{className:"cm-row",children:[o.jsxs("span",{className:"cm-hint",children:["Agents sweep these with ",o.jsx("code",{children:"bdrive comments"})]}),o.jsx(Ie,{variant:"primary",disabled:!T.trim()||M,onClick:()=>{H()},children:"Comment"})]})]})]})}function M7(e){const{t,active:n,onFocus:r,onJump:i,actions:l,canDelete:u}=e,f=!!(t.anchor.quote||t.anchor.element)&&!t.missing&&!t.resolved,[h,m]=b.useState(""),[y,g]=b.useState(!1),w=b.useRef(null);b.useEffect(()=>{n&&w.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const x=async S=>{if(!y){g(!0);try{await S()}catch(E){Ne(E.message)}finally{g(!1)}}},j=S=>x(async()=>{await l.act(t.id,S,h),m("")});return o.jsxs("div",{ref:w,className:"cm-card"+(n?" active":"")+(t.resolved?" resolved":""),"data-comment":t.id,children:[o.jsxs("div",{className:"cm-card-top",onClick:r,children:[o.jsx("span",{className:"cm-n",children:t.n}),o.jsx(vN,{a:t.anchor})]}),(t.outdated||t.missing)&&o.jsx("div",{className:"cm-flag",children:t.missing?"The file no longer exists":"The file changed since this comment"}),t.messages.map(S=>o.jsxs("div",{className:"cm-msg",children:[o.jsx("span",{className:"cm-av","aria-hidden":"true",children:T7(S.name||S.author||"?")}),o.jsxs("div",{className:"cm-msg-main",children:[o.jsxs("div",{className:"cm-who",children:[o.jsx("b",{children:S.name||S.author||"someone"})," ",o.jsx("time",{dateTime:S.time,title:new Date(S.time).toLocaleString(),children:CS(S.time)})]}),o.jsx("div",{className:"cm-body",children:S.body})]})]},S.id)),!t.resolved&&!t.missing&&o.jsxs("div",{className:"cm-queued",children:[o.jsx(ge,{name:"sparkle"}),o.jsxs("span",{children:["Queued for next agent sweep · ",o.jsx("code",{children:"bdrive comments"})]})]}),t.resolved&&t.resolved_at&&o.jsxs("div",{className:"cm-resolved",children:[o.jsx(ge,{name:"check"})," Resolved by ",t.resolved_name||t.resolved_by||"someone"," ",CS(t.resolved_at)]}),o.jsx("textarea",{className:"cm-reply",value:h,rows:h?3:1,placeholder:t.resolved?"Add a note…":"Reply…",onChange:S=>m(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&h.trim()&&j("reply")}}),o.jsxs("div",{className:"cm-row",children:[u&&o.jsx("button",{className:"cm-del",title:"Delete this thread","aria-label":"Delete this thread",onClick:()=>{x(async()=>{await ir("Delete comment","Delete this comment thread for everyone?","Delete",!0)&&await l.remove(t.id)})},children:o.jsx(ge,{name:"trash"})}),o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act",disabled:y,onClick:()=>{j(t.resolved?"reopen":"resolve")},children:[!t.resolved&&o.jsx(ge,{name:"check"}),t.resolved?"Reopen":h.trim()?"Reply & resolve":"Resolve"]}),f&&o.jsxs(Ie,{variant:"toolbar",className:"ghost cm-act cm-jump",onClick:i,children:[o.jsx(ge,{name:"jump"})," Jump to text"]}),o.jsx("span",{className:"cm-spacer"}),h.trim()&&o.jsx(Ie,{variant:"subtle",disabled:y,onClick:()=>{j("reply")},children:"Reply"})]})]})}function vN({a:e}){return!e.quote&&!e.element?o.jsx("div",{className:"cm-quote cm-el",children:"Whole file"}):o.jsxs("div",{className:"cm-anchor",children:[e.quote&&o.jsxs("div",{className:"cm-quote",children:[e.prefix&&o.jsx("span",{className:"cm-ctx",children:e.prefix}),o.jsx("span",{className:"cm-q",children:e.quote}),e.suffix&&o.jsx("span",{className:"cm-ctx",children:e.suffix})]}),e.element&&o.jsx("div",{className:"cm-quote cm-el",children:e.element})]})}function T7(e){const t=e.trim().split(/[\s@._-]+/).filter(Boolean);return t.length?(t[0][0]+(t[1]?.[0]??"")).toUpperCase():"?"}function yN(e){return[...e].sort((t,n)=>t.created.localeCompare(n.created)).map((t,n)=>({...t,n:n+1}))}function ed(e){return!!(e instanceof Element?e:e?.parentElement)?.closest("[data-bd-ignore]")}function td(){return typeof CSS<"u"&&"highlights"in CSS?CSS.highlights:null}function O7(e,t,n,r){return{x:Math.max(8,Math.min(e-n/2,innerWidth-n-8)),y:Math.max(60,Math.min(t+8,innerHeight-r-8))}}function CS(e){const t=(Date.now()-new Date(e).getTime())/1e3,n=new Intl.RelativeTimeFormat("en",{numeric:"auto"});return t<60?"just now":t<3600?n.format(-Math.round(t/60),"minute"):t<86400?n.format(-Math.round(t/3600),"hour"):t<86400*30?n.format(-Math.round(t/86400),"day"):new Date(e).toLocaleDateString()}var _S=1,A7=.9,D7=.8,z7=.17,_p=.1,Ep=.999,L7=.9999,$7=.99,F7=/[\\\/_+.#"@\[\(\{&]/,I7=/[\\\/_+.#"@\[\(\{&]/g,P7=/[\s-]/,xN=/[\s-]/g;function Tg(e,t,n,r,i,l,u){if(l===t.length)return i===e.length?_S:$7;var f=`${i},${l}`;if(u[f]!==void 0)return u[f];for(var h=r.charAt(l),m=n.indexOf(h,i),y=0,g,w,x,j;m>=0;)g=Tg(e,t,n,r,m+1,l+1,u),g>y&&(m===i?g*=_S:F7.test(e.charAt(m-1))?(g*=D7,x=e.slice(i,m-1).match(I7),x&&i>0&&(g*=Math.pow(Ep,x.length))):P7.test(e.charAt(m-1))?(g*=A7,j=e.slice(i,m-1).match(xN),j&&i>0&&(g*=Math.pow(Ep,j.length))):(g*=z7,i>0&&(g*=Math.pow(Ep,m-i))),e.charAt(m)!==t.charAt(l)&&(g*=L7)),(g<_p&&n.charAt(m-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&n.charAt(m-1)!==r.charAt(l))&&(w=Tg(e,t,n,r,m+1,l+2,u),w*_p>g&&(g=w*_p)),g>y&&(y=g),m=n.indexOf(h,m+1);return u[f]=y,y}function ES(e){return e.toLowerCase().replace(xN," ")}function U7(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tg(e,t,ES(e),ES(t),0,0,{})}var Ll='[cmdk-group=""]',Np='[cmdk-group-items=""]',V7='[cmdk-group-heading=""]',bN='[cmdk-item=""]',NS=`${bN}:not([aria-disabled="true"])`,Og="cmdk-item-select",yo="data-value",H7=(e,t,n)=>U7(e,t,n),wN=b.createContext(void 0),vc=()=>b.useContext(wN),SN=b.createContext(void 0),yy=()=>b.useContext(SN),jN=b.createContext(void 0),CN=b.forwardRef((e,t)=>{let n=xo(()=>{var D,B;return{search:"",value:(B=(D=e.value)!=null?D:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=xo(()=>new Set),i=xo(()=>new Map),l=xo(()=>new Map),u=xo(()=>new Set),f=_N(e),{label:h,children:m,value:y,onValueChange:g,filter:w,shouldFilter:x,loop:j,disablePointerSelection:S=!1,vimBindings:E=!0,..._}=e,N=ds(),R=ds(),T=ds(),A=b.useRef(null),M=eq();xi(()=>{if(y!==void 0){let D=y.trim();n.current.value=D,L.emit()}},[y]),xi(()=>{M(6,ae)},[]);let L=b.useMemo(()=>({subscribe:D=>(u.current.add(D),()=>u.current.delete(D)),snapshot:()=>n.current,setState:(D,B,P)=>{var I,re,he,we;if(!Object.is(n.current[D],B)){if(n.current[D]=B,D==="search")Q(),Z(),M(1,X);else if(D==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(T);Se?Se.focus():(I=document.getElementById(N))==null||I.focus()}if(M(7,()=>{var Se;n.current.selectedItemId=(Se=le())==null?void 0:Se.id,L.emit()}),P||M(5,ae),((re=f.current)==null?void 0:re.value)!==void 0){let Se=B??"";(we=(he=f.current).onValueChange)==null||we.call(he,Se);return}}L.emit()}},emit:()=>{u.current.forEach(D=>D())}}),[]),H=b.useMemo(()=>({value:(D,B,P)=>{var I;B!==((I=l.current.get(D))==null?void 0:I.value)&&(l.current.set(D,{value:B,keywords:P}),n.current.filtered.items.set(D,U(B,P)),M(2,()=>{Z(),L.emit()}))},item:(D,B)=>(r.current.add(D),B&&(i.current.has(B)?i.current.get(B).add(D):i.current.set(B,new Set([D]))),M(3,()=>{Q(),Z(),n.current.value||X(),L.emit()}),()=>{l.current.delete(D),r.current.delete(D),n.current.filtered.items.delete(D);let P=le();M(4,()=>{Q(),P?.getAttribute("id")===D&&X(),L.emit()})}),group:D=>(i.current.has(D)||i.current.set(D,new Set),()=>{l.current.delete(D),i.current.delete(D)}),filter:()=>f.current.shouldFilter,label:h||e["aria-label"],getDisablePointerSelection:()=>f.current.disablePointerSelection,listId:N,inputId:T,labelId:R,listInnerRef:A}),[]);function U(D,B){var P,I;let re=(I=(P=f.current)==null?void 0:P.filter)!=null?I:H7;return D?re(D,n.current.search,B):0}function Z(){if(!n.current.search||f.current.shouldFilter===!1)return;let D=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(I=>{let re=i.current.get(I),he=0;re.forEach(we=>{let Se=D.get(we);he=Math.max(Se,he)}),B.push([I,he])});let P=A.current;be().sort((I,re)=>{var he,we;let Se=I.getAttribute("id"),ve=re.getAttribute("id");return((he=D.get(ve))!=null?he:0)-((we=D.get(Se))!=null?we:0)}).forEach(I=>{let re=I.closest(Np);re?re.appendChild(I.parentElement===re?I:I.closest(`${Np} > *`)):P.appendChild(I.parentElement===P?I:I.closest(`${Np} > *`))}),B.sort((I,re)=>re[1]-I[1]).forEach(I=>{var re;let he=(re=A.current)==null?void 0:re.querySelector(`${Ll}[${yo}="${encodeURIComponent(I[0])}"]`);he?.parentElement.appendChild(he)})}function X(){let D=be().find(P=>P.getAttribute("aria-disabled")!=="true"),B=D?.getAttribute(yo);L.setState("value",B||void 0)}function Q(){var D,B,P,I;if(!n.current.search||f.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let he of r.current){let we=(B=(D=l.current.get(he))==null?void 0:D.value)!=null?B:"",Se=(I=(P=l.current.get(he))==null?void 0:P.keywords)!=null?I:[],ve=U(we,Se);n.current.filtered.items.set(he,ve),ve>0&&re++}for(let[he,we]of i.current)for(let Se of we)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(he);break}n.current.filtered.count=re}function ae(){var D,B,P;let I=le();I&&(((D=I.parentElement)==null?void 0:D.firstChild)===I&&((P=(B=I.closest(Ll))==null?void 0:B.querySelector(V7))==null||P.scrollIntoView({block:"nearest"})),I.scrollIntoView({block:"nearest"}))}function le(){var D;return(D=A.current)==null?void 0:D.querySelector(`${bN}[aria-selected="true"]`)}function be(){var D;return Array.from(((D=A.current)==null?void 0:D.querySelectorAll(NS))||[])}function $(D){let B=be()[D];B&&L.setState("value",B.getAttribute(yo))}function q(D){var B;let P=le(),I=be(),re=I.findIndex(we=>we===P),he=I[re+D];(B=f.current)!=null&&B.loop&&(he=re+D<0?I[I.length-1]:re+D===I.length?I[0]:I[re+D]),he&&L.setState("value",he.getAttribute(yo))}function V(D){let B=le(),P=B?.closest(Ll),I;for(;P&&!I;)P=D>0?W7(P,Ll):J7(P,Ll),I=P?.querySelector(NS);I?L.setState("value",I.getAttribute(yo)):q(D)}let ee=()=>$(be().length-1),K=D=>{D.preventDefault(),D.metaKey?ee():D.altKey?V(1):q(1)},O=D=>{D.preventDefault(),D.metaKey?$(0):D.altKey?V(-1):q(-1)};return b.createElement(lt.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:D=>{var B;(B=_.onKeyDown)==null||B.call(_,D);let P=D.nativeEvent.isComposing||D.keyCode===229;if(!(D.defaultPrevented||P))switch(D.key){case"n":case"j":{E&&D.ctrlKey&&K(D);break}case"ArrowDown":{K(D);break}case"p":case"k":{E&&D.ctrlKey&&O(D);break}case"ArrowUp":{O(D);break}case"Home":{D.preventDefault(),$(0);break}case"End":{D.preventDefault(),ee();break}case"Enter":{D.preventDefault();let I=le();if(I){let re=new Event(Og);I.dispatchEvent(re)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:H.inputId,id:H.labelId,style:nq},h),Tf(e,D=>b.createElement(SN.Provider,{value:L},b.createElement(wN.Provider,{value:H},D))))}),q7=b.forwardRef((e,t)=>{var n,r;let i=ds(),l=b.useRef(null),u=b.useContext(jN),f=vc(),h=_N(e),m=(r=(n=h.current)==null?void 0:n.forceMount)!=null?r:u?.forceMount;xi(()=>{if(!m)return f.item(i,u?.id)},[m]);let y=EN(i,l,[e.value,e.children,l],e.keywords),g=yy(),w=Ea(M=>M.value&&M.value===y.current),x=Ea(M=>m||f.filter()===!1?!0:M.search?M.filtered.items.get(i)>0:!0);b.useEffect(()=>{let M=l.current;if(!(!M||e.disabled))return M.addEventListener(Og,j),()=>M.removeEventListener(Og,j)},[x,e.onSelect,e.disabled]);function j(){var M,L;S(),(L=(M=h.current).onSelect)==null||L.call(M,y.current)}function S(){g.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:_,onSelect:N,forceMount:R,keywords:T,...A}=e;return b.createElement(lt.div,{ref:Eo(l,t),...A,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!w,"data-disabled":!!E,"data-selected":!!w,onPointerMove:E||f.getDisablePointerSelection()?void 0:S,onClick:E?void 0:j},e.children)}),B7=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...l}=e,u=ds(),f=b.useRef(null),h=b.useRef(null),m=ds(),y=vc(),g=Ea(x=>i||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);xi(()=>y.group(u),[]),EN(u,f,[e.value,e.heading,h]);let w=b.useMemo(()=>({id:u,forceMount:i}),[i]);return b.createElement(lt.div,{ref:Eo(f,t),...l,"cmdk-group":"",role:"presentation",hidden:g?void 0:!0},n&&b.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:m},n),Tf(e,x=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?m:void 0},b.createElement(jN.Provider,{value:w},x))))}),G7=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),l=Ea(u=>!u.search);return!n&&!l?null:b.createElement(lt.div,{ref:Eo(i,t),...r,"cmdk-separator":"",role:"separator"})}),K7=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,l=yy(),u=Ea(m=>m.search),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),b.createElement(lt.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":f,id:h.inputId,type:"text",value:i?e.value:u,onChange:m=>{i||l.setState("search",m.target.value),n?.(m.target.value)}})}),Z7=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,l=b.useRef(null),u=b.useRef(null),f=Ea(m=>m.selectedItemId),h=vc();return b.useEffect(()=>{if(u.current&&l.current){let m=u.current,y=l.current,g,w=new ResizeObserver(()=>{g=requestAnimationFrame(()=>{let x=m.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return w.observe(m),()=>{cancelAnimationFrame(g),w.unobserve(m)}}},[]),b.createElement(lt.div,{ref:Eo(l,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":f,"aria-label":r,id:h.listId},Tf(e,m=>b.createElement("div",{ref:Eo(u,h.listInnerRef),"cmdk-list-sizer":""},m)))}),Y7=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:l,container:u,...f}=e;return b.createElement(Kg,{open:n,onOpenChange:r},b.createElement(Yg,{container:u},b.createElement(Qg,{"cmdk-overlay":"",className:i}),b.createElement(Xg,{"aria-label":e.label,"cmdk-dialog":"",className:l},b.createElement(CN,{ref:t,...f}))))}),Q7=b.forwardRef((e,t)=>Ea(n=>n.filtered.count===0)?b.createElement(lt.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),X7=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...l}=e;return b.createElement(lt.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Tf(e,u=>b.createElement("div",{"aria-hidden":!0},u)))}),yc=Object.assign(CN,{List:Z7,Item:q7,Input:K7,Group:B7,Separator:G7,Dialog:Y7,Empty:Q7,Loading:X7});function W7(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function J7(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _N(e){let t=b.useRef(e);return xi(()=>{t.current=e}),t}var xi=typeof window>"u"?b.useEffect:b.useLayoutEffect;function xo(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Ea(e){let t=yy(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function EN(e,t,n,r=[]){let i=b.useRef(),l=vc();return xi(()=>{var u;let f=(()=>{var m;for(let y of n){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(m=y.current.textContent)==null?void 0:m.trim():i.current}})(),h=r.map(m=>m.trim());l.value(e,f,h),(u=t.current)==null||u.setAttribute(yo,f),i.current=f}),i}var eq=()=>{let[e,t]=b.useState(),n=xo(()=>new Map);return xi(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function tq(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Tf({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(tq(t),{ref:t.ref},n(t.props.children)):n(t)}var nq={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function sq({className:e,...t}){return o.jsx(yc,{"data-slot":"command",className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function rq({className:e,...t}){return o.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[o.jsx(X_,{className:"size-4 shrink-0 opacity-50"}),o.jsx(yc.Input,{"data-slot":"command-input",className:at("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function aq({className:e,...t}){return o.jsx(yc.List,{"data-slot":"command-list",className:at("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function iq({className:e,...t}){return o.jsx(yc.Group,{"data-slot":"command-group",className:at("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t})}function kS({className:e,...t}){return o.jsx(yc.Item,{"data-slot":"command-item",className:at("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}const oq=40,lq=5;function RS({item:e,ranges:t,hint:n}){const r=e.kind==="file"||e.kind==="folder",i=r?e.label.lastIndexOf("/")+1:0;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"picon",children:o.jsx(ge,{name:e.icon})}),o.jsxs("span",{className:"ptext",children:[o.jsx(Ng,{className:"plabel",text:e.label.slice(i),ranges:t,offset:i}),r&&i>0&&o.jsx(Ng,{className:"ploc",text:e.label.slice(0,i-1),ranges:t}),!r&&n&&o.jsx("span",{className:"ploc",children:n})]}),!r&&o.jsx("span",{className:"pkind",children:e.kind})]})}function cq({open:e,onClose:t,candidates:n,recent:r=[],initialQuery:i=""}){const[l,u]=b.useState("");b.useEffect(()=>{e&&u(i)},[e,i]);const f=b.useMemo(()=>e?n():[],[e,n]),h=l.trim()!=="",m=b.useMemo(()=>h?f.map(x=>W2(x.label)):[],[f,h]),y=b.useMemo(()=>J2(l,m,{limit:oq}).hits,[l,m]),g=b.useMemo(()=>{const x=new Map,j=new Map;for(const E of f)E.kind==="file"&&j.set(E.label,E);const S=r.flatMap(E=>j.get(E)??[]).slice(0,lq);S.length&&x.set("Recent",S);for(const E of f)E.group&&(x.get(E.group)??x.set(E.group,[]).get(E.group)).push(E);return[...x]},[f,r]),w=x=>{t(),x.run()};return o.jsx(uc,{open:e,onOpenChange:x=>!x&&t(),children:o.jsxs(dc,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[o.jsx(zo,{className:"sr-only",children:"Search file names, projects and actions"}),o.jsxs(sq,{shouldFilter:!1,loop:!0,children:[o.jsxs("div",{id:"palette-inputwrap",children:[o.jsx(ge,{name:"search"}),o.jsx(rq,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:l,onValueChange:u})]}),o.jsx(aq,{children:h?y.length===0?o.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):y.map(x=>{const j=f[x.index];return o.jsx(kS,{value:String(x.index),"data-kind":j.kind,onSelect:()=>w(j),children:o.jsx(RS,{item:j,ranges:x.ranges,hint:j.hint})},x.index)}):g.map(([x,j])=>o.jsx(iq,{heading:x,children:j.map(S=>o.jsx(kS,{value:x+":"+S.kind+":"+S.label,"data-kind":S.kind,onSelect:()=>w(S),children:o.jsx(RS,{item:S,ranges:[],hint:S.hint===x?void 0:S.hint})},S.kind+":"+S.label))},x))}),o.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ↵ open · esc close"})]})]})})}const NN=e=>"bdrive.recent."+e,uq=12;function dq(e,t,n,r=uq){return[{path:t,at:n},...e.filter(i=>i.path!==t)].slice(0,r)}function fq(e){try{const t=JSON.parse(e||"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n.path=="string"&&typeof n.at=="number"&&Number.isFinite(n.at)):[]}catch{return[]}}const Ag=new Map,hq=[],Dg=new Set;function mq(e){return Dg.add(e),()=>{Dg.delete(e)}}function kN(e){let t=Ag.get(e);if(!t){let n=null;try{n=localStorage.getItem(NN(e))}catch{}t=fq(n),Ag.set(e,t)}return t}function pq(e,t){const n=dq(kN(e),t,Date.now());Ag.set(e,n);try{localStorage.setItem(NN(e),JSON.stringify(n))}catch{}for(const r of Dg)r()}function RN(e){return b.useSyncExternalStore(mq,()=>e?kN(e):hq)}function xy(e){return new Set(e.entries.map(t=>t.path)).size}function MN(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),n=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const f=n.get(t(l));if(f){f.entries.push(l),f.idx.push(u);return}n.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const r=[],i=new Set;return e.forEach((l,u)=>{const f=l.note||l.session?n.get(t(l)):void 0;if(!f||xy(f)<2){r.push({i:u});return}i.has(f)||(i.add(f),r.push({run:f,i:u}))}),r}function gq(e,t=new Date){const n=t.getHours(),r=n<5?"Good evening":n<12?"Good morning":n<18?"Good afternoon":"Good evening",i=(e||"").trim().split(/\s+/)[0];return i?r+", "+i:r}function vq(e,t){const n=new Set;let r=0,i=0;for(const l of e)r++,n.add(l.path),yi(l)&&i++;return{changes:r,files:n.size,agent:i,capped:t}}function yq(e,t){const n=l=>l.seq?(l.device?.id??"")+"\0"+l.seq:l.time+"\0"+l.path+"\0"+l.kind+"\0"+(l.device?.id??""),r=new Set,i=[];for(const l of[...e,...t]){const u=n(l);r.has(u)||(r.add(u),i.push(l))}return i.sort((l,u)=>Date.parse(u.time)-Date.parse(l.time))}function xq(e,t){const n=new Map;for(const r of e){const i=r.device?.id||r.device?.name;if(!i)continue;let l=n.get(i);l||(l={id:i,name:r.device.name||i,last:Date.parse(r.time)||0,you:!1},n.set(i,l)),!l.agent&&yi(r)&&(l.agent=Rf(r.note)),t&&r.user===t&&(l.you=!0)}return[...n.values()].sort((r,i)=>i.last-r.last)}const bq=15*6e4;function wq(e){const t=[];for(const n of e){const r=Vr(n.path);r&&t.push({kind:"conflict",path:n.path,original:r.original,device:r.device})}return t}function Sq(e,t,n=Date.now(),r=3){if(!t)return[];const i=[];for(const l of e){const u=t[l.path],f=iy(l.time,n);if(!u||f===null)continue;const h=Ps(u);C2(h,f)&&i.push({kind:"stale",path:l.path,reads:h,days:f})}return i.sort((l,u)=>u.reads-l.reads).slice(0,r)}function jq(e){return e===null||e>30?"stale":e>7?"aging":"fresh"}function Cq(e,t,n=Date.now()){if(!e||!t)return[];const r=l=>{let u=l.dir?0:Date.parse(l.time||"")||0;for(const f of l.children||[])u=Math.max(u,r(f));return u},i=[];for(const l of e.children||[]){if(!l.dir)continue;const u=fd(t,l.path,!0),f=u?Ps(u):0;if(!f)continue;const h=r(l);i.push({name:l.name,reads:f,fresh:jq(h?(n-h)/864e5:null)})}return i.sort((l,u)=>u.reads-l.reads)}const _q=200,Eq=e=>"/api/p/"+e+"/",MS=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")+1):"",Ud=e=>e.slice(e.lastIndexOf("/")+1);function Nq(e){const{project:t,flatFiles:n,heatMap:r,me:i}=e,l=t.id,u=Eq(l),f=ry(l),h=RN(l),[m,y]=b.useState(""),g=T2(l),w=rt({queryKey:["homeHistory",u],queryFn:()=>We(u+"history?n="+_q),enabled:e.loaded&&n.length>0,retry:!1,staleTime:6e4}),x=rt({queryKey:["comments",u,"open-all"],queryFn:()=>We(u+"comments?status=open"),enabled:e.comments&&n.length>0,retry:!1}),j=b.useMemo(()=>g.data?.entries||[],[g.data]),S=b.useMemo(()=>yq(j,w.data?.entries||[]),[j,w.data]),E=b.useMemo(()=>vq(j,j.length>=Ld),[j]),_=b.useMemo(()=>xq(S,i?.email),[S,i?.email]),N=b.useMemo(()=>new Set(n.map(U=>U.path)),[n]),R=b.useMemo(()=>h.filter(U=>N.has(U.path)).slice(0,4),[h,N]),T=b.useMemo(()=>{const U=wq(n),Z=new Set(n.filter(Q=>i&&Q.user===i.email).map(Q=>Q.path)),X=new Map;for(const Q of x.data?.comments||[]){const ae=!!i&&(Q.author===i.email||Q.messages.some(le=>le.author===i.email));!Z.has(Q.path)&&!ae||X.set(Q.path,(X.get(Q.path)||0)+1)}for(const[Q,ae]of X)U.push({kind:"comments",path:Q,count:ae});return U.concat(Sq(n,r))},[n,x.data,r,i]),A=b.useMemo(()=>Cq(e.tree,r),[e.tree,r]),M=b.useMemo(()=>{const U=m?S.filter(Z=>m==="agent"===yi(Z)):S;return{list:U,items:MN(U).slice(0,6)}},[S,m]);if(!e.loaded)return o.jsx("div",{className:"empty",children:"Loading…"});if(n.length===0)return o.jsx("div",{className:"home home-empty",children:o.jsx(I2,{project:t,existing:e.existing})});const L=U=>$n(U,l),H=un("history",l,"",m?{actor:m}:void 0);return o.jsxs("div",{className:"home",children:[o.jsxs("header",{className:"home-head",children:[o.jsx("h1",{className:"home-greet",children:gq(i?.name)}),o.jsx("p",{className:"home-since",children:g.data?E.changes===0?`Nothing changed since your last visit ${vo(f)}.`:`Since your last visit ${vo(f)} — ${E.changes}${E.capped?"+":""} change${E.changes===1?"":"s"} across ${E.files} file${E.files===1?"":"s"}`+(E.agent?`, ${E.agent} of them by agents.`:"."):t.description||""})]}),R.length>0&&o.jsxs("section",{className:"home-sec home-jump","aria-label":"Jump back in",children:[o.jsx("h2",{className:"home-eyebrow",children:"Jump back in"}),o.jsx("div",{className:"home-cards",children:R.map(U=>o.jsxs("a",{className:"home-card",...Pn(L(U.path)),children:[o.jsxs("span",{className:"hc-name",children:[o.jsx(ge,{name:"doc"}),Ud(U.path)]}),o.jsx("span",{className:"hc-dir",children:MS(U.path)||"/"}),o.jsxs("span",{className:"hc-when",children:["Viewed ",vo(U.at)]})]},U.path))})]}),o.jsxs("div",{className:"home-grid",children:[o.jsxs("div",{className:"home-main",children:[o.jsxs("section",{className:"home-sec home-attn","aria-label":"Needs your attention",children:[o.jsxs("h2",{className:"home-h",children:["Needs your attention",T.length>0&&o.jsx("span",{className:"home-count",children:T.length})]}),T.length===0?o.jsx("p",{className:"home-none",children:"Nothing needs you right now."}):o.jsx("ul",{className:"home-list",children:T.map(U=>o.jsx(kq,{a:U,href:L},U.kind+U.path))})]}),o.jsxs("section",{className:"home-sec home-activity","aria-label":"Recent activity",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Recent activity"}),o.jsx("a",{className:"home-more",...Pn(H),children:"View all activity →"})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:[["","Everyone"],["agent","Agents"],["human","People"]].map(([U,Z])=>o.jsx("button",{"aria-pressed":m===U,onClick:()=>y(U),children:Z},U))}),w.isError?o.jsx("p",{className:"home-none",children:"Activity is unavailable right now."}):w.data?M.items.length===0?o.jsx("p",{className:"home-none",children:"No changes yet."}):o.jsx("ul",{className:"home-feed",children:M.items.map(U=>{const Z=M.list[U.i],X=U.run,Q=yi(Z),ae=Q?Rf(Z.note):Z.user_name||Z.author||"Someone",le=X?`${Z.kind==="delete"?"changed":"updated"} ${xy(X)} files`:Z.kind==="add"?"created":Z.kind==="delete"?"deleted":"edited";return o.jsxs("li",{className:"home-fe",children:[o.jsx("span",{className:"fe-avatar "+(Q?"agent":"human"),"aria-hidden":"true",children:o.jsx(ge,{name:Q?"sparkle":"users"})}),o.jsxs("div",{className:"fe-body",children:[o.jsxs("div",{children:[o.jsx("b",{className:"fe-who",children:ae})," ",o.jsx("span",{className:"fe-what",children:le})]}),X?o.jsx("span",{className:"fe-path",children:MS(Z.path)||Ud(Z.path)}):Z.kind==="delete"?o.jsx("span",{className:"fe-path del",children:Z.path}):o.jsx("a",{className:"fe-path",...Pn(L(Z.path)),children:Z.path}),Z.device?.name&&o.jsx("span",{className:"fe-dev",children:Z.device.name})]}),o.jsx("span",{className:"fe-when",children:vo(Date.parse(Z.time))})]},U.i)})}):o.jsx("p",{className:"home-none",children:"Loading…"})]})]}),o.jsxs("aside",{className:"home-side",children:[o.jsxs("section",{className:"home-sec home-devices","aria-label":"Devices",children:[o.jsx("h2",{className:"home-h",children:"Devices"}),_.length===0?o.jsx("p",{className:"home-none",children:"No device has synced a change recently."}):o.jsxs("ul",{className:"home-devlist",children:[_.slice(0,5).map(U=>{const Z=Date.now()-U.last5&&o.jsxs("li",{className:"home-none",children:["+ ",_.length-5," more devices"]})]})]}),o.jsxs("section",{className:"home-sec home-connect","aria-label":"Connect another device",children:[o.jsxs("h2",{className:"home-h",children:[o.jsx(ge,{name:"terminal"}),"Connect another device"]}),o.jsx("p",{className:"gd-desc",children:"Paste this into your coding agent in the folder you want synced."}),o.jsx(tc,{code:Nf(window.location.origin,{project:t})}),o.jsx("a",{className:"home-more",...Pn(un("install",l)),children:"Full setup guide →"})]}),A.length>0&&o.jsxs("section",{className:"home-sec home-reads","aria-label":"Where reads go",children:[o.jsxs("div",{className:"home-row",children:[o.jsx("h2",{className:"home-h",children:"Where reads go"}),o.jsx("a",{className:"home-more",...Pn(un("dashboard",l)),children:"Insights →"})]}),o.jsx("ul",{className:"home-bars",children:A.slice(0,6).map(U=>o.jsxs("li",{className:"fresh-"+U.fresh,children:[o.jsxs("a",{className:"hb-label",...Pn(L(U.name)),children:[o.jsx("span",{children:U.name}),o.jsx("span",{className:"hb-n",children:U.reads})]}),o.jsx("span",{className:"hb-track",children:o.jsx("span",{className:"hb-fill",style:{width:100*U.reads/A[0].reads+"%"}})})]},U.name))}),o.jsxs("div",{className:"home-legend",children:[o.jsx("span",{className:"fresh-fresh",children:"fresh"}),o.jsx("span",{className:"fresh-aging",children:"aging"}),o.jsx("span",{className:"fresh-stale",children:"stale"})]})]})]})]}),e.tree&&o.jsx("section",{className:"home-sec home-files","aria-label":"Browse files",id:"home-files",children:o.jsx(hN,{node:{...e.tree,name:t.name,path:""},heatMap:r,folders:e.folders,hub:!1,apiBase:u,onOpen:e.onOpen,onFullHistory:e.onFullHistory,onRendered:e.onRendered})})]})}function kq({a:e,href:t}){let n,r,i,l,u;return e.kind==="conflict"?(n="alert",u="conflict",r=o.jsxs(o.Fragment,{children:["Sync conflict on ",o.jsx("b",{children:e.original})]}),i=`A diverged copy from ${e.device||"another device"} was kept beside it`,l="Resolve"):e.kind==="comments"?(n="comment",u="comments",r=o.jsxs(o.Fragment,{children:[e.count," open comment",e.count===1?"":"s"," on ",o.jsx("b",{children:Ud(e.path)})]}),i=e.path,l="Reply"):(n="clock",u="stale",r=o.jsxs(o.Fragment,{children:[o.jsx("b",{children:Ud(e.path)})," is read a lot but going stale"]}),i=`${e.reads} reads in 30d · last changed ${oy(e.days)}`,l="Review"),o.jsxs("li",{className:"home-attn-row "+u,children:[o.jsx("span",{className:"ha-icon","aria-hidden":"true",children:o.jsx(ge,{name:n})}),o.jsxs("div",{className:"ha-text",children:[o.jsx("span",{className:"ha-title",children:r}),o.jsx("span",{className:"ha-sub",children:i})]}),o.jsx("a",{className:e.kind==="conflict"?"pbtn":"btn",...Pn(t(e.path)),children:l})]})}function Rq(e,t){return rt({queryKey:["heatDevices",e],queryFn:()=>We(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const Mq=["all","human","agent","share"],TN={all:"All reads",human:"People",agent:"Agents",share:"Share links"},zg={agent:"agents",human:"people",share:"share"},ON="bd.insights.thresholds.v2",TS="bd.insights.thresholds",OS={hot:3,stale:30};function AS(e){const t=JSON.parse(e||"null");return t&&t.hot>=1&&t.stale>=1?{hot:+t.hot,stale:+t.stale}:null}function Tq(){try{const e=AS(localStorage.getItem(ON));if(e)return e;const t=AS(localStorage.getItem(TS));if(localStorage.removeItem(TS),t&&(t.hot!==OS.hot||t.stale!==OS.stale))return t}catch{}return{hot:S2,stale:j2}}const Us=(e,t)=>`${e} ${t}${e===1?"":"s"}`,xc=e=>{const t=Math.round(e);return t===0?"today":t===1?"1 day ago":`${t} days ago`},Oq=e=>`${e.human} people · ${e.agent} agents · ${e.share} share`;function Of(e){const t=[e.path,`${Us(e.reads,"read")}/30d (${Oq(e)})`];return e.orphan?t.push("no longer in the project"):t.push(`changed ${xc(e.days)}${e.editor?" by "+e.editor:""}`),e.empty?t.push("⛔ empty but still read"):e.danger&&t.push("⚠ hot + stale"),t.join(" — ")}function AN({p:e}){return e.empty?o.jsx("span",{className:"in-flag in-flag-empty",role:"img","aria-label":"emptied",children:"⛔"}):e.danger?o.jsx("span",{className:"in-flag in-flag-stale",role:"img","aria-label":"hot and stale",children:"⚠"}):null}function Aq(e,t){const n=t.filter(i=>!i.size).map(i=>i.path+"@"+(i.time||"")).join(` `),{data:r}=rt({queryKey:["emptied",e,n],queryFn:()=>We(e+"history/emptied"),enabled:!!e&&n!=="",staleTime:6e4});return new Set(r?.paths??[])}function Dq(e){const t=Aq(e.apiBase,e.flatFiles),[n,r]=b.useState("all"),[i,l]=b.useState(Tq);b.useEffect(()=>{try{localStorage.setItem(ON,JSON.stringify(i))}catch{}},[i]);const{flatFiles:u,heatMap:f,devices:h,scope:m}=e,y=R=>!m||R===m||R.startsWith(m+"/"),g=m?u.filter(R=>y(R.path)):u;if(!e.loading&&!g.length)return o.jsxs("div",{className:"insights",children:[o.jsxs("h1",{className:"in-title",children:["Knowledge insights",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsxs("div",{className:"dl-empty in-blank",children:[o.jsx("p",{children:m?`Nothing in ${m} to chart yet.`:"Nothing to chart yet."}),o.jsx("p",{children:m?`No files under ${m} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&o.jsx("a",{className:"pbtn",...Pn(e.installHref),children:"Set up a device →"})]})]});const w=h&&m?h.map(R=>{const T=Object.create(null);for(const[A,M]of Object.entries(R.folders||{}))y(A)&&(T[A]=M);return{...R,folders:T}}).filter(R=>Object.keys(R.folders).length>0):h,x=Date.now(),j=R=>n==="all"?Ps(R):R[n]||0,S=g.map(R=>{const T=f&&f[R.path]||{},A=R.time?Math.max(0,(x-new Date(R.time).getTime())/864e5):0,M=j(T),L=t.has(R.path)&&M>0;return{path:R.path,reads:M,agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:A,editor:R.user_name||R.user||R.author||"",empty:L,danger:!L&&M>=i.hot&&A>=i.stale}}),E=wU(f,new Set(u.map(R=>R.path))).filter(y).map(R=>{const T=f[R];return{path:R,reads:j(T),agent:T.agent||0,human:T.human||0,share:T.share||0,total:Ps(T),days:0,editor:"",danger:!1,empty:!1,orphan:!0}}).filter(R=>R.reads>0),_=E.length>0?o.jsxs("p",{className:"in-legend in-orphan-note",children:[Us(E.length,"file")," with reads ",E.length===1?"is":"are"," no longer in the project — see Hot path."]}):null,N=n==="all"?["agent","human","share"]:[n];return o.jsxs("div",{className:"insights",children:[o.jsxs("div",{className:"in-top",children:[o.jsxs("h1",{className:"in-title",children:["What the team and its agents actually read",m?o.jsxs("span",{className:"in-scope",children:[" · ",m]}):null]}),o.jsx("div",{className:"in-lens",role:"group","aria-label":"Reader lens",children:Mq.map(R=>o.jsxs("button",{className:"in-lens-btn"+(R===n?" active":""),"aria-pressed":R===n,onClick:()=>r(R),children:[R!=="all"&&o.jsx("span",{className:"in-sw "+R,"aria-hidden":!0}),TN[R]]},R))})]}),o.jsx("p",{className:"dl-sub",children:m?`Reads over the last 30 days × freshness, for ${m} and everything in it. ${Ir}`:"Last 30 days · one read = one visit. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ir}),o.jsx(zq,{pts:S,orphans:E,lens:n,th:i}),o.jsx(Pq,{pts:S,th:i,setTh:l,lens:n,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),o.jsxs("div",{className:"in-split",children:[o.jsxs("section",{className:"in-sec in-sec-map",children:[o.jsx(Zq,{pts:S,scope:m||"",onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),_]}),o.jsxs("section",{className:"in-sec in-sec-hot",children:[o.jsx("h2",{className:"in-h2",children:"Hot path"}),o.jsx("p",{className:"in-sub",children:"Agents and people live on different files — so each gets its own chart."}),o.jsx(Wq,{pts:[...S,...E],kinds:N,th:i,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory})]})]}),o.jsx(eB,{pts:S,th:i,onOpenFile:e.onOpenFile}),_,w&&w.length>0&&o.jsx(rB,{devices:w,lens:n})]})}function Af(e){const[t,n]=b.useState(!1);return o.jsxs("section",{className:"in-sec","data-sec":e.id,children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:e.title}),e.sub&&o.jsx("p",{className:"in-sub",children:e.sub})]}),o.jsxs("div",{className:"in-sec-tools",children:[e.aside,o.jsx("button",{className:"in-astable","aria-pressed":t,onClick:()=>n(!t),children:t?"View as chart":"View as table"})]})]}),t?o.jsx("div",{className:"in-table-wrap",children:e.table()}):e.children]})}function zq({pts:e,orphans:t,lens:n,th:r}){const i=[...e,...t],l=x=>i.reduce((j,S)=>j+(n==="all"||n===x?S[x]:0),0),u={human:l("human"),agent:l("agent"),share:l("share")},f=u.human+u.agent+u.share,h=e.filter(x=>x.reads>0).length,m=e.length?Math.round(h/e.length*100):0,y=e.filter(x=>x.danger).length,g=e.filter(x=>x.empty),w=g.reduce((x,j)=>x+j.reads,0);return o.jsxs("div",{className:"in-kpis",children:[o.jsxs("div",{className:"in-kpi","data-kpi":"reads",children:[o.jsx("div",{className:"in-kpi-l",children:"Reads"}),o.jsx("div",{className:"in-kpi-v",children:f.toLocaleString("en")}),o.jsx("div",{className:"in-kpi-bar","aria-hidden":!0,children:["human","agent","share"].map(x=>u[x]?o.jsx("span",{className:"in-hp-"+x,style:{flexGrow:u[x]}},x):null)}),o.jsx("div",{className:"in-kpi-n",children:["human","agent","share"].map(x=>o.jsxs("span",{"data-kind":x,children:[o.jsx("span",{className:"in-sw "+x,"aria-hidden":!0})," ",u[x].toLocaleString("en")," ",zg[x]]},x))})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"coverage",children:[o.jsx("div",{className:"in-kpi-l",children:"Files read at least once"}),o.jsxs("div",{className:"in-kpi-v",children:[m,"% ",o.jsxs("small",{children:[h.toLocaleString("en")," of ",e.length.toLocaleString("en")]})]}),o.jsx("div",{className:"in-kpi-bar in-kpi-meter","aria-hidden":!0,children:o.jsx("span",{className:"in-kpi-fill",style:{width:m+"%"}})})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"stale",children:[o.jsx("div",{className:"in-kpi-l",children:"Hot but stale"}),o.jsxs("div",{className:"in-kpi-v",children:[y,y>0&&o.jsx("span",{className:"in-status in-status-warn",children:"⚠ Review"})]}),o.jsxs("div",{className:"in-kpi-n",children:["≥ ",Us(r.hot,"read")," and unchanged for ",r.stale,"+ days"]})]}),o.jsxs("div",{className:"in-kpi","data-kpi":"empty",children:[o.jsx("div",{className:"in-kpi-l",children:"Read, but now empty"}),o.jsxs("div",{className:"in-kpi-v",children:[g.length,g.length>0&&o.jsx("span",{className:"in-status in-status-crit",children:"⛔ Restore"})]}),o.jsx("div",{className:"in-kpi-n",children:g.length?`0-byte files opened ${Us(w,"time")}`:"no empty file is being read"})]})]})}function Lq(e){if(e.empty)return"Emptied, still opened";const t=e.total||1;return e.share/t>=.5?"Mostly read via a public share link":e.agent/t>=.95?"Only agents read it":e.agent/t>=.6?"Agents rely on it, nobody updates it":e.human/t>=.95?"Only people read it":"Read a lot, maintained by nobody"}function $q({th:e,setTh:t}){const n=(r,i)=>{const l=Math.round(Number(r));return Number.isFinite(l)&&l>=1?l:i};return o.jsxs("div",{className:"in-thresholds",role:"group","aria-label":"Thresholds",children:[o.jsxs("label",{children:["Stale after"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Stale after days",value:e.stale,onChange:r=>t({...e,stale:n(r.target.value,e.stale)})})," ","days"]}),o.jsx("span",{"aria-hidden":!0,children:"·"}),o.jsxs("label",{children:["hot ≥"," ",o.jsx("input",{type:"number",min:1,"aria-label":"Hot at reads",value:e.hot,onChange:r=>t({...e,hot:n(r.target.value,e.hot)})})," ","reads"]})]})}function Fq({p:e,max:t,lens:n}){const r=n==="all"?["human","agent","share"]:[n];return o.jsx("span",{className:"in-fx-bar",style:{width:Math.max(4,e.reads/t*100)+"%"},children:r.map(i=>e[i]?o.jsx("span",{className:"in-hp-"+i,style:{flexGrow:e[i]}},i):null)})}const Iq=8;function Pq(e){const t=e.pts.filter(i=>i.danger||i.empty).sort((i,l)=>Number(l.empty)-Number(i.empty)||l.reads*Math.max(1,l.days)-i.reads*Math.max(1,i.days)),n=t.slice(0,Iq),r=Math.max(1,...n.map(i=>i.reads));return o.jsxs("section",{className:"in-sec in-fix","data-sec":"fix",children:[o.jsxs("div",{className:"in-sec-head",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"in-h2",children:"Fix these first"}),o.jsx("p",{className:"in-sub",children:"Files people or agents keep relying on that are emptied or no longer maintained. Ranked by reads × days since last change."})]}),o.jsx($q,{th:e.th,setTh:e.setTh})]}),n.length===0?o.jsx("div",{className:"in-fix-none",children:"Nothing hot and stale, and no empty file is being read."}):o.jsxs("table",{className:"in-fix-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads · 30d"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Why it's here"}),o.jsx("th",{children:o.jsx("span",{className:"sr-only",children:"Action"})})]})}),o.jsx("tbody",{children:n.map(i=>{const l=i.path.lastIndexOf("/");return o.jsxs("tr",{className:"in-fix-row","data-path":i.path,"data-kind":i.empty?"empty":"stale",title:Of(i),children:[o.jsxs("td",{className:"in-fx-file",children:[o.jsx(AN,{p:i}),o.jsxs("span",{className:"in-fx-name",children:[o.jsx("span",{children:i.path.slice(l+1)}),l>0&&o.jsx("small",{children:i.path.slice(0,l+1)})]})]}),o.jsxs("td",{className:"in-fx-reads",children:[o.jsx("span",{className:"in-fx-track",children:o.jsx(Fq,{p:i,max:r,lens:e.lens})}),o.jsx("span",{className:"in-fx-n",children:i.reads})]}),o.jsxs("td",{className:"in-fx-when"+(i.empty?" empty":""),children:[xc(i.days),i.empty?" → 0 B":""]}),o.jsx("td",{className:"in-fx-why",children:Lq(i)}),o.jsx("td",{className:"in-fx-act",children:i.empty?o.jsx("button",{className:"pbtn in-fx-restore",onClick:()=>e.onOpenHistory(i.path),children:"Restore"}):o.jsx("button",{className:"in-fx-review",onClick:()=>e.onOpenFile(i.path),children:"Review"})})]},i.path)})})]}),t.length>n.length&&o.jsxs("p",{className:"in-legend",children:["+ ",t.length-n.length," more below the cut"]})]})}function Uq(e,t,n,r,i){const l=e.reduce((m,y)=>m+y.value,0);if(!l||r<=0||i<=0)return[];const u=e.slice().sort((m,y)=>y.value-m.value).map(m=>({it:m,a:m.value/l*r*i})),f=(m,y)=>{const w=m.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of m){const S=j.a/w;x=Math.max(x,S/w,w/S)}return x},h=[];for(;u.length;){const m=r>=i,y=m?i:r,g=[u.shift()];for(;u.length&&f(g.concat(u[0]),y)<=f(g,y);)g.push(u.shift());const w=g.reduce((j,S)=>j+S.a,0)/y;let x=0;for(const j of g){const S=j.a/w;m?h.push({item:j.it,x:t,y:n+x,w,h:S}):h.push({item:j.it,x:t+x,y:n,w:S,h:w}),x+=S}m?(t+=w,r-=w):(n+=w,i-=w)}return h}function Vq(e){if(e>=60)return[3,14,30];const t=Math.max(4,e),n=Math.max(1,Math.round(t*.1)),r=Math.max(n+1,Math.round(t*.3)),i=Math.max(r+1,Math.round(t*.6));return[n,r,i]}const Hq=(e,t)=>e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4;function qq(e){const t=[...e].sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]:0}function DN(e,t){const n=t?t.split("/").length:0;return e.split("/").slice(0,-1).slice(0,n+2).join("/")}function Bq(e,t){const n=new Map;for(const r of e){const i=DN(r.path,t),l=n.get(i);l?l.push(r):n.set(i,[r])}return[...n.entries()].map(([r,i])=>{const l=i.filter(u=>u.reads>0);return{key:r,label:r?r===t?"(files here)":r.slice(t?t.length+1:0):"(root)",file:!1,value:i.reduce((u,f)=>u+f.reads+1,0),reads:l.reduce((u,f)=>u+f.reads,0),days:qq((l.length?l:i).map(u=>u.days)),files:i,danger:i.some(u=>u.danger),empty:i.some(u=>u.empty)}})}function Gq(e,t){return e.map(n=>({key:n.path,label:t?n.path.slice(t.length+1):n.path,file:!0,value:n.reads+1,reads:n.reads,days:n.days,files:[n],danger:n.danger,empty:n.empty}))}function Kq(e){if(e.file)return Of(e.files[0]);const t=r=>e.files.reduce((i,l)=>i+l[r],0),n=[e.danger?`⚠ ${e.files.filter(r=>r.danger).length} hot + stale`:"",e.empty?`⛔ ${e.files.filter(r=>r.empty).length} emptied`:""].filter(Boolean);return[`${e.key||"(root)"}/`,`${Us(e.reads,"read")}/30d (${t("human")} people · ${t("agent")} agents · ${t("share")} share)`,`${Us(e.files.length,"file")} · read files changed ~${xc(e.days)}`,...n].join(" — ")}const kp=600,DS=420,zN=8;function Zq({pts:e,scope:t,onOpenFile:n,onOpenFolder:r,isFolder:i}){const[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=t&&i(t)?t:"",h=jU(e.map(_=>_.days)),m=!!h&&CU(h.min,h.max),y=Vq(h?h.max:0),g=l===null?e:e.filter(_=>DN(_.path,f)===l),w=l===null?Bq(e,f):Gq(g,l||f),x=Uq(w,0,0,kp,DS),j=new Set(w.filter(_=>_.danger&&!_.empty).sort((_,N)=>N.reads*N.days-_.reads*_.days).slice(0,zN).map(_=>_.key)),S=o.jsxs("nav",{className:"in-tm-crumbs","aria-label":"Treemap level",children:[o.jsx("button",{className:l===null?"cur":"",onClick:()=>u(null),children:f||"All folders"}),l!==null&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":!0,children:"›"}),o.jsx("span",{className:"cur",children:l||"(root)"}),l&&i(l)&&o.jsx("button",{className:"in-tm-open",onClick:()=>r(l),children:"Open folder"})]}),l===null&&o.jsx("span",{className:"in-tm-hint",children:"click a folder to see its files"})]}),E=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:l===null?"Folder":"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Files"}),o.jsx("th",{children:"Last change"}),o.jsx("th",{children:"Flag"})]})}),o.jsx("tbody",{children:[...w].sort((_,N)=>N.reads-_.reads).map(_=>o.jsxs("tr",{children:[o.jsx("td",{children:_.label}),o.jsx("td",{children:_.reads}),o.jsx("td",{children:_.files.length}),o.jsx("td",{children:xc(_.days)}),o.jsx("td",{children:_.empty?"⛔ emptied":_.danger?"⚠ hot + stale":""})]},_.key))})]});return o.jsxs(Af,{id:"treemap",title:"Where reads go",sub:"Area = reads · colour = how recently the read files changed",table:E,children:[S,o.jsx("svg",{viewBox:`0 0 ${kp} ${DS}`,className:"in-chart in-treemap",style:{maxWidth:kp},"data-level":l===null?"folder":"file",onClick:_=>{const N=_.target.closest("[data-path], [data-dir]");if(!N)return;const R=N.getAttribute("data-path");if(R!==null)return n(R);const T=N.getAttribute("data-dir");T!==null&&u(T)},children:x.map(({item:_,x:N,y:R,w:T,h:A})=>{const M=Hq(_.days,y),L="in-tm-cell "+(m?"in-tm-flat":"in-tm-b"+M)+(_.empty?" flag-empty":j.has(_.key)?" flag-stale":""),H=_.empty?"⛔ ":j.has(_.key)?"⚠ ":"",U=Math.floor((T-10)/6.2),Z=H+_.label,X=Z.length>U?Z.slice(0,Math.max(1,U-1))+"…":Z,Q=_.file?{"data-path":_.key}:{"data-dir":_.key};return o.jsxs("g",{children:[o.jsx("rect",{x:N+1,y:R+1,width:Math.max(.4,T-2),height:Math.max(.4,A-2),rx:3,className:L,"data-bin":m?0:M,...Q,children:o.jsx("title",{children:Kq(_)})}),T>46&&A>22&&U>=4&&o.jsxs("text",{x:N+7,y:R+16,className:"in-tm-label"+(!m&&M>=3?" on-dark":""),...Q,children:[X,A>36&&o.jsxs("tspan",{x:N+7,dy:13,className:"in-tm-sub",children:[_.reads,_.file?"":` · ${Us(_.files.length,"file")}`]})]})]},_.key)})}),o.jsx(Yq,{range:h,flat:m,edges:y})]})}function Yq({range:e,flat:t,edges:n}){if(!e)return null;const r=_U(e.min,e.max),i=[`≤ ${n[0]}d`,`${n[0]+1}–${n[1]}d`,`${n[1]+1}–${n[2]}d`,`> ${n[2]}d`];return o.jsxs("p",{className:"in-legend in-tm-legend",children:["Last change",o.jsx("span",{className:"in-sw-age"+(t?" in-sw-flat":""),children:i.map((l,u)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-tm-b"+(u+1),"aria-hidden":!0})," ",l]},l))}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-empty","aria-hidden":!0,children:"⛔"})," emptied"]}),o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-flag in-flag-stale","aria-hidden":!0,children:"⚠"})," hot + stale (top ",zN,")"]}),o.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old — bins fit this range`})]})}const Qq={agent:"What agents load",human:"What people open",share:"What share links serve"},Xq=8;function Wq({pts:e,kinds:t,th:n,onOpenFile:r,onOpenHistory:i}){const l=t.map(u=>({k:u,total:e.reduce((f,h)=>f+h[u],0),top:e.filter(f=>f[u]>0).sort((f,h)=>h[u]-f[u]||h.days-f.days).slice(0,Xq)})).filter(u=>u.top.length>0||t.length>1&&u.k!=="share");return l.some(u=>u.top.length)?o.jsx(o.Fragment,{children:l.map(({k:u,total:f,top:h})=>o.jsx(Jq,{k:u,total:f,top:h,th:n,onOpenFile:r,onOpenHistory:i},u))}):o.jsx("div",{className:"dl-empty",children:"No reads in the window yet."})}function Jq(e){const{k:t,top:n}=e,r=n.length?n[0][t]:1,i=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsxs("th",{children:[zg[t]," reads"]}),o.jsx("th",{children:"Last change"})]})}),o.jsx("tbody",{children:n.map(l=>o.jsxs("tr",{children:[o.jsx("td",{children:l.path}),o.jsx("td",{children:l[t]}),o.jsx("td",{children:l.orphan?"deleted":xc(l.days)})]},l.path))})]});return o.jsx(Af,{id:"hot-"+t,title:Qq[t],aside:o.jsx("span",{className:"in-hp-total",children:Us(e.total,"read")}),table:i,children:o.jsxs("div",{className:"in-hotpath in-hp-"+t+"-list","data-kind":t,children:[o.jsx("span",{className:"in-sw "+t,"aria-hidden":!0}),n.length===0&&o.jsxs("div",{className:"in-hp-none",children:["No ",zg[t]," reads in the window."]}),n.map(l=>{const u=()=>l.orphan?e.onOpenHistory(l.path):e.onOpenFile(l.path),f={danger:l[t]>=e.th.hot&&l.danger,empty:l.empty};return o.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:Of(l),onClick:u,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),u())},children:[o.jsxs("span",{className:"in-hp-line",children:[o.jsxs("span",{className:"in-hp-name"+(l.danger||l.empty?" danger":""),children:[o.jsx(AN,{p:{danger:l.danger||f.danger,empty:l.empty}}),l.path]}),l.orphan&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),o.jsx("span",{className:"in-hp-count",children:l[t]})]}),o.jsx("span",{className:"in-hp-bar",children:o.jsx("span",{className:"in-hp-"+t,style:{width:(l[t]/r*100).toFixed(1)+"%"}})})]},l.path)})]})})}function eB({pts:e,th:t,onOpenFile:n}){const l={l:44,r:16,t:20,b:34},u=e.filter(N=>N.reads>0),f=Math.max(t.stale*1.5,...u.map(N=>N.days),1),h=Math.max(t.hot*3,...u.map(N=>N.reads)),m=5,y=N=>l.l+m+N/f*(960-l.l-l.r-2*m),g=N=>340-l.b-m-Math.log10(N+1)/Math.log10(h+1)*(340-l.t-l.b-2*m),w=u.filter(N=>N.danger||N.empty),x=u.filter(N=>N.danger).length,j=kU(w.map(N=>({path:N.path,reads:N.reads,cx:y(N.days),cy:g(N.reads),r:4.5})),{right:960-l.r,top:l.t+8,bottom:340-l.b-4}),S=[0,.25,.5,.75,1].map(N=>Math.round(N*f)),E=[1,3,10,30,100,300,1e3,3e3].filter(N=>N<=h),_=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"File"}),o.jsx("th",{children:"Reads"}),o.jsx("th",{children:"Days since change"}),o.jsx("th",{children:"Verdict"})]})}),o.jsx("tbody",{children:[...u].sort((N,R)=>Number(R.empty)-Number(N.empty)||Number(R.danger)-Number(N.danger)||R.reads-N.reads).map(N=>o.jsxs("tr",{children:[o.jsx("td",{children:N.path}),o.jsx("td",{children:N.reads}),o.jsx("td",{children:Math.round(N.days)}),o.jsx("td",{children:N.empty?"⛔ emptied":N.danger?"⚠ hot + stale":""})]},N.path))})]});return o.jsxs(Af,{id:"scatter",title:"Reads × days since last change",sub:`One dot per file read in the window (${u.length}). Grey = fine; only the files that need you are coloured and named.`,aside:o.jsx("span",{className:"in-cap",children:"Hover a dot for path, reads by type, last editor"}),table:_,children:[o.jsxs("svg",{viewBox:"0 0 960 340",className:"in-chart in-scatter",style:{maxWidth:960},children:[o.jsx("rect",{x:y(t.stale),y:l.t,width:Math.max(0,960-l.r-y(t.stale)),height:Math.max(0,g(t.hot)-l.t),className:"in-danger-zone"}),S.map(N=>o.jsxs("text",{x:y(N),y:340-l.b+14,className:"in-tick",textAnchor:"middle",children:[N,"d"]},"x"+N)),E.map(N=>o.jsx("text",{x:l.l-6,y:g(N)+3,className:"in-tick",textAnchor:"end",children:N},"y"+N)),o.jsx("line",{x1:y(t.stale),y1:l.t,x2:y(t.stale),y2:340-l.b,className:"in-threshold","data-th":"stale"}),o.jsx("line",{x1:l.l,y1:g(t.hot),x2:960-l.r,y2:g(t.hot),className:"in-threshold","data-th":"hot"}),o.jsx("line",{x1:l.l,y1:340-l.b,x2:960-l.r,y2:340-l.b,className:"in-axis"}),o.jsx("line",{x1:l.l,y1:l.t,x2:l.l,y2:340-l.b,className:"in-axis"}),o.jsx("text",{x:960-l.r,y:334,className:"in-label",textAnchor:"end",children:"days since last change →"}),o.jsx("text",{x:12,y:(l.t+340-l.b)/2,className:"in-label",transform:`rotate(-90 12 ${(l.t+340-l.b)/2})`,children:"reads / 30d (log) →"}),o.jsx("text",{x:y(t.stale)+6,y:l.t+14,className:"in-quad in-quad-danger",children:"hot + stale"}),o.jsxs("text",{x:y(t.stale)+92,y:l.t+14,className:"in-quad-count",children:["· ",x]}),o.jsx("text",{x:l.l+6,y:l.t+14,className:"in-quad",children:"hot + fresh"}),o.jsx("text",{x:960-l.r-6,y:340-l.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),o.jsx("text",{x:l.l+6,y:340-l.b-8,className:"in-quad",children:"cold + fresh"}),u.map(N=>o.jsx("circle",{cx:Number(y(N.days).toFixed(1)),cy:Number(g(N.reads).toFixed(1)),r:N.danger||N.empty?4.5:3.5,className:"in-pt"+(N.empty?" empty":N.danger?" danger":""),onClick:()=>n(N.path),children:o.jsx("title",{children:Of(N)})},N.path)),j.map(N=>o.jsx("text",{x:Number(N.x.toFixed(1)),y:Number(N.y.toFixed(1)),textAnchor:N.anchor,className:"in-pt-label",children:N.name},N.path))]}),o.jsxs("p",{className:"in-legend",children:[o.jsx("span",{className:"in-sw in-sw-other","aria-hidden":!0})," other files"," ",o.jsx("span",{className:"in-sw in-sw-stale","aria-hidden":!0})," ⚠ hot + stale"," ",o.jsx("span",{className:"in-sw in-sw-empty","aria-hidden":!0})," ⛔ emptied"]})]})}const tB=e=>e<=0?0:e<=5?1:e<=20?2:e<=50?3:4;function nB(e,t){const n=[],r=e.reduce((l,u)=>l+u.total,0);if(!r)return n;if(e.length>=3){const l=e[0].total+e[1].total;n.push({icon:"users",head:`2 devices do ${Math.round(l/r*100)}% of agent reading`,body:`${e[0].name} and ${e[1].name}: their agents' context is the team's de-facto canon.`})}const i=e.filter(l=>l.total=2){const l=t[t.length-1];n.push({icon:"archive",head:`${l.name||"(root)"}${l.name?"/":""} is the least-read folder by agents`,body:`${Us(l.total,"read")} in 30 days — a candidate to exclude from agent search, or to point agents at.`})}return n.slice(0,3)}function sB({name:e}){const t=e==="users"?wv:e==="off"?S3:g3;return o.jsx(t,{className:"in-tk-ico","aria-hidden":!0,size:15})}function rB({devices:e,lens:t}){const n=new Map;for(const y of e)for(const[g,w]of Object.entries(y.folders||{}))n.set(g,(n.get(g)||0)+w);const r=[...n.entries()].sort((y,g)=>g[1]-y[1]).slice(0,10).map(([y,g])=>({name:y,total:g})),i=(y,g)=>y.folders&&Object.prototype.hasOwnProperty.call(y.folders,g)?y.folders[g]:0,l=e.map(y=>({d:y,name:y.name||y.id||"",total:Object.values(y.folders||{}).reduce((g,w)=>g+w,0)})).sort((y,g)=>g.total-y.total).slice(0,12),u=nB(l,r),f=t==="human"||t==="share",h=()=>o.jsxs("table",{className:"in-data-table",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Device"}),r.map(y=>o.jsx("th",{children:y.name||"(root)"},y.name)),o.jsx("th",{children:"Total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("td",{children:y.name}),r.map(g=>o.jsx("td",{children:i(y.d,g.name)},g.name)),o.jsx("td",{children:y.total})]},y.d.id||y.name))})]}),m=o.jsxs("p",{className:"in-legend in-cov-off",children:["This matrix counts agent reads only — the ",TN[t]," lens has nothing to show here."]});return o.jsxs(Af,{id:"coverage",title:"Which agents read which folders",sub:"Agent reads per device × top-level folder · folders sorted by total agent reads",table:f?()=>m:h,children:[f&&m,!f&&o.jsxs("div",{className:"in-cov",children:[o.jsxs("div",{className:"in-matrix-wrap",children:[o.jsxs("table",{className:"in-matrix",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{}),r.map(y=>o.jsx("th",{scope:"col",children:y.name||"(root)"},y.name)),o.jsx("th",{scope:"col",className:"in-cv-total",children:"total"})]})}),o.jsx("tbody",{children:l.map(y=>o.jsxs("tr",{children:[o.jsx("th",{scope:"row",title:y.name,children:y.name}),r.map(g=>{const w=i(y.d,g.name);return o.jsx("td",{className:"in-cv in-cv-"+tB(w),title:`${y.name} × ${g.name||"(root)"}: ${Us(w,"agent read")}/30d`,children:w||"·"},g.name)}),o.jsx("td",{className:"in-cv-total",children:y.total})]},y.d.id||y.name))})]}),o.jsxs("p",{className:"in-legend in-cv-legend",children:["Agent reads"," ",["0","1–5","6–20","21–50","50+"].map((y,g)=>o.jsxs("span",{className:"in-tm-key",children:[o.jsx("span",{className:"in-sw in-cv-"+g,"aria-hidden":!0})," ",y]},y))]})]}),u.length>0&&o.jsxs("aside",{className:"in-takeaways",children:[o.jsx("h3",{children:"What this tells you"}),u.map(y=>o.jsxs("div",{className:"in-takeaway",children:[o.jsx(sB,{name:y.icon}),o.jsxs("div",{children:[o.jsx("b",{children:y.head}),o.jsx("p",{children:y.body})]})]},y.head))]})]})]})}const aB=[["","Everyone"],["agent","Agents"],["human","People"]],iB=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"local time"}catch{return"local time"}};function oB(e){const{filters:t,authors:n,devices:r,onChange:i}=e,l=N=>{const R={...t,...N};for(const T of Object.keys(R))R[T]||delete R[T];i(R)},[u,f]=b.useState(t?.q??""),h=b.useRef(!1);b.useEffect(()=>{h.current||f(t?.q??"")},[t?.q]),b.useEffect(()=>{if(!h.current)return;const N=setTimeout(()=>{h.current=!1,u!==(t?.q??"")&&l({q:u})},250);return()=>clearTimeout(N)},[u]);const[m,y]=b.useState(!1),g=m||!!t?.since||!!t?.until,w=t?.range??(g?"custom":""),x=t?.user&&!n.includes(t.user)?[t.user,...n]:n,j=t?.device&&!r.some(N=>N.id===t.device)?[{id:t.device,name:t.device},...r]:r,S=t?.device?"d:"+t.device:t?.user?"u:"+t.user:"",E=Mv(t),_=iB();return o.jsxs("div",{className:"hfilters",children:[o.jsxs("label",{className:"hf-search",children:[o.jsx(ge,{name:"search"}),o.jsx(md,{type:"search",value:u,placeholder:"Filter by path or file name…","aria-label":"Filter by path",onChange:N=>{h.current=!0,f(N.target.value)}})]}),o.jsx("div",{className:"hf-seg",role:"group","aria-label":"Who made the change",children:aB.map(([N,R])=>o.jsx("button",{type:"button","aria-pressed":(t?.actor??"")===N,onClick:()=>l({actor:N}),children:R},R))}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"laptop"}),o.jsxs("select",{className:"hf-device",value:S,"aria-label":"Filter by device or person",onChange:N=>{const R=N.target.value;l({device:R.startsWith("d:")?R.slice(2):void 0,user:R.startsWith("u:")?R.slice(2):void 0})},children:[o.jsx("option",{value:"",children:"All devices"}),j.length>0&&o.jsx("optgroup",{label:"Devices",children:j.map(N=>o.jsx("option",{value:"d:"+N.id,children:N.name},N.id))}),x.length>0&&o.jsx("optgroup",{label:"People",children:x.map(N=>o.jsx("option",{value:"u:"+N,children:N},N))})]})]}),o.jsxs("span",{className:"hf-pick",children:[o.jsx(ge,{name:"clock"}),o.jsxs("select",{className:"hf-range",value:w,"aria-label":`Date range (${_})`,onChange:N=>{const R=N.target.value;if(R==="custom"){y(!0),t?.range&&l({range:void 0});return}y(!1),l({range:R,since:void 0,until:void 0})},children:[o.jsx("option",{value:"",children:"All time"}),Object.entries(Pd).map(([N,R])=>o.jsx("option",{value:N,children:R},N)),o.jsx("option",{value:"custom",children:"Custom…"})]})]}),g&&o.jsxs("span",{className:"hf-dates",children:[o.jsx(md,{type:"date",className:"hf-date",value:t?.since??"","aria-label":`From date (${_})`,onChange:N=>l({since:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-dash",children:"–"}),o.jsx(md,{type:"date",className:"hf-date",value:t?.until??"","aria-label":`To date (${_})`,onChange:N=>l({until:N.target.value,range:void 0})}),o.jsx("span",{className:"hf-lbl",title:"Days are your own calendar days",children:_})]}),E&&o.jsx("button",{type:"button",className:"hf-clear",onClick:()=>{y(!1),i({})},children:"Clear"})]})}function lB(e,t){if(!e)return[];const n=(...i)=>{const l={...e};for(const u of i)delete l[u];return l},r=[];return e.q&&r.push(["path: "+e.q,n("q")]),e.actor&&r.push([e.actor==="agent"?"Agents":"People",n("actor")]),e.device&&r.push([t.find(i=>i.id===e.device)?.name||e.device,n("device")]),e.user&&r.push([e.user,n("user")]),e.range&&r.push([Pd[e.range]||e.range,n("range")]),(e.since||e.until)&&r.push([(e.since||"…")+" – "+(e.until||"…"),n("since","until")]),r}function cB(e){const t=new Set;for(const n of e)n.user&&t.add(n.user);return[...t].sort()}function uB(e){const{apiBase:t,target:n,isFolder:r,onMeta:i,onRendered:l,restore:u,remove:f,undoRun:h,filters:m}=e,y=b.useMemo(()=>new Set(e.flatFiles.map(ve=>ve.path)),[e.flatFiles]),g=!n||r(n),w=n?g?"prefix="+encodeURIComponent(n+"/"):"path="+encodeURIComponent(n):"prefix=",x=b.useMemo(()=>w+nN(m),[w,m]),j=mn(),{data:S,error:E,isPending:_,fetchNextPage:N,hasNextPage:R,isFetchingNextPage:T}=IM({queryKey:["history",t,x],queryFn:({pageParam:ve})=>We(t+"history?"+x+"&n=100"+(ve?"&cursor="+encodeURIComponent(ve):"")),initialPageParam:"",getNextPageParam:ve=>ve.next_cursor,staleTime:15e3,retry:1}),[A,M]=b.useState(!1),[L,H]=b.useState(0);b.useEffect(()=>{if(M(!1),!_)return;const ve=setTimeout(()=>M(!0),fB);return()=>clearTimeout(ve)},[_,x,L]);const U=()=>{H(ve=>ve+1),j.resetQueries({queryKey:["history",t,x]})},Z=b.useRef(new Set),X=b.useRef(new Map);b.useEffect(()=>{E&&i("History unavailable: "+E.message)},[E,i]),b.useEffect(()=>{S&&l?.()},[S,l]);const Q=b.useMemo(()=>S?S.pages.flatMap(ve=>ve.entries||[]):[],[S]);for(const ve of cB(Q))Z.current.add(ve);for(const ve of Q)ve.device?.id&&!X.current.has(ve.device.id)&&X.current.set(ve.device.id,ve.device.name||ve.device.id);const ae=[...X.current].map(([ve,Me])=>({id:ve,name:Me})).sort((ve,Me)=>ve.name.localeCompare(Me.name)),le=e.onFilters&&o.jsx(oB,{filters:m,authors:[...Z.current].sort(),devices:ae,onChange:e.onFilters}),be=g&&o.jsx(pB,{apiBase:t,scope:w,filters:m}),$=b.useMemo(()=>MN(Q),[Q]),q=b.useMemo(()=>$.flatMap(ve=>ve.run?ve.run.idx:[ve.i]),[$]),[V,ee]=b.useState(null);if(b.useEffect(()=>ee(null),[x]),b.useEffect(()=>{const ve=Me=>{if(Me.metaKey||Me.ctrlKey||Me.altKey||Me.defaultPrevented)return;const Ye=Me.target;if(Ye&&(Ye.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Ye.tagName)))return;if(Me.key==="Escape"&&V!==null){ee(null);return}if(Me.key!=="j"&&Me.key!=="k"||!q.length)return;Me.preventDefault();const ht=V===null?-1:q.indexOf(V),tt=Me.key==="j"?Math.min(q.length-1,ht+1):Math.max(0,ht===-1?0:ht-1);ee(q[tt])};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[q,V]),b.useEffect(()=>{V!==null&&document.querySelector(`.history [data-hidx="${V}"]`)?.scrollIntoView({block:"nearest"})},[V]),!S)return o.jsx("div",{className:"activity",children:o.jsxs("div",{className:"history",children:[le,be,E||A?o.jsx(mB,{onRetry:U,timedOut:!E}):_&&o.jsx(hB,{})]})});const K=ve=>{if(Q[ve].prev||Q[ve].kind==="delete")return Q[ve].prev||void 0;for(let Me=ve+1;Me{const Me=Q[ve].kind==="delete"?K(ve):Q[ve].blob;return Me&&Me===O.get(Q[ve].path)?void 0:Me},B=ve=>O.get(Q[ve].path)==="",P=ve=>{const Me=K(ve);return Me&&Me!==O.get(Q[ve].path)?Me:void 0},I=lB(m,ae);let re="";const he=new Map;for(const ve of Q){const Me=ui(new Date(ve.time));he.set(Me,(he.get(Me)??0)+1)}const we=V!==null?Q[V]:void 0,Se=V===null?-1:q.indexOf(V);return o.jsxs("div",{className:"activity"+(we?" has-panel":"")+(Q.length?" two-zone":""),children:[o.jsxs("div",{className:"history",children:[le,be,Q.length===0&&(Mv(m)?o.jsxs("div",{className:"empty hempty",children:[o.jsx("span",{className:"hempty-icon",children:o.jsx(ge,{name:"search"})}),o.jsx("b",{children:"No changes match these filters."}),o.jsx("span",{className:"hchips",children:I.map(([ve,Me])=>o.jsxs("button",{type:"button",className:"hf-chip",title:"Remove "+ve,onClick:()=>e.onFilters?.(Me),children:[ve,o.jsx(ge,{name:"x"})]},ve))}),o.jsx("span",{className:"hempty-hint",children:"Try widening the date range, or check whether this folder is excluded in .bdriveignore."}),o.jsxs("span",{className:"hempty-actions",children:[o.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"}),m?.range!=="30d"&&(m?.range||m?.since||m?.until)&&o.jsx("button",{type:"button",className:"pbtn hf-widen",onClick:()=>e.onFilters?.({...m,range:"30d",since:void 0,until:void 0}),children:"Show last 30 days"})]})]}):o.jsx("div",{className:"empty",children:"No history yet."})),$.map((ve,Me)=>{const Ye=ui(new Date(Q[ve.i].time)),ht=Ye!==re?o.jsxs("div",{className:"hday",children:[o.jsx("b",{children:fy(Ye)}),o.jsxs("span",{children:["· ",he.get(Ye)," change",he.get(Ye)===1?"":"s",R&&Ye===ui(new Date(Q[Q.length-1].time))?"+":""]})]},"d"+Ye):null;re=Ye;const tt=ve.run?o.jsx(vB,{run:ve.run,known:y,onOpen:e.onOpen,apiBase:t,prevBlob:K,restoreSha:D,recreates:B,restore:u,remove:f,undoRun:h,sel:V,onSelect:ee},"g"+Me):o.jsx(vy,{idx:ve.i,entry:Q[ve.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:K(ve.i)},restore:u,restoreSha:D(ve.i),recreates:B(ve.i),selected:V===ve.i,onSelect:()=>ee(ve.i)},"r"+ve.i);return ht?[ht,tt]:tt}),R&&o.jsx("button",{type:"button",className:"btn hmore",onClick:()=>N(),disabled:T,children:T?"Loading…":"Load more"})]}),we&&V!==null?o.jsx(gB,{entry:we,apiBase:t,prev:K(V),restorePrev:P(V),recreates:B(V),restore:u,linkFor:e.linkFor,flatFiles:e.flatFiles,projectId:e.projectId,onOpen:e.onOpen,onClose:()=>ee(null),onPrev:Se>0?()=>ee(q[Se-1]):void 0,onNext:Seee(q[Se+1]):void 0},V):Q.length>0&&o.jsx(dB,{})]})}function dB(){return o.jsxs("aside",{className:"apanel-empty","aria-label":"Change details",children:[o.jsx(ge,{name:"hist"}),o.jsx("b",{children:"Select a change"}),o.jsx("span",{children:"Its diff, rendered view and full file appear here."}),o.jsxs("span",{className:"ap-keys",children:[o.jsx("kbd",{children:"J"})," ",o.jsx("kbd",{children:"K"})," move · ",o.jsx("kbd",{children:"Esc"})," close"]})]})}const fB=1e4;function hB(){return o.jsxs("div",{className:"hskel","aria-busy":"true","aria-label":"Loading activity",children:[o.jsx("div",{className:"hday",children:o.jsx("b",{children:"Today"})}),[62,74,48,68,56].map((e,t)=>o.jsxs("div",{className:"hskel-row",children:[o.jsx("span",{className:"hskel-dot"}),o.jsxs("span",{className:"hskel-lines",children:[o.jsx("span",{style:{width:e+"%"}}),o.jsx("span",{style:{width:e/2+"%"}})]}),o.jsx("span",{className:"hskel-time"})]},t)),o.jsx("div",{className:"hskel-note",children:"Loading changes…"})]})}function mB({onRetry:e,timedOut:t}){return o.jsxs("div",{className:"empty hempty herror",role:"alert",children:[o.jsx("span",{className:"hempty-icon herror-icon",children:o.jsx(ge,{name:"alert"})}),o.jsx("b",{children:"Couldn't load activity"}),o.jsxs("span",{className:"hempty-hint",children:[t?"The history service didn't respond within 10 seconds.":"The history service returned an error."," ","Your files are still syncing — only this view is affected."]}),o.jsx("span",{className:"hempty-actions",children:o.jsxs("button",{type:"button",className:"pbtn herror-retry",onClick:e,children:[o.jsx(ge,{name:"hist"}),"Try again"]})})]})}function pB({apiBase:e,scope:t,filters:n}){const r=OH(n),i=nN(n);let l="";try{l=Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{}const u=t+i+(TH(n)?"&all=1":"")+"&days="+r+"&offset="+-new Date().getTimezoneOffset()+(l?"&tz="+encodeURIComponent(l):""),{data:f}=rt({queryKey:["history-summary",e,u],queryFn:()=>We(e+"history/summary?"+u),staleTime:15e3,retry:!1});if(!f)return o.jsx("div",{className:"hsum hsum-wait"});const h=ui(new Date),m=Math.max(1,...f.days.map(E=>E.agent+E.human)),y=E=>{const[_,N,R]=E.split("-").map(Number);return new Date(_,N-1,R)},g=E=>E.toLocaleDateString([],{month:"short",day:"numeric"}),w=f.days.length,x=w?w===1?g(y(f.days[0].date)):g(y(f.days[0].date))+" – "+g(y(f.days[w-1].date)):"",j=f.total?Math.round(100*f.agent/f.total):0,S=AH(n);return o.jsxs("div",{className:"hsum",children:[o.jsxs("div",{className:"hsum-head",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"hsum-total",children:[f.total.toLocaleString()," change",f.total===1?"":"s"]}),o.jsxs("div",{className:"hsum-sub",children:[x&&x+" · ",j,"% by agents · ",f.devices.toLocaleString()," device",f.devices===1?"":"s",o.jsxs("span",{className:"hsum-range",children:[" · ",S]})]})]}),o.jsxs("div",{className:"hsum-legend",children:[o.jsx("span",{className:"agent",children:"Agents"}),o.jsx("span",{className:"human",children:"People"})]})]}),o.jsx("div",{className:"hsum-bars"+(f.days.length>14?" dense":""),children:f.days.map((E,_)=>{const N=y(E.date),R=E.date===h;return o.jsxs("div",{className:"hsum-col"+(R?" today":""),title:`${g(N)}: ${E.agent.toLocaleString()} by agents, ${E.human.toLocaleString()} by people`,children:[o.jsxs("div",{className:"hsum-stack",children:[o.jsx("span",{className:"agent",style:{height:100*E.agent/m+"%"}}),o.jsx("span",{className:"human",style:{height:100*E.human/m+"%"}})]}),o.jsx("span",{className:"hsum-day",children:f.days.length===1?fy(E.date):f.days.length>14?_%5===0||R?N.getDate():"":N.toLocaleDateString([],{weekday:"short"})})]},E.date)})})]})}function gB(e){const{entry:t,apiBase:n,restore:r}=e,i=t.kind==="delete",l=t.path.split("/").pop()||t.path,u=yi(t)?Rf(t.note):xv(t),f=t.device.name||t.device.id,h=new Date(t.time),m=!!r?.busy&&!!e.restorePrev&&r.busy===t.path+e.restorePrev;return o.jsxs("aside",{className:"apanel","aria-label":"Change to "+t.path,children:[o.jsxs("div",{className:"ap-head",children:[o.jsx(ge,{name:"doc"}),o.jsx("span",{className:"ap-name",children:l}),o.jsx("button",{type:"button",className:"ap-nav",title:"Previous change (K)",disabled:!e.onPrev,onClick:e.onPrev,children:o.jsx(ge,{name:"chev"})}),o.jsx("button",{type:"button",className:"ap-nav down",title:"Next change (J)",disabled:!e.onNext,onClick:e.onNext,children:o.jsx(ge,{name:"chevd"})}),o.jsx("button",{type:"button",className:"ap-close",title:"Close (Esc)",onClick:e.onClose,children:o.jsx(ge,{name:"x"})})]}),o.jsx("div",{className:"ap-path",children:t.path}),o.jsxs("div",{className:"ap-who",children:[o.jsx(ge,{name:yi(t)?"terminal":"users"}),u,f?" on "+f:""," · ",fy(ui(h))," ",h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]}),o.jsxs("div",{className:"ap-actions",children:[!i&&t.blob&&o.jsxs("button",{type:"button",className:"pbtn ap-open",onClick:()=>e.onOpen(t.path,t.blob),children:[o.jsx(ge,{name:"expand"}),"Open file"]}),r&&e.restorePrev&&o.jsxs("button",{type:"button",className:"btn ap-restore",disabled:m,onClick:()=>r.onRestore(t.path,e.restorePrev,e.recreates),children:[o.jsx(ge,{name:"hist"}),m?"Restoring…":i?"Restore file":"Restore previous"]}),e.linkFor&&(i?!!e.prev:!!t.blob)&&o.jsxs("button",{type:"button",className:"btn ap-copy",onClick:async()=>{const y=location.origin+e.linkFor(t.path,i?e.prev:t.blob);Ne(await Mn(y)?"Link copied":y,!1)},children:[o.jsx(ge,{name:"link"}),"Copy link"]})]}),o.jsx(h7,{apiBase:n,path:t.path,kind:t.kind,prev:e.prev,cur:i?void 0:t.blob,flatFiles:e.flatFiles,projectId:e.projectId,onOpenFile:y=>e.onOpen(y)}),o.jsx("div",{className:"ap-foot",children:"J / K to move between changes · esc close"})]})}function vB({run:e,known:t,onOpen:n,apiBase:r,prevBlob:i,restoreSha:l,recreates:u,restore:f,remove:h,undoRun:m,sel:y,onSelect:g}){const[w,x]=b.useState(!0),j=e.entries[0],S=ff(j),E=[j.device.name||j.device.id,j.device.os].filter(Boolean).join(" · "),_=j.session,N=j.device?.id,{data:R}=rt({queryKey:["session-reads",r,_,N],queryFn:()=>We(r+"heat?session="+encodeURIComponent(_)+"&device="+encodeURIComponent(N)),enabled:!!_&&!!N,staleTime:3e4}),T=new Set(R?.paths??[]),A=new Set(e.entries.map(Q=>Q.path)),M=[...T].filter(Q=>!A.has(Q)).sort(),L=e.entries.map(Q=>new Date(Q.time).getTime()),H=yB(Math.min(...L),Math.max(...L)),U=DH(Math.max(...L)-Math.min(...L)),Z=xy(e),X=!!m?.busy&&m.busy===(e.session||e.note);return o.jsxs("div",{className:"hrun"+(w?" open":""),children:[o.jsxs("div",{className:"hrun-head",children:[o.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":w,title:w?"Collapse this run":"Expand this run",onClick:()=>x(!w),children:o.jsx(ge,{name:w?"chevd":"chev"})}),o.jsx("span",{className:"havatar agent","aria-hidden":"true",children:o.jsx(ge,{name:"terminal"})}),o.jsxs("span",{className:"hrun-title",children:[o.jsxs("span",{className:"hrun-what",children:[o.jsx("b",{children:e.session?Rf(e.note):S.split(" <")[0]})," edited ",Z," file",Z===1?"":"s",U?" · "+U:""]}),o.jsxs("span",{className:"hrun-sub",children:[o.jsx("span",{className:"hrun-note",children:o.jsx(fN,{text:e.note})}),o.jsxs("span",{className:"hrun-meta",children:[T.size>0?`read ${T.size} · changed ${Z}`:`${Z} file${Z===1?"":"s"}`," ·"," ",S,E?" · "+E:""]})]})]}),o.jsx("span",{className:"hrun-time",children:H}),m&&o.jsxs("button",{type:"button",className:"hrun-undo",disabled:X,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[o.jsx(ge,{name:"hist"}),X?"undoing…":"undo this run"]})]}),w&&o.jsxs("div",{className:"hrun-body",children:[e.entries.map((Q,ae)=>o.jsx(vy,{entry:Q,apiBase:r,onOpen:n,diff:{apiBase:r,prev:i(e.idx[ae])},restore:f,remove:h,restoreSha:l(e.idx[ae]),recreates:u(e.idx[ae]),inRun:!0,read:T.has(Q.path),idx:e.idx[ae],stat:!0,selected:y===e.idx[ae],onSelect:()=>g(e.idx[ae])},ae)),M.length>0&&o.jsxs("div",{className:"hrun-reads",children:[o.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),M.map(Q=>o.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>n(Q),children:[o.jsx("span",{className:"hkind",children:"read"}),o.jsx("span",{className:"hpath",children:Q}),!t.has(Q)&&o.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"})]},Q))]}),_&&o.jsx("div",{className:"hrun-foot",children:"Reads shown are what this device reported for this session — a narrower set than the project's read totals."})]})]})}function yB(e,t){const n=new Date(e),r=new Date(t),i=l=>l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return n.toDateString()!==r.toDateString()?n.toLocaleString()+" – "+r.toLocaleString():e===t?i(r):i(n)+" – "+i(r)}function xB(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}const bB=768,Lg=600;function zS(e,t){return Math.round(Math.min(Math.max(e,Lg),Math.max(t,Lg)))}const wB=300,LS=32;function $S(e){const t=e.parentElement,n=getComputedStyle(t),r=t.clientWidth-parseFloat(n.paddingLeft)-parseFloat(n.paddingRight),i=e.querySelector(":scope > aside.fv-rail"),l=i&&window.matchMedia(Kp).matches&&getComputedStyle(i).display!=="none"?wB:0;return r-l}function SB(e){const t=e.width??bB,n=i=>l=>{if(l.button!==0)return;l.preventDefault();const u=l.currentTarget,f=u.parentElement,h=$S(f),m=Math.min(t,h),y=l.clientX;let g=null;u.setPointerCapture(l.pointerId),u.classList.add("dragging"),document.body.classList.add("rw-dragging");const w=j=>{const S=i==="right"?j.clientX-y:y-j.clientX;g=zS(m+2*S,h),f.style.setProperty("--page-read",g+"px")},x=()=>{u.removeEventListener("pointermove",w),u.removeEventListener("pointerup",x),u.removeEventListener("pointercancel",x),u.classList.remove("dragging"),document.body.classList.remove("rw-dragging"),g!==null&&e.onChange(g)};u.addEventListener("pointermove",w),u.addEventListener("pointerup",x),u.addEventListener("pointercancel",x)},r=i=>l=>{const u=i==="right"?"ArrowRight":"ArrowLeft",f=i==="right"?"ArrowLeft":"ArrowRight";if(l.key!==u&&l.key!==f)return;l.preventDefault();const h=$S(l.currentTarget.parentElement);e.onChange(zS(Math.min(t,h)+(l.key===u?LS:-LS),h))};return o.jsx(o.Fragment,{children:["left","right"].map(i=>o.jsx("div",{className:`rw-handle rw-${i}`,role:"separator","aria-orientation":"vertical","aria-label":"Resize the reading width","aria-valuenow":t,"aria-valuemin":Lg,tabIndex:0,title:"Drag to resize · double-click to reset",onPointerDown:n(i),onKeyDown:r(i),onDoubleClick:()=>e.onChange(null)},i))})}const jB=3,FS=2;function IS(e,t){return{key:e,want:t,attempts:0}}function CB(e,t){return e.key!==t||e.attempts>=jB?null:(e.attempts++,e.want)}function _B(e,t,n,r){e.key===t&&(Math.abs(n-e.want)<=FS||e.attempts===0||n>=r-FS&&nWe(t+"history?"+i+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===r),f=u?ff(u):"",h=u?.time?new Date(u.time).toLocaleString():"",m=t+"blob?sha="+r+"&name="+encodeURIComponent(n.split("/").pop()||n)+"&download=1";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"clock"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:[h&&"Version from "+h,f&&"by "+f].filter(Boolean).join(" ")||"Earlier version"}),o.jsx("span",{children:"This is not the current file."})]}),o.jsxs("div",{className:"vb-actions",children:[o.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),o.jsx("a",{className:"ai-btn",download:!0,href:m,children:"Download this version"})]})]})}function NB(e){const{conflict:t,originalHref:n}=e,r=t.device||"another device";return o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"alert"})}),o.jsxs("div",{className:"vb-text",children:[o.jsx("b",{children:"Conflict copy — a concurrent edit, preserved"}),o.jsxs("span",{children:[r," edited this file at the same time as someone else on"," ",t.when.toLocaleString(),". Rather than drop either version, beardrive kept that one here."," ",n?o.jsxs(o.Fragment,{children:["The other version lives at ",o.jsx("code",{children:t.original})]}):o.jsx(o.Fragment,{children:"The other version kept the original name."})]})]}),n&&o.jsx("div",{className:"vb-actions",children:o.jsx("button",{className:"ai-btn",onClick:n,children:"Open the other version"})})]})}function LN(e){const{config:t,apiBase:n,route:r,hub:i,project:l}=e,u=o$(Av()),f=mn(),{tree:h,flatFiles:m,dirIndex:y,loaded:g}=E2(n,!i||!!l),w=!i||!!l,{people:x,setPeople:j}=mV(n,r.path??"",w);hV(n,w,j);const S=MU(n,i&&!!l&&!!t.reads?.enabled),{data:E}=hE(i&&l?l?.id:void 0),_=b.useMemo(()=>E?.folders||[],[E]),N=b.useMemo(()=>new Set(_.map(ie=>ie.prefix.replace(/\/$/,""))),[_]),R=i&&!!l&&!r.path&&!r.view,T=r.view==="dashboard",A=Rq(n,T);b.useEffect(()=>{(T||R)&&f.invalidateQueries({queryKey:["heat",n]})},[T,R,n,f]);const M=r.path,L=r.view?void 0:r.version,H=M||(r.view==="dashboard"||r.view==="history")&&r.viewTarget||"",U=!!M&&y.has(M),Z=!!M&&g&&!U&&m.some(ie=>ie.path===M),X=!!M&&g&&!U&&!Z&&!L,Q=U&&!r.view;b.useEffect(()=>{i&&l&&Z&&!L&&pq(l.id,M)},[i,l,Z,M,L]),b.useEffect(()=>{(!i||l)&&!g&&M&&!r.view&&ii.test(M)&&f.prefetchQuery(my(n,M,L))},[i,l,g,M,r.view,L,n,f]);const{data:ae}=rt({queryKey:["resolve",n,M],queryFn:()=>We(n+"resolve?path="+encodeURIComponent(M)),enabled:X,retry:!1,staleTime:6e4}),[le,be]=b.useState(null);b.useEffect(()=>{!X||!ae?.to||(be({from:M,to:ae.to}),gt($n(ae.to,l?.id,void 0,r.full,r.editing),{replace:!0}))},[X,ae,M,l?.id,r.full,r.editing]);const[$,q]=b.useState(()=>new Set),V=b.useRef(!0);b.useEffect(()=>{if(!h||!V.current)return;V.current=!1;const ie=(h.children||[]).filter(Ee=>Ee.dir);ie.length===1&&q(Ee=>new Set(Ee).add(ie[0].path))},[h]),b.useEffect(()=>{!H||!g||q(ie=>{const Ee=new Set(ie);for(const ze of _H(H))Ee.add(ze);return y.has(H)&&Ee.add(H),Ee})},[H,g,y]);const ee=b.useCallback(ie=>{q(Ee=>{const ze=new Set(Ee);return ze.has(ie)?ze.delete(ie):ze.add(ie),ze})},[]),K=b.useRef(null),O=b.useRef(new Map),D=b.useRef(IS("",0)),B=b.useCallback(()=>{const ie=K.current;if(!ie)return;const Ee=CB(D.current,u);Ee!==null&&ie.scrollTo({top:Ee,behavior:"instant"})},[u]);b.useEffect(()=>{D.current=IS(u,c$()==="POP"?O.current.get(u)??0:0),B()},[u,B]);const P=b.useCallback(()=>{const ie=K.current;ie&&(O.current.set(u,ie.scrollTop),_B(D.current,u,ie.scrollTop,ie.scrollHeight-ie.clientHeight))},[u]),I=b.useCallback((ie,Ee)=>{gt($n(ie,l?.id,Ee)),fs()},[l?.id]),re=b.useCallback(ie=>gt(un("history",l?.id,ie)),[l?.id]),[he,we]=b.useState(""),[Se,ve]=b.useState(!1),[Me,Ye]=b.useState(!1),[ht,tt]=b.useState(!1),[es,Fe]=b.useState("");b.useEffect(()=>n3(ie=>{Fe(ie??""),tt(!0)}),[]);const ot=b.useRef(null),Yt=b.useRef(null),jt=b.useRef(null),sn=b.useRef(null),Ct=e.panel??null,Lt=!Ct&&i&&!!l&&(Z||U)&&In(l.perm,"write"),ts=ie=>K2(_,ie)?.me,At=!Ct&&Z&&!L&&(!i||!!l&&In(ts(M)??l.perm,"write")),rn=!!r.editing&&At;b.useEffect(()=>{if(!At||!Z||rn)return;(window.requestIdleCallback??(Ee=>window.setTimeout(Ee,1500)))(()=>Cp())},[At,Z,rn]);const[ns,hr]=b.useState(!1);b.useEffect(()=>{hr(!1)},[M,L]);const Hs=b.useMemo(()=>{const ie=t.me?.name||t.me?.email||"Someone";let Ee=0;for(let ze=0;zeTn||[],[Tn]),Y=z.filter(ie=>!ie.resolved).length,[W,de]=b.useState(!1),[me,xe]=b.useState(null),[je,_e]=b.useState(!1),Ae=b.useCallback(()=>de(!0),[]);b.useEffect(()=>{xe(null),_e(!1)},[M]),b.useEffect(()=>{r.comment&&(de(!0),xe(r.comment))},[r.comment]);const Ke=!!r.full&&!r.view&&!!M&&!U&&!Ct,[_t,an]=b.useState(null),Dt=b.useRef(null),Le=b.useRef(null),dt=b.useRef(!1);b.useEffect(()=>{dt.current=!1},[M]);const Nt=b.useCallback(()=>{dt.current=!0,gt($n(M,l?.id,L,!0,r.editing))},[M,l?.id,L,r.editing]),$t=b.useCallback(()=>{dt.current?(dt.current=!1,history.back()):gt($n(M,l?.id,L,!1,r.editing),{replace:!0})},[M,l?.id,L,r.editing]);b.useLayoutEffect(()=>{if(Ke)return document.body.classList.add("full-view"),document.body.classList.remove("sb-open"),pi(),()=>{document.body.classList.remove("full-view"),pi()}},[Ke]),b.useEffect(()=>{if(!Ke)return;const ie=Ee=>{Ee.key==="Escape"&&!ht&&$t()};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[Ke,ht,$t]);const Hn=b.useRef(!1);b.useEffect(()=>{Ke?Le.current?.focus():Hn.current&&Dt.current?.focus(),Hn.current=Ke},[Ke]);const{data:vt}=mE(l?.id,i&&!!l),fn=b.useCallback(()=>{f.invalidateQueries({queryKey:["shares",l?.id]})},[f,l?.id]),mr=Z?(vt||[]).filter(ie=>ie.path===M):[],{data:Cn}=rt({queryKey:["desktop-status"],queryFn:()=>We("/api/desktop/status"),enabled:!!t.desktop,staleTime:6e4}),on=t.desktop&&l?Cn?.mounts.find(ie=>ie.project===l.id)?.server:void 0,qr=b.useCallback(async()=>{if(!on)return;const ie=on+window.location.pathname,Ee=await Mn(ie);Ne(Ee?"Web link copied":ie,!Ee)},[on]),qn=!Ct&&i&&!!l,$o=!Ct&&Z&&!r.view,Oa=!Ct&&Z,ps=Oa&&!P_.test(M)&&!ad.test(M)&&!Dr.test(M),Ft=Oa&&!ad.test(M)&&!rn,_n=!Ct&&(Z||i&&!!l&&U),Br=L?n+"blob?sha="+L+"&name="+encodeURIComponent(M)+"&download=1":n+"download?path="+encodeURIComponent(M),Aa=!Dr.test(M),Df=Mo(n,M,L)+"&print=1",Fo=b.useCallback(()=>{Ye(!1),Aa?window.print():Yt.current?.click()},[Aa]),Ci=b.useCallback(async()=>{try{const ie=await kf(Mo(n,M,L));if(ie.kind!=="text")return Ne(ie.kind==="too-large"?"Too large to copy — use Download.":"That file isn't text — use Download.",!0);const Ee=await Mn(ie.text);Ne(Ee?"Copied "+M:"Copy failed — the clipboard needs a secure (https) origin.",!Ee)}catch(ie){Ne("Copy failed: "+ie.message,!0)}},[n,M,L]),pr=b.useCallback(()=>ve(!0),[]),[Io,gr]=b.useState(""),gs=i&&!!l&&In(l?.perm,"write"),Da=b.useCallback(async(ie,Ee,ze)=>{if(await ir("Restore this version of "+ie+"?","It syncs to every device as a new change. "+(ze?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){gr(ie+Ee);try{await Sn(n+"restore",{path:ie,sha:Ee}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Restored "+ie+" — it syncs to every device like any other change.")}catch(Qe){Ne("Restore failed: "+Qe.message,!0)}finally{gr("")}}},[n,f]),[Gr,Ht]=b.useState(""),_i=b.useCallback(async ie=>{if(await ir("Remove "+ie+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Ht(ie);try{await Sn(n+"remove",{path:ie}),f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n,ie]}),f.invalidateQueries({queryKey:["text"]}),Ne("Removed "+ie+" — it syncs to every device like any other change.")}catch(Ee){Ne("Remove failed: "+Ee.message,!0)}finally{Ht("")}}},[n,f]),[bc,qs]=b.useState(""),Kr=b.useCallback(async ie=>{const Ee=ie.session||ie.note,ze=ie.session?{session:ie.session,device:ie.entries[0]?.device?.id}:{note:ie.note,device:ie.entries[0]?.device?.id};qs(Ee);try{const Qe=await Sn(n+"undo-run",{...ze,preview:!0}),Nn=new Set(Qe.changed_after);if(!Qe.undone.length){Ne("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await ir("Undo this run?",o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[ie.note||Ee," — ",Qe.undone.length," file",Qe.undone.length===1?"":"s"]}),o.jsx("div",{className:"undo-list",children:Qe.undone.map(Fa=>o.jsxs("div",{className:"undo-row",children:[o.jsx("span",{className:"undo-path",children:Fa.path}),Nn.has(Fa.path)&&o.jsx("span",{className:"undo-after",children:"changed after this run"}),o.jsx("span",{className:"undo-what",children:Fa.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},Fa.path))}),Nn.size>0&&o.jsxs("div",{className:"undo-warn",children:[Nn.size," file",Nn.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",Nn.size===1?"that change":"those changes"," too."]}),Qe.skipped.length>0&&o.jsxs("div",{children:[Qe.skipped.length," already hold",Qe.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),Qe.refused.length>0&&o.jsxs("div",{children:[Qe.refused.length," path",Qe.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",Qe.refused.join(", "),"."]})]}),"Undo run",!0))return;const Dn=await Sn(n+"undo-run",ze);f.invalidateQueries({queryKey:["history",n]}),f.invalidateQueries({queryKey:["tree",n]}),f.invalidateQueries({queryKey:["render",n]}),f.invalidateQueries({queryKey:["text"]});const Zs=Dn.skipped.length?`, skipped ${Dn.skipped.length} (already current)`:"";Ne(`Undid ${Dn.undone.length} file${Dn.undone.length===1?"":"s"}${Zs}.`)}catch(Qe){Ne("Undo failed: "+Qe.message,!0)}finally{qs("")}},[n,f]),Ei=b.useCallback(()=>{if(!M)return re("");re(U?M+"/":M)},[M,U,re]);b.useEffect(()=>{const ie=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key.toLowerCase()==="k"&&(Ee.preventDefault(),Fe(""),tt(ze=>!ze))};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[]);const wc=b.useCallback(()=>{const ie=[],Ee=ze=>ie.push(ze);if(i&&l){const ze=l.id,Qe=Ks=>()=>{e.onClosePanel?.(),gt(Ks)};Ee({icon:"home",label:l.name,hint:"Home",kind:"project",group:"Go to",run:Qe("/"+ze)});const Nn=(Ks,Dn,Zs)=>Ee({icon:Ks,label:Dn,kind:"page",group:"Go to",run:Qe(Zs)});Nn("activity","Activity",un("history",ze)),Nn("insights","Insights",un("dashboard",ze)),Nn("gear","Settings",un("settings",ze)),Nn("laptop","Connect a device",un("install",ze))}if(i&&l&&M){const ze=M.slice(M.lastIndexOf("/")+1),Qe=(Nn,Ks,Dn)=>Ee({icon:Nn,label:Ks,hint:ze,kind:"action",group:ze,run:Dn});Lt&&Qe("share","Share",pr),Qe("hist","History",Ei),Z&&Qe("download","Download",()=>ot.current?.click()),Ft&&Qe("printer","Print",Fo),ps&&Qe("copy","Copy",Ci)}if(i)for(const ze of e.projects||[])(!l||ze.id!==l.id)&&Ee({icon:"folder",label:ze.name,kind:"project",group:"Projects",run:()=>gt("/"+ze.id)});t.auth?.enabled&&Ee({icon:"power",label:"Sign out",kind:"action",group:"Account",run:()=>window.location.href="/auth/logout"});for(const ze of y.keys())Ee({icon:"folder",label:ze,kind:"folder",run:()=>I(ze)});for(const ze of m)Vr(ze.path)||Ee({icon:"doc",label:ze.path,kind:"file",run:()=>I(ze.path)});return ie},[i,l,M,Z,Lt,ps,Ft,t.auth?.enabled,y,m,e.projects,e.onClosePanel,pr,Ci,Fo,Ei,I]),Po=RN(i?l?.id:void 0),zf=b.useMemo(()=>Po.map(ie=>ie.path).filter(ie=>ie!==M),[Po,M]),It=i?l?.id:void 0;b.useEffect(()=>{if(!It)return;const ie=()=>mU(It);return window.addEventListener("pagehide",ie),()=>{window.removeEventListener("pagehide",ie),ie()}},[It]);const za=r.view==="history"&&!r.viewTarget;b.useEffect(()=>{It&&za&&pU(It)},[It,za]);const vs=ry(It),En=b.useMemo(()=>hH(h,vs),[h,vs]),Ni=vU(It),Sc=AU(n,!!It&&!!t.comments&&Ni.length>0),ki=b.useMemo(()=>({comments:Sc,conflicts:En.conflicts}),[Sc,En.conflicts]),La=b.useMemo(()=>new Set(m.map(ie=>ie.path)),[m]),Ri=b.useCallback(ie=>La.has(ie)||y.has(ie),[La,y]),Lf=b.useMemo(()=>[...y.keys()],[y]),{query:On}=ly(),Bs=yU();b.useEffect(()=>xg,[]);const Mi=i&&!!l&&t.upload.enabled&&In(l.perm,"write"),Ti=b.useCallback(ie=>!!l&&In(ts(ie?ie+"/":"")??l.perm,"write"),[l,_]),Gs=b.useCallback(async ie=>{const Ee=(await Wl("New file","File name","untitled.md","Create"))?.trim().replace(/^\/+/,"");if(!Ee)return;const ze=(ie?ie+"/":"")+Ee;if(La.has(ze)||y.has(ze)){Ne(ze+" already exists",!0);return}try{await BM(n+"upload/content?path="+encodeURIComponent(ze),""),await f.invalidateQueries({queryKey:["tree",n]}),gt($n(ze,l?.id,void 0,!1,!0)),fs()}catch(Qe){Ne("Could not create "+ze+": "+Qe.message,!0)}},[n,La,y,l?.id,f]),$a=b.useMemo(()=>({open:ie=>{e.onClosePanel?.(),I(ie)},newFile:Mi?Gs:void 0,canCreateIn:Ti,pinned:It?ie=>ay(It).includes(ie):void 0,togglePin:It?ie=>W1(It,ie):void 0,copyPath:async ie=>{const Ee=await Mn(ie);Ne(Ee?"Path copied":ie,!Ee)},copyShareLink:i&&l&&In(l.perm,"write")?async ie=>{const Ee=(vt||[]).find(ze=>ze.path===ie);if(Ee){const ze=await Mn(Ee.url);Ne(ze?"Share link copied":Ee.url,!ze);return}e.onClosePanel?.(),I(ie),ve(!0)}:void 0,history:i&&l?ie=>re(ie):void 0,insights:i&&l?ie=>gt(un("dashboard",l.id,ie)):void 0,remove:gs?_i:void 0}),[Mi,Gs,Ti,It,i,l,vt,I,re,gs,_i,e.onClosePanel]);b.useEffect(()=>{if(!Me)return;const ie=()=>Ye(!1);return document.addEventListener("click",ie),()=>document.removeEventListener("click",ie)},[Me]);const Oi=b.useCallback(ie=>y.has(ie),[y]);let Bn="app",Ai,An;if(Ct)An=Ct.body;else if(r.view==="dashboard")Bn="wide",An=o.jsx(Dq,{apiBase:i?n:void 0,flatFiles:m,heatMap:S,devices:A,scope:r.viewTarget||"",loading:!g,installHref:l?un("install",l.id):void 0,onOpenFile:I,onOpenFolder:I,onOpenHistory:re,isFolder:Oi});else if(r.view==="history")Bn="wide",Ai="activity-page",An=o.jsx(uB,{apiBase:n,target:r.viewTarget||"",isFolder:Oi,flatFiles:m,projectId:l?.id,onOpen:I,onMeta:we,onRendered:B,restore:gs?{onRestore:Da,busy:Io}:void 0,remove:gs?{onRemove:_i,busy:Gr}:void 0,undoRun:gs?{onUndoRun:Kr,busy:bc}:void 0,filters:r.filters,linkFor:(ie,Ee)=>$n(ie,l?.id,Ee),onFilters:ie=>gt(un("history",l?.id,r.viewTarget||"",ie))});else if(M)if(!g)An=ii.test(M)?o.jsx(uN,{}):o.jsx("div",{className:"empty",children:"Loading…"});else if(X)An=o.jsxs("div",{className:"notfound",children:[o.jsx("h1",{children:"Couldn't find that"}),o.jsxs("p",{children:[o.jsx("code",{children:M})," isn't in this project right now."]}),o.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),o.jsx("button",{className:"pbtn",onClick:()=>f.invalidateQueries({queryKey:["tree",n]}),children:"Check again"})]});else if(U)An=o.jsx(hN,{node:y.get(M),heatMap:S,folders:_,hub:i&&!!l,apiBase:n,onOpen:I,onFullHistory:re,onRendered:B});else{Bn=Dr.test(M)||ad.test(M)?"wide":"read",Ai="markdown",Ke&&!ii.test(M)&&(Ai+=" bleed");const ie=Vr(M);An=o.jsxs(o.Fragment,{children:[L&&o.jsx(EB,{apiBase:n,path:M,version:L,onViewCurrent:()=>I(M)}),ie&&o.jsx(NB,{conflict:ie,originalHref:m.some(Ee=>Ee.path===ie.original)?()=>I(ie.original):void 0}),(()=>{const Ee=o.jsx(XH,{apiBase:n,path:M,version:L,heatMap:S,flatFiles:m,projectId:l?.id,onOpenFile:I,onMeta:we,onRendered:B,editing:rn,editSource:ns,me:Hs,commentable:ms,flushRef:jt});return ms?o.jsx(k7,{apiBase:n,path:M,framed:Dr.test(M),lines:!ii.test(M)&&!Dr.test(M)&&!U_.test(M),threads:z,focus:me,onFocus:xe,onOpenPanel:Ae,picking:je,onPicking:_e,children:Ee}):Ee})()]})}else R?(m.length>0&&(Bn="wide"),An=o.jsx(Nq,{project:l,tree:h,flatFiles:m,loaded:g,heatMap:S,folders:_,me:t.me,comments:!!t.comments,existing:r.connect==="existing",onOpen:I,onFullHistory:re,onRendered:B})):An=o.jsx("div",{className:"empty",children:"Select a file to read it."});le&&le.to===M&&(An=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"vbanner",role:"status",children:[o.jsx("span",{className:"vb-icon",children:o.jsx(ge,{name:"link"})}),o.jsxs("div",{className:"vb-text",children:[o.jsxs("b",{children:["Moved from ",le.from]}),o.jsx("span",{children:"The URL has been updated."})]})]}),An]}));const jc=Ct?Ct.crumb:M?o.jsxs(o.Fragment,{children:[o.jsx(kH,{path:M,onOpenFolder:I}),i&&Z&&!L&&!rn&&o.jsx("span",{className:"sync-pill",title:"This file is on the hub and syncing to every device",children:"Synced"})]}):r.view==="dashboard"?"Insights — "+(r.viewTarget||l?.name||""):r.view==="history"?"Activity — "+xB(r.viewTarget||"",Oi):R?l.name:null,Uo=o.jsx(li,{nav:t.desktop?o.jsxs("span",{id:"nav-btns",children:[o.jsx("button",{className:"nav-btn",title:"Back (⌘[)","aria-label":"Back",onClick:()=>history.back(),children:o.jsx(ge,{name:"chevl"})}),o.jsx("button",{className:"nav-btn",title:"Forward (⌘])","aria-label":"Forward",onClick:()=>history.forward(),children:o.jsx(ge,{name:"chev"})})]}):void 0,crumb:jc,meta:he,actions:o.jsxs(o.Fragment,{children:[o.jsx(jV,{people:x,path:M}),ms&&o.jsxs(Ie,{id:"comments-btn",variant:"toolbar",className:"ghost",title:Y?`${Y} open comment${Y===1?"":"s"}`:"Comments","aria-label":"Comments","aria-pressed":W,onClick:()=>de(ie=>!ie),children:[o.jsx(ge,{name:"comment"})," ",o.jsx("span",{className:"lbl",children:"Comments"}),Y>0&&o.jsx("span",{className:"cm-count",children:Y})]}),qn&&(Z||!M&&!r.view)&&o.jsxs(Ie,{id:"history-btn",variant:"toolbar",className:"ghost",title:"History","aria-label":"History",onClick:Ei,children:[o.jsx(ge,{name:"hist"})," ",o.jsx("span",{className:"lbl",children:"History"})]}),At&&o.jsxs(Ie,{id:"edit-btn",variant:"toolbar",onPointerEnter:()=>{rn||(Cp(),gS(f,n,M))},onFocus:()=>{rn||(Cp(),gS(f,n,M))},title:rn?"Stop editing":"Edit this file",onClick:async()=>{if(!rn){gt($n(M,l?.id,L,r.full,!0));return}const ie=jt.current;if(!(ie&&sn.current===ie)){sn.current=ie;try{const Ee=window.location.pathname;let ze=!0;try{ze=await(ie?.()??Promise.resolve(!0))}catch{}if(!ze||window.location.pathname!==Ee)return;const Qe=new URLSearchParams(window.location.search).get("full")==="1";gt($n(M,l?.id,L,Qe,!1))}finally{sn.current===ie&&(sn.current=null)}}},children:[!rn&&o.jsx(ge,{name:"pencil"})," ",o.jsx("span",{className:"lbl-keep",children:rn?"Done":"Edit"})]}),rn&&Dr.test(M)&&o.jsx(Ie,{id:"edit-source-btn",variant:"toolbar",title:ns?"Back to editing the page":"Edit this file's HTML markup",onClick:()=>{jt.current&&sn.current===jt.current||hr(ie=>!ie)},children:ns?"Edit page":"Edit source"}),Lt&&o.jsxs(Ie,{id:"share-btn",variant:"primary",title:"Share","aria-label":"Share",onClick:pr,children:[o.jsx(ge,{name:"link"})," ",o.jsx("span",{className:"lbl",children:"Share"})]}),$o&&o.jsx(Ie,{id:"full-btn",ref:Dt,variant:"toolbar",className:"icon-only",title:"Fullscreen","aria-label":"Fullscreen",onClick:Nt,children:o.jsx(ge,{name:"expand"})}),Oa&&o.jsx("a",{id:"download",hidden:!0,download:!0,href:Br,ref:ot,children:"Download"}),Ft&&!Aa&&o.jsx("a",{id:"print",hidden:!0,target:"_blank",rel:"noopener",href:Df,ref:Yt,children:"Print"}),_n&&o.jsx(Ie,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:ie=>{ie.stopPropagation(),Ye(!Me)},children:o.jsx(ge,{name:"dots"})}),Me&&o.jsxs("div",{id:"more-menu",role:"menu",children:[qn&&o.jsx("button",{className:"more-item",onClick:Ei,children:"History"}),Oa&&o.jsx("button",{className:"more-item",onClick:()=>ot.current?.click(),children:"Download"}),Ft&&o.jsx("button",{id:"print-item",className:"more-item",onClick:Fo,children:"Print"}),on&&o.jsx("button",{className:"more-item",onClick:qr,children:"Copy web link"}),ps&&o.jsx("button",{className:"more-item",onClick:Ci,children:"Copy"}),i&&!!l&&o.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),gt(un("dashboard",l?.id,M))},children:"Insights"})]})]})});return o.jsxs(o.Fragment,{children:[o.jsx(oi,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,rail:o.jsxs(oE,{top:e.sidebar.railTop,children:[e.sidebar.railNav,o.jsx(NH,{pins:Ni,badges:ki,onOpen:$a.open})]}),tree:o.jsxs(o.Fragment,{children:[!i&&o.jsx(F2,{}),On.trim()?o.jsx(CH,{query:On,dirs:Lf,files:m,onOpen:$a.open}):o.jsxs(o.Fragment,{children:[It&&o.jsx(EH,{pins:Ni,badges:ki,exists:Ri,currentPath:H,onOpen:$a.open,onUnpin:ie=>W1(It,ie)}),It&&o.jsxs("div",{className:"sb-section files-head",children:[o.jsx("span",{children:"Files"}),o.jsx("button",{className:"tact"+(Bs==="recent"?" on":""),id:"tree-sort-btn","aria-label":Bs==="recent"?"Sort by name":"Sort by most recently changed","aria-pressed":Bs==="recent",title:Bs==="recent"?"Sorted by most recently changed":"Sorted by name",onClick:()=>xU(Bs==="recent"?"name":"recent"),children:o.jsx(ge,{name:"sort"})}),Mi&&o.jsx("button",{className:"tact",id:"new-file-root","aria-label":"New file",title:"New file",onClick:()=>Gs(""),children:o.jsx(ge,{name:"fileplus"})})]}),o.jsx(SH,{root:h,expanded:$,onToggle:ee,currentPath:H,listingShowing:Q,restricted:N,stats:En,order:Bs,actions:$a})]})]}),topbar:Uo,exit:Ke?o.jsxs("button",{id:"exit-full",ref:Le,onClick:$t,"aria-label":"Exit fullscreen",children:[o.jsx(ge,{name:"shrink"}),o.jsx("span",{className:"lbl",children:"Exit"}),o.jsx("kbd",{children:"esc"})]}):void 0,contentRef:K,onContentScroll:P,children:o.jsxs(bo,{width:Bn,className:Ai,style:Bn==="read"&&_t!==null?{"--page-read":_t+"px"}:void 0,children:[!Ct&&Z&&o.jsx(b7,{shares:mr,canRevoke:!!l&&In(l.perm,"write"),onChanged:fn}),An,Bn==="read"&&o.jsx(SB,{width:_t,onChange:an})]})}),Se&&l&&o.jsx(x7,{project:l,path:M,isDir:U,shares:vt||[],onChanged:fn,onOpenFolder:ie=>gt($n(ie,l.id)),onClose:()=>{ve(!1),fn()}}),ms&&W&&o.jsx(R7,{apiBase:n,path:M,threads:z,focus:me,onFocus:xe,onClose:()=>{de(!1),_e(!1)},framed:Dr.test(M),picking:je,onPicking:_e,me:t.me?.email,admin:In(l?.perm,"admin")}),o.jsx(cq,{open:ht,onClose:()=>tt(!1),candidates:wc,recent:zf,initialQuery:es})]})}function kB({config:e}){const t=Av(),n=gE(),[r,i]=b.useState(null),[l,u]=b.useState(null);b.useEffect(()=>u(null),[t]);const f=b.useMemo(()=>{if(!e.desktop)return null;const I=t.split("?")[0].match(/^\/setup(?:\/(connect|syncing|done))?\/?$/);return I?I[1]??"welcome":null},[t,e.desktop]),h=b.useMemo(()=>{const I=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return I?I[1]:null},[t]),m=b.useMemo(()=>new URLSearchParams(t.split("?")[1]||"").get("p")||"",[t]),y=JL(),{data:g}=WL(!h),{data:w}=fE(!h),x=!!e.auth.admin,{data:j}=pE(x),S=b.useMemo(()=>Tv(t,"hub"),[t]),[E,_]=b.useState(!1),N=()=>e.desktop?gt("/setup/connect"):_(!0),R=e.upload.enabled,T=async(I,re)=>{const he=re===P2;try{const we=await Sn("/api/projects",{name:I,template:he?"":re});_(!1),await n(),gt("/"+we.project.id+(he?"?connect=existing":"")),Ne(`Created “${we.project.name}”.`)}catch(we){Ne("Could not create the project: "+we.message,!0)}},A=E&&!e.desktop?o.jsx(lV,{templates:e.templates??[],onCreate:T,onClose:()=>_(!1)}):null,M=b.useMemo(()=>g&&(g.find(I=>I.id===S.project)||r&&g.find(I=>I.org===r)||g.find(I=>I.id===a3())||g[0])||null,[g,S.project,r]),L=kv(e.desktop?M?.id:void 0),H=b.useMemo(()=>!M||!e.desktop?M:{...M,perm:L.data?.me??M.perm},[M,e.desktop,L.data]);if(b.useEffect(()=>{document.title=M?yE(S,M.name):e.brand||"BearDrive"},[M,S,e.brand]),b.useEffect(()=>{M&&i3(M.id)},[M]),h)return o.jsx(RB,{token:h,onDone:async I=>{i(I),await n();const he=!!(m?await y().catch(()=>null):null)?.projects?.some(we=>we.id===m);gt(he?"/"+m+"/install":"/",{replace:!0})}});const U=e.brand||"BearDrive",Z=M&&w?.find(I=>I.id===M.org)||null,X=o.jsx(hf,{name:U,onHome:()=>gt("/"),beta:U==="BearDrive"}),Q=mn(),ae=(I,re)=>{re&&Ne(re),vd(I).catch(()=>{}).finally(()=>Q.invalidateQueries({queryKey:["config"]}))},le=e.me?{me:e.me,org:Z,orgActive:!!S.org,billing:e.billing,mcp:e.mcp,signOut:e.desktop?()=>ae("/api/desktop/logout"):void 0,admin:x?{pending:j?.length||0,onClick:()=>{u({kind:"hub"}),fs()}}:void 0}:void 0,be=!e.me&&e.desktop?o.jsx(BU,{onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")}):void 0;if(f)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx(oV,{step:f,signedIn:!!e.me,onSignIn:()=>ae("/api/desktop/login","Finish signing in in your browser…")})})});if(!g||!w)return o.jsx(oi,{vault:X,topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Loading…"})})});if(e.desktop&&g.length===0)return o.jsx(si,{to:"/setup"});if(!M)return o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsx(tV,{onNew:N,canCreate:R})}),A]});const $=l?.kind==="hub"?{crumb:"Signup & access",body:o.jsx(oU,{})}:null,q=S.org?w.find(I=>I.id===S.org):null,ee=S.org&&!q?{crumb:"Organization",body:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Organization not found"}),o.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}:q?{crumb:"Organization",body:o.jsx(sU,{org:q,projects:g,myEmail:e.me?.email||""})}:null;if(!!S.project&&!g.some(I=>I.id===S.project)){const I=l$(g,S.project);return I?o.jsx(si,{to:S.view?un(S.view,I,S.viewTarget,S.filters):$n(S.path,I,S.version,S.full,S.editing)}):o.jsxs(oi,{vault:X,projectsNav:o.jsx(pp,{projects:g,account:le,onNew:N}),orgBar:be,topbar:o.jsx(li,{}),children:[o.jsx(bo,{children:o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"Project not found"}),o.jsxs("p",{children:["There's no project called “",mf(S.project),"” in your account. It may have been renamed or deleted, or the link may be wrong."]}),o.jsx("p",{children:o.jsxs("a",{...Pn("/"+M.id),children:["Back to ",M.name]})})]})}),A]})}const O=S.connections?{crumb:"Connected agents",body:e.mcp?o.jsx(lU,{projects:g}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No agent access on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't serve an MCP endpoint."})]})}:null,D=S.billing?{crumb:"Billing",body:e.billing?o.jsx(GU,{url:e.billing.url}):o.jsxs("div",{className:"empty",children:[o.jsx("h3",{children:"No billing on this hub"}),o.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,B=S.view==="settings"?{crumb:"Project settings",body:o.jsx(YU,{project:H??M,org:Z,onDeleted:async()=>{await n(),gt("/")}})}:S.view==="install"?{crumb:"Installation",body:o.jsx(I2,{project:M,existing:S.connect==="existing"})}:null;if(!S.org&&!S.billing&&!S.connections&&S.project!==M.id)return o.jsx(si,{to:"/"+M.id});if(S.legacyView&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.queryTarget&&S.view)return o.jsx(si,{to:un(S.view,M.id,S.viewTarget,S.filters)});if(S.trailingSlash&&S.path)return o.jsx(si,{to:$n(S.path,M.id,S.version,S.full,S.editing)});const P={active:l?null:!S.view&&!S.path?"home":S.view==="dashboard"&&!S.viewTarget?"insights":S.view==="history"&&!S.viewTarget?"activity":S.view==="settings"?"settings":null,onNav:I=>{u(null),gt(I==="home"?"/"+M.id:un(I==="activity"?"history":I==="insights"?"dashboard":"settings",M.id)),fs()}};return o.jsxs(o.Fragment,{children:[o.jsx(LN,{config:e,apiBase:"/api/p/"+M.id+"/",route:S,hub:!0,project:H??M,projects:g,sidebar:{vault:X,projectsNav:o.jsx(pp,{projects:g,currentId:M.id,account:le,onNew:N,menu:P}),railTop:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"rail-mark",children:o.jsx(jv,{size:20})}),o.jsx(UU,{projects:g,current:M,menu:P,account:le,onNew:N})]}),railNav:o.jsx(PU,{pid:M.id,menu:P}),orgBar:o.jsxs(o.Fragment,{children:[o.jsx(IU,{pid:M.id,readsEnabled:!!e.reads?.enabled,active:!l&&S.view==="install",onOpen:()=>{u(null),gt(un("install",M.id)),fs()}}),be]})},panel:$||ee||D||O||B,onClosePanel:()=>u(null)},M.id),A]})}function RB({token:e,onDone:t}){return b.useEffect(()=>{let n=!1;return Sn("/api/invites/"+e).then(r=>{n||(Ne(`Welcome — you joined the “${r.org.name}” team. Opening its projects…`),t(r.org.id))}).catch(r=>{n||String(r.message).includes("signing in")||(Ne("Could not accept the invite: "+r.message,!0),t(null))}),()=>{n=!0}},[e]),o.jsx(oi,{vault:o.jsx(hf,{name:"BearDrive",beta:!0}),topbar:o.jsx(li,{}),children:o.jsx(bo,{children:o.jsx("div",{className:"empty",children:"Joining…"})})})}function MB({config:e}){const t=Av(),n=e.volume||"BearDrive",r=b.useMemo(()=>Tv(t,"volume"),[t]),i=e.brand||e.volume;return b.useEffect(()=>{document.title=i?yE(r,i):"BearDrive"},[r,i]),r.trailingSlash&&r.path?o.jsx(si,{to:$n(r.path,void 0,r.version,r.full,r.editing)}):o.jsx(LN,{config:e,apiBase:"/api/",route:r,hub:!1,sidebar:{vault:o.jsx(hf,{name:n,showSignout:e.auth.enabled})}})}function TB(){const{data:e}=KM();return o.jsxs(t3,{delayDuration:150,children:[e?e.mode==="hub"?o.jsx(kB,{config:e}):o.jsx(MB,{config:e}):o.jsx(oi,{vault:o.jsx(hf,{name:"…",showSignout:!1}),topbar:o.jsx(li,{}),children:o.jsx("div",{className:"empty",children:"Loading…"})}),o.jsx(VL,{}),o.jsx(ZL,{}),o.jsx(XL,{})]})}const OB=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$/;function AB(e,t){if(!e.project||!OB.test(e.project))return[];const n="/api/p/"+e.project+"/",r=[{queryKey:["projects"],url:"/api/projects"},{queryKey:["orgs"],url:"/api/orgs"},{queryKey:["tree",n],url:n+"tree?slim=1"}],i={queryKey:["heat",n],url:n+"heat?days=30"},l=e.path;if(!l||e.view||e.version||e.editing||!t(l))return[...r,i];const u=encodeURIComponent(l);return[...r,{queryKey:["render",n,l,""],url:n+"render?path="+u},i,{queryKey:["comments",n,l],url:n+"comments?status=all&path="+u}]}async function DB(e){const t=await fetch(e,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(e+": "+t.status);return t.json()}function zB(e,t){for(const{queryKey:n,url:r}of AB(Tv(t,"hub"),i=>ii.test(i)))e.prefetchQuery({queryKey:n,queryFn:()=>DB(r),retry:!1})}class LB extends b.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("BearDrive: unhandled render error",t,n.componentStack)}render(){return this.state.error?o.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[o.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),o.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),o.jsx("p",{className:"mb-4",children:o.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),o.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const $N=new EM({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:3e4}}});GM();zB($N,location.pathname+location.search);IL();JR.createRoot(document.getElementById("root")).render(o.jsx(b.StrictMode,{children:o.jsx(LB,{children:o.jsx(NM,{client:$N,children:o.jsx(TB,{})})})}));export{Hg as H,VB as a,Sg as b,qB as c,GB as d,Mo as e,kf as f,BB as g,BM as h,PB as i,o as j,YB as k,KB as l,xV as m,ZB as o,SV as p,b as r,uy as s,Ne as t,HB as w}; diff --git a/internal/webapp/static/assets/sharedfile-CR4ZqPh0.js b/internal/webapp/static/assets/sharedfile-f4YTnm99.js similarity index 99% rename from internal/webapp/static/assets/sharedfile-CR4ZqPh0.js rename to internal/webapp/static/assets/sharedfile-f4YTnm99.js index deb011f5..b1f8b227 100644 --- a/internal/webapp/static/assets/sharedfile-CR4ZqPh0.js +++ b/internal/webapp/static/assets/sharedfile-f4YTnm99.js @@ -1,4 +1,4 @@ -import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-Co6en_o0.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` +import{H as et,h as En,i as Jt,k as Qo,l as xr,m as de,f as Lr,e as Or}from"./index-Dgs5VYVU.js";const it=()=>new Map,Ts=e=>{const t=it();return e.forEach((n,s)=>{t.set(s,n)}),t},It=(e,t,n)=>{let s=e.get(t);return s===void 0&&e.set(t,s=n()),s},Zo=(e,t)=>{const n=[];for(const[s,r]of e)n.push(t(r,s));return n},tl=(e,t)=>{for(const[n,s]of e)if(t(s,n))return!0;return!1},zt=()=>new Set,ps=e=>e[e.length-1],el=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(e);for(let s=0;s{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class sl{constructor(){this._observers=it()}on(t,n){It(this._observers,t,zt).add(n)}once(t,n){const s=(...r)=>{this.off(t,s),n(...r)};this.on(t,s)}off(t,n){const s=this._observers.get(t);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(t))}emit(t,n){return $t((this._observers.get(t)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const kt=Math.floor,Tn=Math.abs,Ps=(e,t)=>ee>t?e:t,rl=Math.pow,hi=e=>e!==0?e<0:1/e<0,Rr=1,Ur=2,ws=4,ms=8,Ke=32,Nt=64,ht=128,qn=31,xs=63,re=127,il=2147483647,Rn=Number.MAX_SAFE_INTEGER,Mr=Number.MIN_SAFE_INTEGER,ol=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&kt(e)===e),ui=String.fromCharCode,ll=e=>e.toLowerCase(),cl=/^\s*/g,al=e=>e.replace(cl,""),hl=/([A-Z])/g,vr=(e,t)=>al(e.replace(hl,n=>`${t}${ll(n)}`)),ul=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,s=new Uint8Array(n);for(let r=0;rQe.encode(e),dl=Qe?fl:ul;let Ge=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Ge&&Ge.decode(new Uint8Array).length===1&&(Ge=null);const gl=(e,t)=>nl(t,()=>e).join("");class cn{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const K=()=>new cn,Ws=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Ws(e));let n=0;for(let s=0;s{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Ls=q,_=(e,t)=>{for(;t>re;)q(e,ht|re&t),t=kt(t/128);q(e,re&t)},Ys=(e,t)=>{const n=hi(t);for(n&&(t=-t),q(e,(t>xs?ht:0)|(n?Nt:0)|xs&t),t=kt(t/64);t>0;)q(e,(t>re?ht:0)|re&t),t=kt(t/128)},Os=new Uint8Array(3e4),wl=Os.length/3,ml=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),s=n.length;_(e,s);for(let r=0;r{const n=e.cbuf.length,s=e.cpos,r=Ps(n-s,t.length),i=t.length-r;e.cbuf.set(t.subarray(0,r),s),e.cpos+=r,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ae(n*2,i)),e.cbuf.set(t.subarray(r)),e.cpos=i)},H=(e,t)=>{_(e,t.byteLength),zn(e,t)},qs=(e,t)=>{pl(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kl=(e,t)=>qs(e,4).setFloat32(0,t,!1),Sl=(e,t)=>qs(e,8).setFloat64(0,t,!1),bl=(e,t)=>qs(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),_l=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Ze=(e,t)=>{switch(typeof t){case"string":q(e,119),ie(e,t);break;case"number":ol(t)&&Tn(t)<=il?(q(e,125),Ys(e,t)):_l(t)?(q(e,124),kl(e,t)):(q(e,123),Sl(e,t));break;case"bigint":q(e,122),bl(e,t);break;case"object":if(t===null)q(e,126);else if(De(t)){q(e,117),_(e,t.length);for(let n=0;n0&&_(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const Fr=e=>{e.count>0&&(Ys(e.encoder,e.count===1?e.s:-e.s),e.count>1&&_(e.encoder,e.count-2))};class xn{constructor(){this.encoder=new cn,this.s=0,this.count=0}write(t){this.s===t?this.count++:(Fr(this),this.count=1,this.s=t)}toUint8Array(){return Fr(this),B(this.encoder)}}const Br=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);Ys(e.encoder,t),e.count>1&&_(e.encoder,e.count-2)}};class ys{constructor(){this.encoder=new cn,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Br(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Br(this),B(this.encoder)}}class El{constructor(){this.sarr=[],this.s="",this.lensE=new xn}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new cn;return this.sarr.push(this.s),this.s="",ie(t,this.sarr.join("")),zn(t,this.lensE.toUint8Array()),B(t)}}const Ct=e=>new Error(e),yt=()=>{throw Ct("Method unimplemented")},ut=()=>{throw Ct("Unexpected case")},fi=Ct("Unexpected end of array"),di=Ct("Integer out of Range");class Gn{constructor(t){this.arr=t,this.pos=0}}const Kt=e=>new Gn(e),Cl=e=>e.pos!==e.arr.length,Dl=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},X=e=>Dl(e,C(e)),Ae=e=>e.arr[e.pos++],C=e=>{let t=0,n=1;const s=e.arr.length;for(;e.posRn)throw di}throw fi},zs=e=>{let t=e.arr[e.pos++],n=t&xs,s=64;const r=(t&Nt)>0?-1:1;if((t&ht)===0)return r*n;const i=e.arr.length;for(;e.posRn)throw di}throw fi},Al=e=>{let t=C(e);if(t===0)return"";{let n=String.fromCodePoint(Ae(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Ae(e));else for(;t>0;){const s=t<1e4?t:1e4,r=e.arr.subarray(e.pos,e.pos+s);e.pos+=s,n+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(n))}},Il=e=>Ge.decode(X(e)),Yt=Ge?Il:Al,Gs=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Tl=e=>Gs(e,4).getFloat32(0,!1),xl=e=>Gs(e,8).getFloat64(0,!1),Ll=e=>Gs(e,8).getBigInt64(0,!1),Ol=[e=>{},e=>null,zs,Tl,xl,Ll,e=>!1,e=>!0,Yt,e=>{const t=C(e),n={};for(let s=0;s{const t=C(e),n=[];for(let s=0;sOl[127-Ae(e)](e);class Vr extends Gn{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Cl(this)?this.count=C(this)+1:this.count=-1),this.count--,this.s}}class Ln extends Gn{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=zs(this);const t=hi(this.s);this.count=1,t&&(this.s=-this.s,this.count=C(this)+2)}return this.count--,this.s}}class ks extends Gn{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=zs(this),n=t&1;this.diff=kt(t/2),this.count=1,n&&(this.count=C(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Rl{constructor(t){this.decoder=new Ln(t),this.str=Yt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const Ul=crypto.getRandomValues.bind(crypto),gi=()=>Ul(new Uint32Array(1))[0],Ml="10000000-1000-4000-8000"+-1e11,vl=()=>Ml.replace(/[018]/g,e=>(e^gi()&15>>e/4).toString(16)),Gt=Date.now,jr=e=>new Promise(e);Promise.all.bind(Promise);const Hr=e=>e===void 0?null:e;class Nl{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let pi=new Nl,Xs=!0;try{typeof localStorage<"u"&&localStorage&&(pi=localStorage,Xs=!1)}catch{}const wi=pi,$l=e=>Xs||addEventListener("storage",e),Fl=e=>Xs||removeEventListener("storage",e),en=Symbol("Equality"),mi=(e,t)=>e===t||!!e?.[en]?.(t)||!1,Bl=e=>typeof e=="object",Vl=Object.assign,jl=Object.keys,Hl=(e,t)=>{for(const n in e)t(e[n],n)},Jl=(e,t)=>{const n=[];for(const s in e)n.push(t(e[s],s));return n},Un=e=>jl(e).length,Pl=e=>{for(const t in e)return!1;return!0},an=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Ks=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Wl=(e,t)=>e===t||Un(e)===Un(t)&&an(e,(n,s)=>(n!==void 0||Ks(t,s))&&mi(t[s],n)),Yl=Object.freeze,yi=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&yi(e[t])}return Yl(e)},Qs=(e,t,n=0)=>{try{for(;ne,ke=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[en]!=null)return e[en](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nt.includes(e);var ki={};const Xt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Si=typeof window<"u"&&typeof document<"u"&&!Xt;let bt;const Gl=()=>{if(bt===void 0)if(Xt){bt=it();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");bt.set(`--${vr(t,"-")}`,n),bt.set(`-${vr(t,"-")}`,n)}})):bt=it();return bt},Rs=e=>Gl().has(e),Mn=e=>Hr(Xt?ki[e.toUpperCase().replaceAll("-","_")]:wi.getItem(e)),bi=e=>Rs("--"+e)||Mn(e)!==null,Xl=bi("production"),Kl=Xt&&zl(ki.FORCE_COLOR,["true","1","2"]),Ql=Kl||!Rs("--no-colors")&&!bi("no-color")&&(!Xt||process.stdout.isTTY)&&(!Xt||Rs("--color")||Mn("COLORTERM")!==null||(Mn("TERM")||"").includes("color")),_i=e=>new Uint8Array(e),Zl=(e,t,n)=>new Uint8Array(e,t,n),tc=e=>new Uint8Array(e),ec=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),sc=e=>{const t=atob(e),n=_i(t.length);for(let s=0;s{const t=Buffer.from(e,"base64");return Zl(t.buffer,t.byteOffset,t.byteLength)},ic=Si?ec:nc,oc=Si?sc:rc,lc=e=>{const t=_i(e.byteLength);return t.set(e),t};class cc{constructor(t,n){this.left=t,this.right=n}}const vt=(e,t)=>new cc(e,t),ac=(e,t)=>e.forEach(n=>t(n.left,n.right)),Jr=e=>e.next()>=.5,Ss=(e,t,n)=>kt(e.next()*(n+1-t)+t),Ei=(e,t,n)=>kt(e.next()*(n+1-t)+t),Zs=(e,t,n)=>Ei(e,t,n),hc=e=>ui(Zs(e,97,122)),uc=(e,t=0,n=20)=>{const s=Zs(e,t,n);let r="";for(let i=0;it[Zs(e,0,t.length-1)],fc=Symbol("0schema");class dc{constructor(){this._rerrs=[]}extend(t,n,s,r=null){this._rerrs.push({path:t,expected:n,has:s,message:r})}toString(){const t=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];t.push(gl(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(` `)}}const Us=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[en]?mi(e,t):De(e)?js(e,n=>Hs(t,s=>Us(n,s))):Bl(e)?an(e,(n,s)=>Us(n,t[s])):!1;class nt{static _dilutes=!1;extends(t){let[n,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Us(n,s)}equals(t){return this.constructor===t.constructor&&ke(this.shape,t.shape)}[fc](){return!0}[en](t){return this.equals(t)}validate(t){return this.check(t)}check(t,n){yt()}get nullable(){return Me(this,ts)}get optional(){return new Ai(this)}cast(t){return Pr(t,this),t}expect(t){return Pr(t,this),t}}class tr extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n=void 0){const s=t?.constructor===this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const W=(e,t=null)=>new tr(e,t);W(tr);class er extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape(t);return!s&&n?.extend(null,"custom prop",t?.constructor.name,"failed to check custom prop"),s}}const G=e=>new er(e);W(er);class Xn extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=this.shape.some(r=>r===t);return!s&&n?.extend(null,this.shape.join(" | "),t.toString()),s}}const Kn=(...e)=>new Xn(e),Ci=W(Xn),gc=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),Di=e=>{if(Ie.check(e))return[gc(e)];if(Ci.check(e))return e.shape.map(t=>t+"");if(vi.check(e))return["[+-]?\\d+.?\\d*"];if(Ni.check(e))return[".*"];if(vn.check(e))return e.shape.map(Di).flat(1);ut()};class pc extends nt{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(Di).map(n=>`(${n.join("|")})`).join("")+"$")}check(t,n){const s=this._r.exec(t)!=null;return!s&&n?.extend(null,this._r.toString(),t.toString(),"String doesn't match string template."),s}}W(pc);const wc=Symbol("optional");class Ai extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=t===void 0||this.shape.check(t);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[wc](){return!0}}const mc=W(Ai);class yc extends nt{check(t,n){return n?.extend(null,"never",typeof t),!1}}W(yc);class Qn extends nt{constructor(t,n=!1){super(),this.shape=t,this._isPartial=n}static _dilutes=!0;get partial(){return new Qn(this.shape,!0)}check(t,n){return t==null?(n?.extend(null,"object","null"),!1):an(this.shape,(s,r)=>{const i=this._isPartial&&!Ks(t,r)||s.check(t[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match"),i})}}const kc=e=>new Qn(e),Sc=W(Qn),bc=G(e=>e!=null&&(e.constructor===Object||e.constructor==null));class Ii extends nt{constructor(t,n){super(),this.shape={keys:t,values:n}}check(t,n){return t!=null&&an(t,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Ti=(e,t)=>new Ii(e,t),_c=W(Ii);class xi extends nt{constructor(t){super(),this.shape=t}check(t,n){return t!=null&&an(this.shape,(s,r)=>{const i=s.check(t[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ec=(...e)=>new xi(e);W(xi);class Li extends nt{constructor(t){super(),this.shape=t.length===1?t[0]:new nr(t)}check(t,n){const s=De(t)&&js(t,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Oi=(...e)=>new Li(e),Cc=W(Li),Dc=G(e=>De(e));class Ri extends nt{constructor(t,n){super(),this.shape=t,this._c=n}check(t,n){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&n?.extend(null,this.shape.name,t?.constructor.name),s}}const Ac=(e,t=null)=>new Ri(e,t);W(Ri);const Ic=Ac(nt);class Tc extends nt{constructor(t){super(),this.len=t.length-1,this.args=Ec(...t.slice(-1)),this.res=t[this.len]}check(t,n){const s=t.constructor===Function&&t.length<=this.len;return!s&&n?.extend(null,"function",typeof t),s}}const xc=W(Tc),Lc=G(e=>typeof e=="function");class Oc extends nt{constructor(t){super(),this.shape=t}check(t,n){const s=js(this.shape,r=>r.check(t,n));return!s&&n?.extend(null,"Intersectinon",typeof t),s}}W(Oc,e=>e.shape.length>0);class nr extends nt{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,n){const s=Hs(this.shape,r=>r.check(t,n));return n?.extend(null,"Union",typeof t),s}}const Me=(...e)=>e.findIndex(t=>vn.check(t))>=0?Me(...e.map(t=>nn(t)).map(t=>vn.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new nr(e),vn=W(nr),Ui=()=>!0,Nn=G(Ui),Rc=W(er,e=>e.shape===Ui),sr=G(e=>typeof e=="bigint"),Uc=G(e=>e===sr),Mi=G(e=>typeof e=="symbol");G(e=>e===Mi);const Se=G(e=>typeof e=="number"),vi=G(e=>e===Se),Ie=G(e=>typeof e=="string"),Ni=G(e=>e===Ie),Zn=G(e=>typeof e=="boolean"),Mc=G(e=>e===Zn),$i=Kn(void 0);W(Xn,e=>e.shape.length===1&&e.shape[0]===void 0);Kn(void 0);const ts=Kn(null),vc=W(Xn,e=>e.shape.length===1&&e.shape[0]===null);W(Uint8Array);W(tr,e=>e.shape===Uint8Array);const Nc=Me(Se,Ie,ts,$i,sr,Zn,Mi);(()=>{const e=Oi(Nn),t=Ti(Ie,Nn),n=Me(Se,Ie,ts,Zn,e,t);return e.shape=n,t.shape.values=n,n})();const nn=e=>{if(Ic.check(e))return e;if(bc.check(e)){const t={};for(const n in e)t[n]=nn(e[n]);return kc(t)}else{if(Dc.check(e))return Me(...e.map(nn));if(Nc.check(e))return Kn(e);if(Lc.check(e))return W(e)}ut()},Pr=Xl?()=>{}:(e,t)=>{const n=new dc;if(!t.check(e,n))throw Ct(`Expected value to be of type ${t.constructor.name}. ${n.toString()}`)};class $c{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:nn(t),h:n}),this}else(t){return this.if(Nn,t)}done(){return(t,n)=>{for(let s=0;snew $c(e),Fi=Fc(Nn).if(vi,(e,t)=>Ss(t,Mr,Rn)).if(Ni,(e,t)=>uc(t)).if(Mc,(e,t)=>Jr(t)).if(Uc,(e,t)=>BigInt(Ss(t,Mr,Rn))).if(vn,(e,t)=>ge(t,bs(t,e.shape))).if(Sc,(e,t)=>{const n={};for(const s in e.shape){let r=e.shape[s];if(mc.check(r)){if(Jr(t))continue;r=r.shape}n[s]=Fi(r,t)}return n}).if(Cc,(e,t)=>{const n=[],s=Ei(t,0,42);for(let r=0;rbs(t,e.shape)).if(vc,(e,t)=>null).if(xc,(e,t)=>{const n=ge(t,e.res);return()=>n}).if(Rc,(e,t)=>ge(t,bs(t,[Se,Ie,ts,$i,sr,Zn,Oi(Se),Ti(Me("a","b","c"),Se)]))).if(_c,(e,t)=>{const n={},s=Ss(t,0,3);for(let r=0;rFi(nn(t),e),Tt=typeof document<"u"?document:{},Bc=e=>Tt.createElement(e),Vc=()=>Tt.createDocumentFragment();G(e=>e.nodeType===Gc);const jc=e=>Tt.createTextNode(e);typeof DOMParser<"u"&&new DOMParser;const Hc=(e,t)=>(ac(t,(n,s)=>{s===!1?e.removeAttribute(n):s===!0?e.setAttribute(n,""):e.setAttribute(n,s)}),e),Jc=e=>{const t=Vc();for(let n=0;n(Bi(e,Jc(t)),e),lu=(e,t=[],n=[])=>Pc(Hc(Bc(e),t),n);G(e=>e.nodeType===Yc);const cu=jc;G(e=>e.nodeType===qc);const Wc=e=>Zo(e,(t,n)=>`${n}:${t};`).join(""),Bi=(e,t)=>e.appendChild(t),Yc=Tt.ELEMENT_NODE,qc=Tt.TEXT_NODE;Tt.CDATA_SECTION_NODE;Tt.COMMENT_NODE;const zc=Tt.DOCUMENT_NODE;Tt.DOCUMENT_TYPE_NODE;const Gc=Tt.DOCUMENT_FRAGMENT_NODE;G(e=>e.nodeType===zc);const Ft=Symbol,Vi=Ft(),ji=Ft(),Xc=Ft(),Kc=Ft(),Qc=Ft(),Hi=Ft(),Zc=Ft(),rr=Ft(),ta=Ft(),ea=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[];let s=0;for(;s0&&n.push(t.join(""));s{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());const t=[],n=[],s=it();let r=[],i=0;for(;i0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(r=n,r.unshift(t.join("")));i{console.log(...Ji(e)),Wi.forEach(t=>t.print(e))},Pi=(...e)=>{console.warn(...Ji(e)),e.unshift(rr),Wi.forEach(t=>t.print(e))},Wi=zt(),Yi=e=>({[Symbol.iterator](){return this},next:e}),ia=(e,t)=>Yi(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),_s=(e,t)=>Yi(()=>{const{done:n,value:s}=e.next();return{done:n,value:n?void 0:t(s)}});class es{constructor(t,n){this.clock=t,this.len=n}}class ve{constructor(){this.clients=new Map}}const Te=(e,t,n)=>t.clients.forEach((s,r)=>{const i=e.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,u=s[c];c{let n=0,s=e.length-1;for(;n<=s;){const r=kt((n+s)/2),i=e[r],o=i.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&oa(n,t.clock)!==null},ir=e=>{e.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n=i.clock?t[s-1]=new es(r.clock,ae(r.len,i.clock+i.len-r.clock)):(s{const t=new ve;for(let n=0;n{if(!t.clients.has(r)){const i=s.slice();for(let o=n+1;o{It(e.clients,t,()=>[]).push(new es(n,s))},la=()=>new ve,ca=e=>{const t=la();return e.clients.forEach((n,s)=>{const r=[];for(let i=0;i0&&t.clients.set(s,r)}),t},Ne=(e,t)=>{_(e.restEncoder,t.clients.size),$t(t.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{e.resetDsCurVal(),_(e.restEncoder,n);const r=s.length;_(e.restEncoder,r);for(let i=0;i{const t=new ve,n=C(e.restDecoder);for(let s=0;s0){const o=It(t.clients,r,()=>[]);for(let l=0;l{const s=new ve,r=C(e.restDecoder);for(let i=0;i0){const i=new oe;return _(i.restEncoder,0),Ne(i,s),i.toUint8Array()}return null},qi=gi;class he extends Js{constructor({guid:t=vl(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=qi(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new oo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=jr(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>jr(u=>{const a=h=>{(h===void 0||h===!0)&&(this.off("sync",a),u())};this.on("sync",a)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&M(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set($t(this.subdocs).map(t=>t.guid))}transact(t,n=null){return M(this,t,n)}get(t,n=z){const s=It(this.share,t,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==z&&r!==n)if(r===z){const i=new n;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,Ee)}getText(t=""){return this.get(t,Oe)}getMap(t=""){return this.get(t,Le)}getXmlElement(t=""){return this.get(t,Re)}getXmlFragment(t=""){return this.get(t,le)}toJSON(){const t={};return this.share.forEach((n,s)=>{t[s]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,$t(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new he({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,M(t.parent.doc,s=>{const r=n.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class zi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return C(this.restDecoder)}readDsLen(){return C(this.restDecoder)}}class Gi extends zi{readLeftID(){return D(C(this.restDecoder),C(this.restDecoder))}readRightID(){return D(C(this.restDecoder),C(this.restDecoder))}readClient(){return C(this.restDecoder)}readInfo(){return Ae(this.restDecoder)}readString(){return Yt(this.restDecoder)}readParentInfo(){return C(this.restDecoder)===1}readTypeRef(){return C(this.restDecoder)}readLen(){return C(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return lc(X(this.restDecoder))}readJSON(){return JSON.parse(Yt(this.restDecoder))}readKey(){return Yt(this.restDecoder)}}class aa{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=C(this.restDecoder),this.dsCurrVal}readDsLen(){const t=C(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class xe extends aa{constructor(t){super(t),this.keys=[],C(t),this.keyClockDecoder=new ks(X(t)),this.clientDecoder=new Ln(X(t)),this.leftClockDecoder=new ks(X(t)),this.rightClockDecoder=new ks(X(t)),this.infoDecoder=new Vr(X(t),Ae),this.stringDecoder=new Rl(X(t)),this.parentInfoDecoder=new Vr(X(t),Ae),this.typeRefDecoder=new Ln(X(t)),this.lenDecoder=new Ln(X(t))}readLeftID(){return new be(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new be(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return tn(this.restDecoder)}readBuf(){return X(this.restDecoder)}readJSON(){return tn(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{s=ae(s,t[0].id.clock);const r=Dt(t,s);_(e.restEncoder,t.length-r),e.writeClient(n),_(e.restEncoder,s);const i=t[r];i.write(e,s-i.id.clock);for(let o=r+1;o{const s=new Map;n.forEach((r,i)=>{J(t,i)>r&&s.set(i,r)}),ns(t).forEach((r,i)=>{n.has(i)||s.set(i,0)}),_(e.restEncoder,s.size),$t(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{ha(e,t.clients.get(r),r,i)})},ua=(e,t)=>{const n=it(),s=C(e.restDecoder);for(let r=0;r{const s=[];let r=$t(n.keys()).sort((d,p)=>d-p);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let d=n.get(r[r.length-1]);for(;d.refs.length===d.i;)if(r.pop(),r.length>0)d=n.get(r[r.length-1]);else return null;return d};let o=i();if(o===null)return null;const l=new oo,c=new Map,u=(d,p)=>{const k=c.get(d);(k==null||k>p)&&c.set(d,p)};let a=o.refs[o.i++];const h=new Map,f=()=>{for(const d of s){const p=d.id.client,k=n.get(p);k?(k.i--,l.clients.set(p,k.refs.slice(k.i)),n.delete(p),k.i=0,k.refs=[]):l.clients.set(p,[d]),r=r.filter(b=>b!==p)}s.length=0};for(;;){if(a.constructor!==wt){const p=It(h,a.id.client,()=>J(t,a.id.client))-a.id.clock;if(p<0)s.push(a),u(a.id.client,a.id.clock-1),f();else{const k=a.getMissing(e,t);if(k!==null){s.push(a);const b=n.get(k)||{refs:[],i:0};if(b.refs.length===b.i)u(k,J(t,k)),f();else{a=b.refs[b.i++];continue}}else(p===0||p0)a=s.pop();else if(o!==null&&o.i0){const d=new oe;return lr(d,l,new Map),_(d.restEncoder,0),{missing:c,update:d.toUint8Array()}}return null},da=(e,t)=>lr(e,t.doc.store,t.beforeState),ga=(e,t,n,s=new xe(e))=>M(t,r=>{r.local=!1;let i=!1;const o=r.doc,l=o.store,c=ua(s,o),u=fa(r,l,c),a=l.pendingStructs;if(a){for(const[f,d]of a.missing)if(dd)&&a.missing.set(f,d)}a.update=Fn([a.update,u.update])}}else l.pendingStructs=u;const h=Wr(s,r,l);if(l.pendingDs){const f=new xe(Kt(l.pendingDs));C(f.restDecoder);const d=Wr(f,r,l);h&&d?l.pendingDs=Fn([h,d]):l.pendingDs=h||d}else l.pendingDs=h;if(i){const f=l.pendingStructs.update;l.pendingStructs=null,Qi(r.doc,f)}},n,!1),Qi=(e,t,n,s=xe)=>{const r=Kt(t);ga(r,e,n,new s(r))},Zi=(e,t,n)=>Qi(e,t,n,Gi),pa=(e,t,n=new Map)=>{lr(e,t.store,n),Ne(e,ca(t.store))},wa=(e,t=new Uint8Array([0]),n=new oe)=>{const s=eo(t);pa(n,e,s);const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Na(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===un)return Ma(r.map((i,o)=>o===0?i:Fa(i)));if(n.constructor===oe)return Fn(r)}return r[0]},to=(e,t)=>wa(e,t,new un),ma=e=>{const t=new Map,n=C(e.restDecoder);for(let s=0;sma(new zi(Kt(e))),no=(e,t)=>(_(e.restEncoder,t.size),$t(t.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{_(e.restEncoder,n),_(e.restEncoder,s)}),e),ya=(e,t)=>no(e,ns(t.store)),ka=(e,t=new Ki)=>(e instanceof Map?no(t,e):ya(t,e),t.toUint8Array()),Sa=e=>ka(e,new Xi);class ba{constructor(){this.l=[]}}const Yr=()=>new ba,qr=(e,t)=>e.l.push(t),zr=(e,t)=>{const n=e.l,s=n.length;e.l=n.filter(r=>t!==r),s===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},so=(e,t,n)=>Qs(e.l,[t,n]);class be{constructor(t,n){this.client=t,this.clock=n}}const ye=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,D=(e,t)=>new be(e,t),ro=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw ut()},$n=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class io{constructor(t,n,s,r=0){this.type=t,this.tname=n,this.item=s,this.assoc=r}}const au=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},_a=e=>new io(e.type==null?null:D(e.type.client,e.type.clock),e.tname??null,e.item==null?null:D(e.item.client,e.item.clock),e.assoc==null?0:e.assoc);class Ea{constructor(t,n,s=0){this.type=t,this.index=n,this.assoc=s}}const Ca=(e,t,n=0)=>new Ea(e,t,n),Cn=(e,t,n)=>{let s=null,r=null;return e._item===null?r=ro(e):s=D(e._item.id.client,e._item.id.clock),new io(s,r,t,n)},hu=(e,t,n=0)=>{let s=e._start;if(n<0){if(t===0)return Cn(e,null,n);t--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>t)return Cn(e,D(s.id.client,s.id.clock+t),n);t-=s.length}if(s.right===null&&n<0)return Cn(e,s.lastId,n);s=s.right}return Cn(e,null,n)},Da=(e,t)=>{const n=_e(e,t),s=t.clock-n.id.clock;return{item:n,diff:s}},Aa=(e,t,n=!0)=>{const s=t.store,r=e.item,i=e.type,o=e.tname,l=e.assoc;let c=null,u=0;if(r!==null){if(J(s,r.client)<=r.clock)return null;const a=n?Fs(s,r):Da(s,r),h=a.item;if(!(h instanceof v))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:a.diff+(l>=0?0:1);let f=h.left;for(;f!==null;)!f.deleted&&f.countable&&(u+=f.length),f=f.left}}else{if(o!==null)c=t.get(o);else if(i!==null){if(J(s,i.client)<=i.clock)return null;const{item:a}=n?Fs(s,i):{item:_e(s,i)};if(a instanceof v&&a.content instanceof xt)c=a.content.type;else return null}else throw ut();l>=0?u=c._length:u=0}return Ca(c,u,e.assoc)},uu=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&ye(e.item,t.item)&&ye(e.type,t.type)&&e.assoc===t.assoc,we=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!hn(t.ds,e.id),vs=(e,t)=>{const n=It(e.meta,vs,zt),s=e.doc.store;n.has(t)||(t.sv.forEach((r,i)=>{r{}),n.add(t))};class oo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ns=e=>{const t=new Map;return e.clients.forEach((n,s)=>{const r=n[n.length-1];t.set(s,r.id.clock+r.length)}),t},J=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},lo=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==t.id.clock)throw ut()}n.push(t)},Dt=(e,t)=>{let n=0,s=e.length-1,r=e[s],i=r.id.clock;if(i===t)return s;let o=kt(t/(i+r.length-1)*s);for(;n<=s;){if(r=e[o],i=r.id.clock,i<=t){if(t{const n=e.clients.get(t.client);return n[Dt(n,t.clock)]},_e=Ia,Ns=(e,t,n)=>{const s=Dt(t,n),r=t[s];return r.id.clock{const n=e.doc.store.clients.get(t.client);return n[Ns(e,n,t.clock)]},Gr=(e,t,n)=>{const s=t.clients.get(n.client),r=Dt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,Pn(e,i,n.clock-i.id.clock+1)),i},Ta=(e,t,n)=>{const s=e.clients.get(t.id.client);s[Dt(s,t.id.clock)]=n},co=(e,t,n,s,r)=>{if(s===0)return;const i=n+s;let o=Ns(e,t,n),l;do l=t[o++],it.deleteSet.clients.size===0&&!tl(t.afterState,(n,s)=>t.beforeState.get(s)!==n)?!1:(ir(t.deleteSet),da(e,t),Ne(e,t.deleteSet),!0),Kr=(e,t,n)=>{const s=t._item;(s===null||s.id.clock<(e.beforeState.get(s.id.client)||0)&&!s.deleted)&&It(e.changed,t,zt).add(n)},On=(e,t)=>{let n=e[t],s=e[t-1],r=t;for(;r>0;n=s,s=e[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof v&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=t-r;return i&&e.splice(t+1-i,i),i},La=(e,t,n)=>{for(const[s,r]of e.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const l=r[o],c=l.clock+l.len;for(let u=Dt(i,l.clock),a=i[u];u{e.clients.forEach((n,s)=>{const r=t.clients.get(s);for(let i=n.length-1;i>=0;i--){const o=n[i],l=Ps(r.length-1,1+Dt(r,o.clock+o.len-1));for(let c=l,u=r[c];c>0&&u.id.clock>=o.clock;u=r[c])c-=1+On(r,c)}})},ao=(e,t)=>{if(tl.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(a=>a.target._item===null||!a.target._item.deleted),c.forEach(a=>{a.currentTarget=u,a._path=null}),c.sort((a,h)=>a.path.length-h.path.length),l.push(()=>{so(u._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&Qa(n)})}),Qs(l,[])}finally{s.gc&&La(i,r,s.gcFilter),Oa(i,r),n.afterState.forEach((a,h)=>{const f=n.beforeState.get(h)||0;if(f!==a){const d=r.clients.get(h),p=ae(Dt(d,f),1);for(let k=d.length-1;k>=p;)k-=1+On(d,k)}});for(let a=o.length-1;a>=0;a--){const{client:h,clock:f}=o[a].id,d=r.clients.get(h),p=Dt(d,f);p+11||p>0&&On(d,p)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ra(rr,Vi,"[yjs] ",ji,Hi,"Changed the client-id because another client seems to be using it."),s.clientID=qi()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const a=new un;Xr(a,n)&&s.emit("update",[a.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const a=new oe;Xr(a,n)&&s.emit("updateV2",[a.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:u}=n;(l.size>0||u.size>0||c.size>0)&&(l.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),u.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:c,added:l,removed:u},s,n]),u.forEach(a=>a.destroy())),e.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,e])):ao(e,t+1)}}},M=(e,t,n=null,s=!0)=>{const r=e._transactionCleanups;let i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new xa(e,n,s),r.push(e._transaction),r.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const l=e._transaction===r[0];e._transaction=null,l&&ao(r,0)}}return o};class Ra{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Qr=(e,t,n)=>{Te(e,n.deletions,s=>{s instanceof v&&t.scope.some(r=>r===e.doc||$n(r,s))&&pr(s,!1)})},Zr=(e,t,n)=>{let s=null;const r=e.doc,i=e.scope;M(r,l=>{for(;t.length>0&&e.currStackItem===null;){const c=r.store,u=t.pop(),a=new Set,h=[];let f=!1;Te(l,u.insertions,d=>{if(d instanceof v){if(d.redone!==null){let{item:p,diff:k}=Fs(c,d.id);k>0&&(p=rt(l,D(p.id.client,p.id.clock+k))),d=p}!d.deleted&&i.some(p=>p===l.doc||$n(p,d))&&h.push(d)}}),Te(l,u.deletions,d=>{d instanceof v&&i.some(p=>p===l.doc||$n(p,d))&&!hn(u.insertions,d.id)&&a.add(d)}),a.forEach(d=>{f=To(l,d,a,u.insertions,e.ignoreRemoteMapChanges,e)!==null||f});for(let d=h.length-1;d>=0;d--){const p=h[d];e.deleteFilter(p)&&(p.delete(l),f=!0)}e.currStackItem=f?u:null}l.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=l},e);const o=e.currStackItem;if(o!=null){const l=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:e},e]),e.currStackItem=null}return o};class fu extends Js{constructor(t,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=De(t)?t[0].doc:t instanceof he?t:t.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(t),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(b=>c.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,a=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():a||this.clear(!1,!0);const f=new ve;c.afterState.forEach((b,w)=>{const S=c.beforeState.get(w)||0,A=b-S;A>0&&sn(f,w,S,A)});const d=Gt();let p=!1;if(this.lastChange>0&&d-this.lastChange0&&!u&&!a){const b=h[h.length-1];b.deletions=Ms([b.deletions,c.deleteSet]),b.insertions=Ms([b.insertions,f])}else h.push(new Ra(c.deleteSet,f)),p=!0;!u&&!a&&(this.lastChange=d),Te(c,c.deleteSet,b=>{b instanceof v&&this.scope.some(w=>w===c.doc||$n(w,b))&&pr(b,!0)});const k=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];p?this.emit("stack-item-added",k):this.emit("stack-item-updated",k)},this.destroy=this.destroy.bind(this),this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",this.destroy)}addToScope(t){const n=new Set(this.scope);t=De(t)?t:[t],t.forEach(s=>{n.has(s)||(n.add(s),(s instanceof z?s.doc!==this.doc:s!==this.doc)&&Pi("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(t){this.trackedOrigins.add(t)}removeTrackedOrigin(t){this.trackedOrigins.delete(t)}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{t&&(this.undoStack.forEach(r=>Qr(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Qr(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=Zr(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=Zr(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),this.doc.off("destroy",this.destroy),super.destroy()}}function*Ua(e){const t=C(e.restDecoder);for(let n=0;nFn(e,Gi,un),va=(e,t)=>{if(e.constructor===pt){const{client:n,clock:s}=e.id;return new pt(D(n,s+t),e.length-t)}else if(e.constructor===wt){const{client:n,clock:s}=e.id;return new wt(D(n,s+t),e.length-t)}else{const n=e,{client:s,clock:r}=n.id;return new v(D(s,r+t),null,D(s,r+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Fn=(e,t=xe,n=oe)=>{if(e.length===1)return e[0];const s=e.map(a=>new t(Kt(a)));let r=s.map(a=>new cr(a,!0)),i=null;const o=new n,l=new ar(o);for(;r=r.filter(f=>f.curr!==null),r.sort((f,d)=>{if(f.curr.id.client===d.curr.id.client){const p=f.curr.id.clock-d.curr.id.clock;return p===0?f.curr.constructor===d.curr.constructor?0:f.curr.constructor===wt?1:-1:p}else return d.curr.id.client-f.curr.id.client}),r.length!==0;){const a=r[0],h=a.curr.id.client;if(i!==null){let f=a.curr,d=!1;for(;f!==null&&f.id.clock+f.length<=i.struct.id.clock+i.struct.length&&f.id.client>=i.struct.id.client;)f=a.next(),d=!0;if(f===null||f.id.client!==h||d&&f.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===wt?i.struct.length-=p:f=va(f,p)),i.struct.mergeWith(f)||(Pt(l,i.struct,i.offset),i={struct:f,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let f=a.curr;f!==null&&f.id.client===h&&f.id.clock===i.struct.id.clock+i.struct.length&&f.constructor!==wt;f=a.next())Pt(l,i.struct,i.offset),i={struct:f,offset:0}}i!==null&&(Pt(l,i.struct,i.offset),i=null),hr(l);const c=s.map(a=>or(a)),u=Ms(c);return Ne(o,u),o.toUint8Array()},Na=(e,t,n=xe,s=oe)=>{const r=eo(t),i=new s,o=new ar(i),l=new n(Kt(e)),c=new cr(l,!1);for(;c.curr;){const a=c.curr,h=a.id.client,f=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(a.id.clock+a.length>f)for(Pt(o,a,ae(f-a.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Pt(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=f;)c.next()}hr(o);const u=or(l);return Ne(i,u),i.toUint8Array()},ho=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=K(),e.written=0)},Pt=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ho(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),_(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},hr=e=>{ho(e);const t=e.encoder.restEncoder;_(t,e.clientStructs.length);for(let n=0;n{const r=new n(Kt(e)),i=new cr(r,!1),o=new s,l=new ar(o);for(let u=i.curr;u!==null;u=i.next())Pt(l,t(u),0);hr(l);const c=or(r);return Ne(o,c),o.toUint8Array()},Fa=e=>$a(e,ql,xe,un),ti="You must not compute changes after the event-handler fired.";class ss{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Ba(this.currentTarget,this.target))}deletes(t){return hn(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=ps(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=ps(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=ps(i.content.getContent());else return;t.set(r,{action:o,oldValue:l})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(ti);const n=this.target,s=zt(),r=zt(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=u.length,r.add(u)):this.adds(u)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(u.content.getContent()),s.add(u)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=u.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}}const Ba=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}t=t._item.parent}return n},Q=()=>{Pi("Invalid access: Add Yjs type to a document before reading data.")},uo=80;let ur=0;class Va{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=ur++}}const ja=e=>{e.timestamp=ur++},fo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ur++},Ha=(e,t,n)=>{if(e.length>=uo){const s=e.reduce((r,i)=>r.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>Tn(t-i.index)t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Tn(n.index-r){for(let s=e.length-1;s>=0;s--){const r=e[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){e.splice(s,1);continue}r.p=i,i.marker=!0}(t0&&t===r.index)&&(r.index=ae(t,r.index+n))}},is=(e,t,n)=>{const s=e,r=t.changedParentTypes;for(;It(r,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;so(s._eH,n,t)};class z{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){qr(this._eH,t)}observeDeep(t){qr(this._dEH,t)}unobserve(t){zr(this._eH,t)}unobserveDeep(t){zr(this._dEH,t)}toJSON(){}}const go=(e,t,n)=>{e.doc??Q(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let s=n-t;const r=[];let i=e._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l0;l++)r.push(o[l]),s--;t=0}}i=i.right}return r},po=e=>{e.doc??Q();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r{let n=0,s=e._start;for(e.doc??Q();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i{const n=[];return on(e,(s,r)=>{n.push(t(s,r,e))}),n},Ja=e=>{let t=e._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),s=0,t=t.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},mo=(e,t)=>{e.doc??Q();const n=rs(e,t);let s=e._start;for(n!==null&&(s=n.p,t-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t{let r=n;const i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right;let u=[];const a=()=>{u.length>0&&(r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new ce(u)),r.integrate(e,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(a(),h.constructor){case Uint8Array:case ArrayBuffer:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new fn(new Uint8Array(h))),r.integrate(e,0);break;case he:r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new dn(h)),r.integrate(e,0);break;default:if(h instanceof z)r=new v(D(o,J(l,o)),r,r&&r.lastId,c,c&&c.id,t,null,new xt(h)),r.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},yo=()=>Ct("Length exceeded!"),ko=(e,t,n,s)=>{if(n>t._length)throw yo();if(n===0)return t._searchMarker&&rn(t._searchMarker,n,s.length),Bn(e,t,null,s);const r=n,i=rs(t,n);let o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Bn(e,t,r,n)},So=(e,t,n,s)=>{if(s===0)return;const r=n,i=s,o=rs(t,n);let l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(s0)throw yo();t._searchMarker&&rn(t._searchMarker,r,-i+s)},Vn=(e,t,n)=>{const s=t._map.get(n);s!==void 0&&s.delete(e)},fr=(e,t,n,s)=>{const r=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(s==null)l=new ce([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ce([s]);break;case Uint8Array:l=new fn(s);break;case he:l=new dn(s);break;default:if(s instanceof z)l=new xt(s);else throw new Error("Unexpected content type")}new v(D(o,J(i.store,o)),r,r&&r.lastId,null,null,t,n,l).integrate(e,0)},dr=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bo=e=>{const t={};return e.doc??Q(),e._map.forEach((n,s)=>{n.deleted||(t[s]=n.content.getContent()[n.length-1])}),t},_o=(e,t)=>{e.doc??Q();const n=e._map.get(t);return n!==void 0&&!n.deleted},Wa=(e,t)=>{const n={};return e._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&we(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dn=e=>(e.doc??Q(),ia(e._map.entries(),t=>!t[1].deleted));class Ya extends ss{}class Ee extends z{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new Ee;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ee}clone(){const t=new Ee;return t.insert(0,this.toArray().map(n=>n instanceof z?n.clone():n)),t}get length(){return this.doc??Q(),this._length}_callObserver(t,n){super._callObserver(t,n),is(this,t,new Ya(this,t))}insert(t,n){this.doc!==null?M(this.doc,s=>{ko(s,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?M(this.doc,n=>{Pa(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?M(this.doc,s=>{So(s,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return mo(this,t)}toArray(){return po(this)}slice(t=0,n=this.length){return go(this,t,n)}toJSON(){return this.map(t=>t instanceof z?t.toJSON():t)}map(t){return wo(this,t)}forEach(t){on(this,t)}[Symbol.iterator](){return Ja(this)}_write(t){t.writeTypeRef(mh)}}const qa=e=>new Ee;class za extends ss{constructor(t,n,s){super(t,n),this.keysChanged=s}}class Le extends z{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Le}clone(){const t=new Le;return this.forEach((n,s)=>{t.set(s,n instanceof z?n.clone():n)}),t}_callObserver(t,n){is(this,t,new za(this,t,n))}toJSON(){this.doc??Q();const t={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];t[s]=r instanceof z?r.toJSON():r}}),t}get size(){return[...Dn(this)].length}keys(){return _s(Dn(this),t=>t[0])}values(){return _s(Dn(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return _s(Dn(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Q(),this._map.forEach((n,s)=>{n.deleted||t(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?M(this.doc,n=>{Vn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?M(this.doc,s=>{fr(s,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return dr(this,t)}has(t){return _o(this,t)}clear(){this.doc!==null?M(this.doc,t=>{this.forEach(function(n,s,r){Vn(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(yh)}}const Ga=e=>new Le,Wt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Wl(e,t);class $s{constructor(t,n,s,r){this.left=t,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===Y?this.right.deleted||$e(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ei=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Y?t.right.deleted||$e(t.currentAttributes,t.right.content):t.right.deleted||(n{const r=new Map,i=s?rs(t,n):null;if(i){const o=new $s(i.p.left,i.p,i.index,r);return ei(e,o,n-i.index)}else{const o=new $s(null,t._start,0,r);return ei(e,o,n)}},Eo=(e,t,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Y&&Wt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=e.doc,i=r.clientID;s.forEach((o,l)=>{const c=n.left,u=n.right,a=new v(D(i,J(r.store,i)),c,c&&c.lastId,u,u&&u.id,t,null,new Y(l,o));a.integrate(e,0),n.right=a,n.forward()})},$e=(e,t)=>{const{key:n,value:s}=t;s===null?e.delete(n):e.set(n,s)},Co=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Y&&Wt(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},Do=(e,t,n,s)=>{const r=e.doc,i=r.clientID,o=new Map;for(const l in s){const c=s[l],u=n.currentAttributes.get(l)??null;if(!Wt(u,c)){o.set(l,u);const{left:a,right:h}=n;n.right=new v(D(i,J(r.store,i)),a,a&&a.lastId,h,h&&h.id,t,null,new Y(l,c)),n.right.integrate(e,0),n.forward()}}return o},Es=(e,t,n,s,r)=>{n.currentAttributes.forEach((f,d)=>{r[d]===void 0&&(r[d]=null)});const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r),c=s.constructor===String?new At(s):s instanceof z?new xt(s):new ue(s);let{left:u,right:a,index:h}=n;t._searchMarker&&rn(t._searchMarker,n.index,c.getLength()),a=new v(D(o,J(i.store,o)),u,u&&u.lastId,a,a&&a.id,t,null,c),a.integrate(e,0),n.right=a,n.index=h,n.forward(),Eo(e,t,n,l)},ni=(e,t,n,s,r)=>{const i=e.doc,o=i.clientID;Co(n,r);const l=Do(e,t,n,r);t:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Y));){if(!n.right.deleted)switch(n.right.content.constructor){case Y:{const{key:c,value:u}=n.right.content,a=r[c];if(a!==void 0){if(Wt(a,u))l.delete(c);else{if(s===0)break t;l.set(c,u)}n.right.delete(e)}else n.currentAttributes.set(c,u);break}default:s0){let c="";for(;s>0;s--)c+=` `;n.right=new v(D(o,J(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new At(c)),n.right.integrate(e,0),n.forward()}Eo(e,t,n,l)},Ao=(e,t,n,s,r)=>{let i=t;const o=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Y){const u=i.content;o.set(u.key,u)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const u=t.content;if(u.constructor===Y){const{key:a,value:h}=u,f=s.get(a)??null;(o.get(a)!==u||f===h)&&(t.delete(e),l++,!c&&(r.get(a)??null)===h&&f!==h&&(f===null?r.delete(a):r.set(a,f))),!c&&!t.deleted&&$e(r,u)}}t=t.right}return l},Xa=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Y){const s=t.content.key;n.has(s)?t.delete(e):n.add(s)}t=t.left}},Ka=e=>{let t=0;return M(e.doc,n=>{let s=e._start,r=e._start,i=it();const o=Ts(i);for(;r;)r.deleted===!1&&(r.content.constructor===Y?$e(o,r.content):(t+=Ao(n,s,r,i,o),i=Ts(o),s=r)),r=r.right}),t},Qa=e=>{const t=new Set,n=e.doc;for(const[s,r]of e.afterState.entries()){const i=e.beforeState.get(s)||0;r!==i&&co(e,n.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===Y&&o.constructor!==pt&&t.add(o.parent)})}M(n,s=>{Te(e,e.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===Y?t.add(i):Xa(s,r)});for(const r of t)Ka(r)})},si=(e,t,n)=>{const s=n,r=Ts(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case xt:case ue:case At:n{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];M(t,s=>{const r=new Map,i=new Map;let o=this.target._start,l=null;const c={};let u="",a=0,h=0;const f=()=>{if(l!==null){let d=null;switch(l){case"delete":h>0&&(d={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(d={insert:u},r.size>0&&(d.attributes={},r.forEach((p,k)=>{p!==null&&(d.attributes[k]=p)}))),u="";break;case"retain":a>0&&(d={retain:a},Pl(c)||(d.attributes=Vl({},c))),a=0;break}d&&n.push(d),l=null}};for(;o!==null;){switch(o.content.constructor){case xt:case ue:this.adds(o)?this.deletes(o)||(f(),l="insert",u=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=1);break;case At:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),u+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),h+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),a+=o.length);break;case Y:{const{key:d,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(d)??null;Wt(k,p)?p!==null&&o.delete(s):(l==="retain"&&f(),Wt(p,i.get(d)??null)?delete c[d]:c[d]=p)}}else if(this.deletes(o)){i.set(d,p);const k=r.get(d)??null;Wt(k,p)||(l==="retain"&&f(),c[d]=k)}else if(!o.deleted){i.set(d,p);const k=c[d];k!==void 0&&(Wt(k,p)?k!==null&&o.delete(s):(l==="retain"&&f(),p===null?delete c[d]:c[d]=p))}o.deleted||(l==="insert"&&f(),$e(r,o.content));break}}o=o.right}for(f();n.length>0;){const d=n[n.length-1];if(d.retain!==void 0&&d.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Oe extends z{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Q(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Oe}clone(){const t=new Oe;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const s=new Za(this,t,n);is(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Q();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?M(this.doc,s=>{const r=new $s(null,this._start,0,new Map);for(let i=0;i(function(){var d=document.documentElement,p,t="dark";try{p=localStorage.getItem("bdrive-theme")}catch(e){}try{t=p==="light"||p==="dark"?p:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch(e){}d.dataset.theme=t;d.style.colorScheme=t})() BearDrive - + diff --git a/internal/webapp/static/inline-edit.js b/internal/webapp/static/inline-edit.js index 413156e9..6a66492e 100644 --- a/internal/webapp/static/inline-edit.js +++ b/internal/webapp/static/inline-edit.js @@ -1,21 +1,21 @@ -(function(){"use strict";var Dr=Object.defineProperty,ul=(n,e)=>{let t={};for(var r in n)Dr(t,r,{get:n[r],enumerable:!0});return Dr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Ar(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Rr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Vt(t+1,s):Vt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class ht extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Br(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Pr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Pr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Pr(s.content,e-i-1,t-i-1)))}function Br(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Br(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function dl(n,e,t){if(t.openStart>n.depth)throw new ht("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ht("Inconsistent open depths");return zr(n,e,t,0)}function zr(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function pt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&Tn(n,e,i+1),o=r.depth>i&&Tn(t,r,i+1),l=[];return pt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Fr(s,o),Be(ze(s,Lr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,Wt(n,e,i+1)),l),pt(e,t,i,l),o&&Be(ze(o,Wt(t,r,i+1)),l)),pt(r,null,i,l),new b(l)}function Wt(n,e,t){let r=[];if(pt(null,n,t,r),n.depth>t){let i=Tn(n,e,t+1);Be(ze(i,Wt(n,e,t+1)),r)}return pt(e,null,t,r),new b(r)}function hl(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class mt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new jt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new mt(t,r,s)}static resolveCached(e,t){let r=Vr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),$r(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class Jt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):$r(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Jt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Jt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function $r(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new yl(e,t);if(r.next==null)return Le.empty;let i=Wr(r);r.next&&r.err("Unexpected trailing text");let s=wl(Cl(i));return Tl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}Le.empty=new Le(!0);class yl{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Wr(n){let e=[];do e.push(bl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function bl(n){let e=[];do e.push(kl(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function kl(n){let e=Ml(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=xl(n,e);else break;return e}function jr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function xl(n,e){let t=jr(n),r=t;return n.eat(",")&&(n.next!="}"?r=jr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Sl(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Ml(n){if(n.eat("(")){let e=Wr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Sl(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Cl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Kr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new ol(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Ol(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Nl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ol(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Ht{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Ur(e,i.attrs),this.excluded=null;let s=qr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Kr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Ht(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Yr{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Gr.compile(this.spec.nodes,this),this.marks=Ht.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Xr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Xr(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Gr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Jt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Xr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function El(n){return n.tag!=null}function Dl(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(El(i))this.tags.push(i);else if(Dl(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new ti(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new ti(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=ni(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=ni(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const Qr={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Al={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Zr={ol:!0,ul:!0},gt=1,On=2,yt=4;function ei(n,e,t){return e!=null?(e?gt:0)|(e==="full"?On:0):n&&n.whitespace=="pre"?gt|On:t&~yt}class qt{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&yt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options>)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Qr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ti{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ei(null,t.preserveWhitespace,0)|(r?yt:0);i?s=new qt(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new qt(null,null,E.none,!0,null,o):s=new qt(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&On?"full":this.localPreserveWS||(i.options>)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):ri(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new qt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=gt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Il(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Zr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function vl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function ni(n){let e={};for(let t in n)e[t]=n[t];return e}function ri(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&_t(Kt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:_t(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ii(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ii(e.marks)}}function ii(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Kt(n){return n.document||window.document}const si=new WeakMap;function Rl(n){let e=si.get(n);return e===void 0&&si.set(n,e=Pl(n)),e}function Pl(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=_t(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const oi=65535,li=Math.pow(2,16);function Bl(n,e){return n+e*li}function ai(n){return n&oi}function zl(n){return(n-(n&oi))/li}const ci=1,fi=2,Ut=4,ui=8;class Nn{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ui)>0}get deletedBefore(){return(this.delInfo&(ci|Ut))>0}get deletedAfter(){return(this.delInfo&(fi|Ut))>0}get deletedAcross(){return(this.delInfo&Ut)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=ai(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Bl(l/3,e-a),m=e==a?fi:e==u?ci:Ut;return(t<0?e!=a:e!=u)&&(m|=ui),new Nn(h,m,p)}i+=f-c}return r?e+i:new Nn(e+i,0,null)}touches(e,t){let r=0,i=ai(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new bt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Se(t.pos,r.pos,this.mark)}merge(e){return e instanceof Se&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Se(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Se(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Se);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(Dn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Se(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Me extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function An(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Fl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Ll(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Ht){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function In(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Vl(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function tt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Hl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&ql(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&mi(n,o,l,s),In(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&pi(n,o,l,s),!1}})}function pi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function mi(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function ql(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Kl(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function _l(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new v(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return gi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Ul(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&gi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function Gl(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);mi(n,f.node(),f.before(),l)}o.inlineContent&&In(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new v(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);pi(n,f.node(),f.before(),n.steps.length)}return n}function Yl(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Yt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return yi(i,s,r)?new v(e,t,r):new Ql(i,s,r).fit()}function yi(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class Ql{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new v(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=bi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return xi(e,-1)<=t?!1:(this.unplaced.size>1&&xi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=bi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(kt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(kt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(ki(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=xt(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=vn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=xt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=xt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=xt(this.placed,this.frontier.length,t))}}function kt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(kt(n.firstChild.content,e-1,t)))}function xt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(xt(n.lastChild.content,e-1,t)))}function bi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,ki(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function vn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Zl(t,s.content,o)?l:null}function Zl(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=ea(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Si(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function na(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Yl(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function ra(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Mi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Mi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class nt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new nt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new nt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new nt(t.pos,t.attr,t.value)}}W.jsonID("attr",nt);class St extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new St(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new St(t.attr,t.value)}}W.jsonID("docAttr",St);let rt=class extends Error{};rt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},rt.prototype=Object.create(Error.prototype),rt.prototype.constructor=rt,rt.prototype.name="TransformError";class Ci{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new bt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Yt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return ta(this,e,t,r),this}replaceRangeWith(e,t,r){return na(this,e,t,r),this}deleteRange(e,t){return ra(this,e,t),this}lift(e,t){return $l(this,e,t),this}join(e,t=1){return Gl(this,e,t),this}wrap(e,t){return Jl(this,e,t),this}setBlockType(e,t=e,r,i=null){return Hl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Kl(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new nt(e,t,r)),this}setDocAttribute(e,t){return this.step(new St(e,t)),this}addNodeMark(e,t){return this.step(new Me(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return _l(this,e,t,r),this}addMark(e,t,r){return Fl(this,e,t,r),this}removeMark(e,t,r){return Ll(this,e,t,r),this}clearIncompatible(e,t,r){return In(this,e,t,r),this}}const Rn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ia(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?it(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):it(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new U(e.node(0))}static atStart(e){return it(e,e,0,0,1)||new U(e)}static atEnd(e){return it(e,e,e.content.size,e.childCount,-1)||new U(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Rn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Rn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Rn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ia{constructor(e,t){this.$from=e,this.$to=t}}let wi=!1;function Ti(n){!wi&&!n.parent.inlineContent&&(wi=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Ti(e),Ti(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Xt(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=it(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Oi(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ni=1,Qt=2,Ei=4;class oa extends Ci{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Qt,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Qt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Qt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Ei,this}get scrolledIntoView(){return(this.updated&Ei)>0}}function Di(n,e){return!e||!n?n:n.bind(e)}class Mt{constructor(e,t,r){this.name=e,this.init=Di(t.init,r),this.apply=Di(t.apply,r)}}const la=[new Mt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Mt("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Mt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Mt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Bn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=la.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Mt(r.key,r.spec.state,r))})}}class st{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Bn(e.schema,e.plugins),s=new st(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ai(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ai(i,e,{})),t[r]=i}return t}class ae{constructor(e){this.spec=e,this.props={},e.props&&Ai(e.props,this,this.props),this.key=e.key?e.key.key:Ii("plugin")}getState(e){return e[this.key]}}const zn=Object.create(null);function Ii(n){return n in zn?n+"$"+ ++zn[n]:(zn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Ii(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const vi=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Ri(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Pi=(n,e,t)=>{let r=Ri(n,t);if(!r)return!1;let i=Fn(r);if(!i){let o=r.blockRange(),l=o&&tt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Hi(n,i,e,-1))return!0;if(r.parent.content.size==0&&(ot(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Yt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},aa=(n,e,t)=>{let r=Ri(n,t);if(!r)return!1;let i=Fn(r);return i?Bi(n,i,e):!1},ca=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);return i?Bi(n,i,e):!1};function Bi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Yt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof v&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function ot(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const zi=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Fn(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Fn(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Fi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);if(!i)return!1;let s=i.nodeAfter;if(Hi(n,i,e,1))return!0;if(r.parent.content.size==0&&(ot(s,"start")||x.isSelectable(s))){let o=Yt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Gt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ua=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Gt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},da=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&tt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},$i=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function Vn(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Vn(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},ji=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof U||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Vn(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&tt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function ha(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof U)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=Vn(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const pa=ha(),ma=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},ga=(n,e)=>(e&&e(n.tr.setSelection(new U(n.doc))),!0);function ya(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Hi(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&ya(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&tt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&&ot(s,"start",!0)&&ot(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function qi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Ki=qi(-1),_i=qi(1);function ba(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&di(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ui(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Gi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!ka(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new jt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Ta(e,t,n,s):Oa(e,t,s):!0:!1}}function Ta(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Na(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},lt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let jn=null;const ge=function(n,e,t){let r=jn||(jn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Ea=function(){jn=null},je=function(n,e,t,r){return t&&(Qi(n,e,t,r,-1)||Qi(n,e,t,r,1))},Da=/^(img|br|input|textarea|hr)$/i;function Qi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||Ct(n)||Da.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Aa(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!Ct(n))e=L(n),n=n.parentNode;else return null}}function Ia(n,e){for(;;){if(n.nodeType==3&&e2),ee=at||(ce?/Mac/.test(ce.platform):!1),ns=ce?/Win/.test(ce.platform):!1,ye=/Android \d/.test(Ce),wt=!!Zi&&"webkitFontSmoothing"in Zi.documentElement.style,Ba=wt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function za(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Fa(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function rs(n,e,t){if(!_n(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=lt(o);continue}let l=o,a=l==s.body,c=a?za(s):Fa(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:lt(o)}}function La(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:is(n.dom)}}function is(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=lt(r));return e}function Va({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;ss(t,r==0?0:r-e)}function ss(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Wa(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:ls(t,i)}function Wa(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Kn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function ja(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Ha(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function as(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;wt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Ha(n,r,i,e))}l==null&&(l=Ja(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function _n(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Tt(Te(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Un(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Tt(Te(c,1),!1)}if(s==null&&i=0)}function Tt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Un(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function fs(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function _a(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return fs(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=cs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const Ua=/[\u0590-\u08ac]/;function Ga(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ua.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:fs(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let us=null,ds=null,hs=!1;function Ya(n,e,t){return us==e&&ds==t?hs:(us=e,ds=t,hs=t=="up"||t=="down"?_a(n,e,t):Ga(n,e,t))}const te=0,ps=1,He=2,se=3;class Ot{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof ys){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ms&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?He:ps,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?He:se}r=o}this.dirty=He}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?He:ps;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Xa extends Ot{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Oe extends Ot{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Oe(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Yn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=xs(f,r,t),c?a=new Qa(e,t,r,i,f,u||null,d,c):t.isText?new en(e,t,r,i,f,d):new Ne(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&tn(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new ec(this,o&&o.node,e);rc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==He)&&(o&&this.protectLocalComposition(e,o),bs(this.contentDOM,this.children,e),at&&ic(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=sc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Xa(this,s,t,i);e.input.compositionNodes.push(o),this.children=Yn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(tn(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ks(this.dom,this.nodeDOM,Gn(this.outerDeco,this.node,t),Gn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function gs(n,e,t,r,i){xs(r,e,n);let s=new Ne(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class en extends Ne{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new en(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class ys extends Ot{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Qa extends Ne{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function bs(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Oe.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Oe)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function nc(n,e){return n.type.side-e.type.side}function rc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function ic(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function sc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Yn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Xn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Zt(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&va(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Ms(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function lc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&G&&we<=11&&(t.disabled=!0,t.disabled=!1)}function Os(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ns(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ns(n)}function Ns(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Zn(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function Es(n){return n.editable&&!n.hasFocus()?!1:Ds(n)}function Ds(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function ac(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function er(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function Ee(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function As(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ee(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=er(n.state,e);return i&&i instanceof x?Ee(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Ee(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):wt?Ee(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return Ee(n,new S(e>0?r.$to:r.$from));{let i=er(n.state,e);return i?Ee(n,i):!1}}}function nn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Et(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ft(n,e){return e<0?cc(n):fc(n)}function cc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Et(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Is(t))break;{let l=t.previousSibling;for(;l&&Et(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=nn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?tr(n,t,r):i&&tr(n,i,s)}function fc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=nn(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function vs(n,e){let t=n.state.doc.resolve(e);if(!(V||ns)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Rs(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=er(n.state,e);if(o&&o instanceof x)return Ee(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof U?T.near(o,e):T.findFrom(o,e);return l?Ee(n,l):!1}return!1}function Ps(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Bs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function hc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Bs(n,r,"true"),setTimeout(()=>Bs(n,r,"false"),20)}return!1}function pc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function mc(n,e){let t=e.keyCode,r=pc(e);if(t==8||ee&&t==72&&r=="c")return Ps(n,-1)||ft(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Ps(n,1)||ft(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?vs(n,n.state.selection.from)=="ltr"?-1:1:-1;return As(n,i,r)||ft(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?vs(n,n.state.selection.from)=="ltr"?1:-1:1;return As(n,i,r)||ft(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Rs(n,-1,r)||ft(n,-1);if(t==40||ee&&t==78&&r=="c")return hc(n)||Rs(n,1,r)||ft(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function nr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=js(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=Ws[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` +(function(){"use strict";var Rr=Object.defineProperty,xl=(n,e)=>{let t={};for(var r in n)Rr(t,r,{get:n[r],enumerable:!0});return Rr(t,Symbol.toStringTag,{value:"Module"}),t};function F(n){this.content=n}F.prototype={constructor:F,find:function(n){for(var e=0;e>1}},F.from=function(n){if(n instanceof F)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new F(e)};function Pr(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&d>0&&c[u-1]==f[d-1];)u--,d--,t--,r--;return u&&d&&u=56320&&n<57344}function Fr(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?jt(t+1,s):jt(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};E.none=[];class pt extends Error{}class k{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Vr(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new k(r,this.openStart,this.openEnd)}removeBetween(e,t){return new k(Lr(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return k.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new k(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new k(e,r,i)}}k.empty=new k(b.empty,0,0);function Lr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Lr(s.content,e-i-1,t-i-1)))}function Vr(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Vr(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function Sl(n,e,t){if(t.openStart>n.depth)throw new pt("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new pt("Inconsistent open depths");return $r(n,e,t,0)}function $r(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function mt(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Be(n.nodeAfter,r),s++));for(let l=s;li&&On(n,e,i+1),o=r.depth>i&&On(t,r,i+1),l=[];return mt(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Wr(s,o),Be(ze(s,jr(n,e,t,r,i+1)),l)):(s&&Be(ze(s,Ht(n,e,i+1)),l),mt(e,t,i,l),o&&Be(ze(o,Ht(t,r,i+1)),l)),mt(r,null,i,l),new b(l)}function Ht(n,e,t){let r=[];if(mt(null,n,t,r),n.depth>t){let i=On(n,e,t+1);Be(ze(i,Ht(n,e,t+1)),r)}return mt(e,null,t,r),new b(r)}function Ml(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class gt{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new qt(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new gt(t,r,s)}static resolveCached(e,t){let r=Jr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Hr(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class Kt extends Fe{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Hr(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Kt(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Kt(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Hr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Le{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new Ol(e,t);if(r.next==null)return Le.empty;let i=qr(r);r.next&&r.err("Unexpected trailing text");let s=Rl(vl(i));return Pl(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Le.empty=new Le(!0);class Ol{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function qr(n){let e=[];do e.push(Nl(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Nl(n){let e=[];do e.push(El(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function El(n){let e=Il(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=Dl(n,e);else break;return e}function Kr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Dl(n,e){let t=Kr(n),r=t;return n.eat(",")&&(n.next!="}"?r=Kr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Al(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Il(n){if(n.eat("(")){let e=qr(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Al(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function vl(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Le(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Yr(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),b.from(t),E.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,E.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new Fe(this,e,t.append(s),E.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new ml(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Bl(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class zl{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Bl(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class _t{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Qr(e,i.attrs),this.excluded=null;let s=Gr(this.attrs);this.instance=s?new E(this,s):null}create(e=null){return!e&&this.instance?this.instance:new E(this,Yr(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new _t(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class ei{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=F.from(e.nodes),t.marks=F.from(e.marks||{}),this.nodes=Zr.compile(this.spec.nodes,this),this.marks=_t.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Le.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?ti(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:ti(this,o.split(" "))}this.nodeFromJSON=i=>Fe.fromJSON(this,i),this.markFromJSON=i=>E.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Zr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Kt(r,r.defaultAttrs,e,E.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function ti(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Fl(n){return n.tag!=null}function Ll(n){return n.style!=null}class he{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Fl(i))this.tags.push(i);else if(Ll(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new si(this,t,!1);return r.addAll(e,E.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new si(this,t,!0);return r.addAll(e,E.none,t.from,t.to),k.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=oi(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=oi(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new he(e,he.schemaRules(e)))}}const ni={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Vl={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},ri={ol:!0,ul:!0},yt=1,Nn=2,bt=4;function ii(n,e,t){return e!=null?(e?yt:0)|(e==="full"?Nn:0):n&&n.whitespace=="pre"?yt|Nn:t&~bt}class Ut{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=E.none,this.match=s||(o&bt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&yt)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!ni.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class si{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=ii(null,t.preserveWhitespace,0)|(r?bt:0);i?s=new Ut(i.type,i.attrs,E.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Ut(null,null,E.none,!0,null,o):s=new Ut(e.schema.topNodeType,null,E.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Nn?"full":this.localPreserveWS||(i.options&yt)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):li(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Ut(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=yt)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function $l(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&ri.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Wl(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function oi(n){let e={};for(let t in n)e[t]=n[t];return e}function li(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Yt(Gt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Yt(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ve(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=ai(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return ai(e.marks)}}function ai(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Gt(n){return n.document||window.document}const ci=new WeakMap;function jl(n){let e=ci.get(n);return e===void 0&&ci.set(n,e=Jl(n)),e}function Jl(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let u in c)if(c[u]!=null){let d=u.indexOf(" ");d>0?a.setAttributeNS(u.slice(0,d),u.slice(d+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=f;uf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof d=="string")a.appendChild(n.createTextNode(d));else{let{dom:h,contentDOM:p}=Yt(n,d,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const fi=65535,ui=Math.pow(2,16);function Hl(n,e){return n+e*ui}function di(n){return n&fi}function ql(n){return(n-(n&fi))/ui}const hi=1,pi=2,Xt=4,mi=8;class En{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&mi)>0}get deletedBefore(){return(this.delInfo&(hi|Xt))>0}get deletedAfter(){return(this.delInfo&(pi|Xt))>0}get deletedAcross(){return(this.delInfo&Xt)>0}}class X{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&X.empty)return X.empty}recover(e){let t=0,r=di(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],u=a+c;if(e<=u){let d=c?e==a?-1:e==u?1:t:t,h=a+i+(d<0?0:f);if(r)return h;let p=e==(t<0?a:u)?null:Hl(l/3,e-a),m=e==a?pi:e==u?hi:Xt;return(t<0?e!=a:e!=u)&&(m|=mi),new En(h,m,p)}i+=f-c}return r?e+i:new En(e+i,0,null)}touches(e,t){let r=0,i=di(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new kt;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,s)}invert(){return new re(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Me(t.pos,r.pos,this.mark)}merge(e){return e instanceof Me&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Me(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Me(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("addMark",Me);class re extends W{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new k(An(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return I.fromReplace(e,this.from,this.to,r)}invert(){return new Me(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new re(t.pos,r.pos,this.mark)}merge(e){return e instanceof re&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new re(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new re(t.from,t.to,e.markFromJSON(t.mark))}}W.jsonID("removeMark",re);class Ce extends W{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new P(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new P(t.from,t.to,t.gapFrom,t.gapTo,k.fromJSON(e,t.slice),t.insert,!!t.structure)}}W.jsonID("replaceAround",P);function In(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function Kl(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&f.type.allowsMarkType(r.type)){let d=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(u);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function _l(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof _t){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new re(o.from,o.to,o.style)))}function vn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Ul(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function nt(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=b.from(r.node(p).copy(f)),u++):a--;let d=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new P(i,s,i,s,new k(r,0,0),t.length,!0))}function Zl(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&ea(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&ki(n,o,l,s),vn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),u=f.map(l,1),d=f.map(l+o.nodeSize,1);return n.step(new P(u,d,u+1,d-1,new k(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&bi(n,o,l,s),!1}})}function bi(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function ki(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function ea(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function ta(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new P(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new k(b.from(o),0,0),1,!0))}function pe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let u=i.node(c),d=i.index(c);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),p=r&&r[f+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||u;if(!u.canReplace(d+1,u.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function na(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let f=r&&r[c];o=b.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new v(e,e,new k(s.append(o),t,t),!0))}function We(n,e){let t=n.resolve(e),r=t.index();return xi(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function ra(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&xi(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function ia(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",u=!!o.contentMatch.matchType(i);f&&!u?r=!1:!f&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);ki(n,f.node(),f.before(),l)}o.inlineContent&&vn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new v(c,a.map(e+t,-1),k.empty,!0)),r===!0){let f=n.doc.resolve(c);bi(n,f.node(),f.before(),n.steps.length)}return n}function sa(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=u&&c.canReplaceWith(a,a,u[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Zt(n,e,t=e,r=k.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return Si(i,s,r)?new v(e,t,r):new la(i,s,r).fit()}function Si(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class la{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new k(s,o,l);return e>-1?new P(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new v(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=Mi(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,u=null;if(t==1&&(o?c.matchType(o.type)||(u=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:u};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return wi(e,-1)<=t?!1:(this.unplaced.size>1&&wi(e,1)>r&&r++,this.unplaced=new k(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=Mi(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new k(xt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new k(xt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(u=g,f.push(Ci(m.mark(d.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=St(this.placed,t,b.from(f)),this.frontier[t].match=u,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=Rn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=St(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=St(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=St(this.placed,this.frontier.length,t))}}function xt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(xt(n.firstChild.content,e-1,t)))}function St(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(St(n.lastChild.content,e-1,t)))}function Mi(n,e){for(let t=0;t1&&(r=r.replaceChild(0,Ci(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function Rn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!aa(t,s.content,o)?l:null}function aa(n,e,t){for(let r=t;r0;d--,h--){let p=i.node(d).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==h&&o.splice(1,0,-d)}let a=o.indexOf(l),c=[],f=r.openStart;for(let d=r.content,h=0;;h++){let p=d.firstChild;if(c.push(p),h==r.openStart)break;d=p.content}for(let d=f-1;d>=0;d--){let h=c[d],p=ca(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))f=d;else if(p||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+f+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));d--){let h=o[d];h<0||(e=i.before(h),t=s.after(h))}}function Ti(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function ua(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=sa(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new k(b.from(r),0,0))}function da(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=Oi(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Oi(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class rt extends W{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return I.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return I.fromReplace(e,this.pos,this.pos+1,new k(b.from(i),0,t.isLeaf?0:1))}getMap(){return X.empty}invert(e){return new rt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new rt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new rt(t.pos,t.attr,t.value)}}W.jsonID("attr",rt);class Mt extends W{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return I.ok(r)}getMap(){return X.empty}invert(e){return new Mt(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Mt(t.attr,t.value)}}W.jsonID("docAttr",Mt);let it=class extends Error{};it=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t},it.prototype=Object.create(Error.prototype),it.prototype.constructor=it,it.prototype.name="TransformError";class Ni{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new kt}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new it(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=k.empty){let i=Zt(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new k(b.from(r),0,0))}delete(e,t){return this.replace(e,t,k.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return fa(this,e,t,r),this}replaceRangeWith(e,t,r){return ua(this,e,t,r),this}deleteRange(e,t){return da(this,e,t),this}lift(e,t){return Gl(this,e,t),this}join(e,t=1){return ia(this,e,t),this}wrap(e,t){return Ql(this,e,t),this}setBlockType(e,t=e,r,i=null){return Zl(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return ta(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new rt(e,t,r)),this}setDocAttribute(e,t){return this.step(new Mt(e,t)),this}addNodeMark(e,t){return this.step(new Ce(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof E)t.isInSet(r.marks)&&this.step(new $e(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new $e(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return na(this,e,t,r),this}addMark(e,t,r){return Kl(this,e,t,r),this}removeMark(e,t,r){return _l(this,e,t,r),this}clearIncompatible(e,t,r){return vn(this,e,t,r),this}}const Pn=Object.create(null);class T{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ha(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?st(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):st(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new G(e.node(0))}static atStart(e){return st(e,e,0,0,1)||new G(e)}static atEnd(e){return st(e,e,e.content.size,e.childCount,-1)||new G(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Pn[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Pn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Pn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return S.between(this.$anchor,this.$head).getBookmark()}}T.prototype.visible=!0;class ha{constructor(e,t){this.$from=e,this.$to=t}}let Ei=!1;function Di(n){!Ei&&!n.parent.inlineContent&&(Ei=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class S extends T{constructor(e,t=e){Di(e),Di(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return T.near(r);let i=e.resolve(t.map(this.anchor));return new S(i.parent.inlineContent?i:r,r)}replace(e,t=k.empty){if(super.replace(e,t),t==k.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof S&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new en(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new S(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=T.findFrom(t,r,!0)||T.findFrom(t,-r,!0);if(s)t=s.$head;else return T.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(T.findFrom(e,-r,!0)||T.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(n,t-(i<0?l.nodeSize:0))}else{let a=st(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ai(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Ii=1,tn=2,vi=4;class ma extends Ni{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=tn,this}ensureMarks(e){return E.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&tn)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~tn,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||E.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(T.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=vi,this}get scrolledIntoView(){return(this.updated&vi)>0}}function Ri(n,e){return!e||!n?n:n.bind(e)}class Ct{constructor(e,t,r){this.name=e,this.init=Ri(t.init,r),this.apply=Ri(t.apply,r)}}const ga=[new Ct("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Ct("selection",{init(n,e){return n.selection||T.atStart(e.doc)},apply(n){return n.selection}}),new Ct("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Ct("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class zn{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ga.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Ct(r.key,r.spec.state,r))})}}class ot{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new zn(e.schema,e.plugins),s=new ot(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=T.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Pi(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Pi(i,e,{})),t[r]=i}return t}class ce{constructor(e){this.spec=e,this.props={},e.props&&Pi(e.props,this,this.props),this.key=e.key?e.key.key:Bi("plugin")}getState(e){return e[this.key]}}const Fn=Object.create(null);function Bi(n){return n in Fn?n+"$"+ ++Fn[n]:(Fn[n]=0,n+"$")}class ie{constructor(e="key"){this.key=Bi(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const zi=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Fi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const Li=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);if(!i){let o=r.blockRange(),l=o&&nt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Ui(n,i,e,-1))return!0;if(r.parent.content.size==0&&(lt(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=Zt(n.doc,r.before(o),r.after(o),k.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},ya=(n,e,t)=>{let r=Fi(n,t);if(!r)return!1;let i=Ln(r);return i?Vi(n,i,e):!1},ba=(n,e,t)=>{let r=Wi(n,t);if(!r)return!1;let i=Vn(r);return i?Vi(n,i,e):!1};function Vi(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let f=i.lastChild;if(!f)return!1;i=f}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let f=l.firstChild;if(!f)return!1;l=f}let c=Zt(n.doc,s,a,k.empty);if(!c||c.from!=s||c instanceof v&&c.slice.size>=a-s)return!1;if(t){let f=n.tr.step(c);f.setSelection(S.create(f.doc,s)),t(f.scrollIntoView())}return!0}function lt(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const $i=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Ln(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Ln(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Wi(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Wi(n,t);if(!r)return!1;let i=Vn(r);if(!i)return!1;let s=i.nodeAfter;if(Ui(n,i,e,1))return!0;if(r.parent.content.size==0&&(lt(s,"start")||x.isSelectable(s))){let o=Zt(n.doc,r.before(),r.after(),k.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof x,i;if(r){if(t.node.isTextblock||!We(n.doc,t.from))return!1;i=t.from}else if(i=Qt(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(x.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},xa=(n,e)=>{let t=n.selection,r;if(t instanceof x){if(t.node.isTextblock||!We(n.doc,t.to))return!1;r=t.to}else if(r=Qt(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},Sa=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&nt(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},Hi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function $n(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=$n(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(T.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Ki=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof G||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=$n(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(pe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&nt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Ma(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!pe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof G)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),f=i.start(h)==i.pos-(i.depth-h),a=$n(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let u=i.pos,d=pe(r.doc,u,o.length,o);if(d||(o[0]=a?{type:a}:null,d=pe(r.doc,u,o.length,o)),!d)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const Ca=Ma(),wa=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(x.create(n.doc,i))),!0)},Ta=(n,e)=>(e&&e(n.tr.setSelection(new G(n.doc))),!0);function Oa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||We(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Ui(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&Oa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,h,e.pos,h,new k(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&We(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:T.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),d=u&&nt(u);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(u,d).scrollIntoView()),!0;if(c&<(s,"start",!0)&<(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let C=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new k(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function Gi(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const Yi=Gi(-1),Xi=Gi(1);function Na(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&gi(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Qi(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Zi(n,e=null,t){return function(r,i){let{empty:s,$cursor:o,ranges:l}=r.selection;if(s&&!o||!Ea(r.doc,l,n))return!1;if(i)if(o)n.isInSet(r.storedMarks||o.marks())?i(r.tr.removeStoredMark(n)):i(r.tr.addStoredMark(n.create(e)));else{let a,c=r.tr;a=!l.some(f=>r.doc.rangeHasMark(f.$from.pos,f.$to.pos,n));for(let f=0;f=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new qt(a,a,e.depth),e.endIndex=0;f--)s=b.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new k(s,0,0),t.length,!0));let o=0;for(let f=0;fo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Pa(e,t,n,s):Ba(e,t,s):!0:!1}}function Pa(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?b.empty:b.from(i))))return!1;let u=s.pos,d=u+o.nodeSize;return r.step(new P(u-(l?1:0),d+(a?1:0),u+1,d-1,new k((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function za(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=b.from(c?n.create():null),u=new k(b.from(n.create(null,b.from(l.type.create(null,f)))),c?3:1,0),d=s.start,h=s.end;t(e.tr.step(new P(d-(c?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const L=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},at=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Jn=null;const ge=function(n,e,t){let r=Jn||(Jn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Fa=function(){Jn=null},je=function(n,e,t,r){return t&&(ns(n,e,t,r,-1)||ns(n,e,t,r,1))},La=/^(img|br|input|textarea|hr)$/i;function ns(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:Q(n))){let o=n.parentNode;if(!o||o.nodeType!=1||wt(n)||La.test(n.nodeName)||n.contentEditable=="false")return!1;e=L(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?Q(n):0}else return!1}}function Q(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Va(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Q(n)}else if(n.parentNode&&!wt(n))e=L(n),n=n.parentNode;else return null}}function $a(n,e){for(;;){if(n.nodeType==3&&e2),ee=ct||(fe?/Mac/.test(fe.platform):!1),ls=fe?/Win/.test(fe.platform):!1,ye=/Android \d/.test(we),Tt=!!rs&&"webkitFontSmoothing"in rs.documentElement.style,Ha=Tt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function qa(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function be(n,e){return typeof n=="number"?n:n[e]}function Ka(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function as(n,e,t){if(!Un(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=at(o);continue}let l=o,a=l==s.body,c=a?qa(s):Ka(l),f=0,u=0;if(e.topc.bottom-be(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+be(i,"top")-c.top:e.bottom-c.bottom+be(i,"bottom")),e.leftc.right-be(r,"right")&&(f=e.right-c.right+be(i,"right")),f||u)if(a)s.defaultView.scrollBy(f,u);else{let h=l.scrollLeft,p=l.scrollTop;u&&(l.scrollTop+=u),f&&(l.scrollLeft+=f);let m=l.scrollLeft-h,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:at(o)}}function _a(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:cs(n.dom)}}function cs(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=at(r));return e}function Ua({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;fs(t,r==0?0:r-e)}function fs(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Ya(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:us(t,i)}function Ya(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function _n(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Xa(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Za(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function ds(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Tt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Za(n,r,i,e))}l==null&&(l=Qa(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Un(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,Ot(Oe(ge(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Gn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==Q(r))){let a=r.childNodes[i-1],c=a.nodeType==3?ge(a,Q(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Ot(Oe(c,1),!1)}if(s==null&&i=0)}function Ot(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Gn(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ps(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function nc(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return ps(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=hs(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=ge(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}const rc=/[\u0590-\u08ac]/;function ic(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!rc.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:ps(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:u}=n.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!h.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,u),a&&(a!=f||c!=u)&&l.extend&&l.extend(a,c)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}let ms=null,gs=null,ys=!1;function sc(n,e,t){return ms==e&&gs==t?ys:(ms=e,gs=t,ys=t=="up"||t=="down"?nc(n,e,t):ic(n,e,t))}const te=0,bs=1,He=2,se=3;class Nt{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=te,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tL(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof Ss){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ks&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?L(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let u=l;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=L(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?He:bs,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=se:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?He:se}r=o}this.dirty=He}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?He:bs;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==te&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class oc extends Nt{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Ne extends Nt{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=Ve.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Ne(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&se||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=se&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=te){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Xn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:u}=Ve.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let d=f;return f=ws(f,r,t),c?a=new lc(e,t,r,i,f,u||null,d,c):t.isText?new rn(e,t,r,i,f,d):new Ee(e,t,r,i,f,u||null,d)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>i.nodeType==1&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==te&&e.eq(this.node)&&sn(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new cc(this,o&&o.node,e);dc(this.node,this.innerDeco,(c,f,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,f):c.type.side>=0&&!u&&a.syncToMarks(f==this.node.childCount?E.none:this.node.child(f).marks,r,e,f),a.placeWidget(c,e,i)},(c,f,u,d)=>{a.syncToMarks(c.marks,r,e,d);let h;a.findNodeMatch(c,f,u,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,u,h,e)||a.updateNextNode(c,f,u,e,d,i)||a.addNode(c,f,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==He)&&(o&&this.protectLocalComposition(e,o),Ms(this.contentDOM,this.children,e),ct&&hc(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof S)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=pc(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new oc(this,s,t,i);e.input.compositionNodes.push(o),this.children=Xn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==se||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=te}updateOuterDeco(e){if(sn(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Cs(this.dom,this.nodeDOM,Yn(this.outerDeco,this.node,t),Yn(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function xs(n,e,t,r,i){ws(r,e,n);let s=new Ee(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class rn extends Ee{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==se||this.dirty!=te&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=te||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=te,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new rn(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=se)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Ss extends Nt{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==te&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class lc extends Ee{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==se)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Ms(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let f=Ne.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,f),this.top=f,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Ne)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function uc(n,e){return n.type.side-e.type.side}function dc(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+d.nodeSize;if(d.isText){let g=p;o!g.inline):l.slice();r(d,m,e.forChild(s,d),h),s=p}}function hc(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function pc(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Xn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Qn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(nn(t)){for(a=o;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&x.isSelectable(u)&&i.parent&&!(u.isInline&&Wa(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new x(o==d?l:r.resolve(d))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=o,d=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Os(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function gc(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,L(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&Y&&Te<=11&&(t.disabled=!0,t.disabled=!1)}function As(n,e){if(e instanceof x){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Is(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Is(n)}function Is(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function er(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||S.between(e,t,r)}function vs(n){return n.editable&&!n.hasFocus()?!1:Rs(n)}function Rs(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function yc(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return je(e.node,e.offset,t.anchorNode,t.anchorOffset)}function tr(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&T.findFrom(s,e)}function De(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Ps(n,e,t){let r=n.state.selection;if(r instanceof S)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return De(n,new S(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=tr(n.state,e);return i&&i instanceof x?De(n,i):!1}else if(!(ee&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?De(n,new x(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):Tt?De(n,new S(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof x&&r.node.isInline)return De(n,new S(e>0?r.$to:r.$from));{let i=tr(n.state,e);return i?De(n,i):!1}}}function on(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Dt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function ut(n,e){return e<0?bc(n):kc(n)}function bc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(Z&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Dt(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Bs(t))break;{let l=t.previousSibling;for(;l&&Dt(l,-1);)i=t.parentNode,s=L(l),l=l.previousSibling;if(l)t=l,r=on(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?nr(n,t,r):i&&nr(n,i,s)}function kc(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=on(t),s,o;for(;;)if(r{n.state==i&&ke(n)},50)}function zs(n,e){let t=n.state.doc.resolve(e);if(!(V||ls)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Fs(n,e,t){let r=n.state.selection;if(r instanceof S&&!r.empty||t.indexOf("s")>-1||ee&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=tr(n.state,e);if(o&&o instanceof x)return De(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof G?T.near(o,e):T.findFrom(o,e);return l?De(n,l):!1}return!1}function Ls(n,e){if(!(n.state.selection instanceof S))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Vs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function Mc(n){if(!j||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Vs(n,r,"true"),setTimeout(()=>Vs(n,r,"false"),20)}return!1}function Cc(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function wc(n,e){let t=e.keyCode,r=Cc(e);if(t==8||ee&&t==72&&r=="c")return Ls(n,-1)||ut(n,-1);if(t==46&&!e.shiftKey||ee&&t==68&&r=="c")return Ls(n,1)||ut(n,1);if(t==13||t==27)return!0;if(t==37||ee&&t==66&&r=="c"){let i=t==37?zs(n,n.state.selection.from)=="ltr"?-1:1:-1;return Ps(n,i,r)||ut(n,i)}else if(t==39||ee&&t==70&&r=="c"){let i=t==39?zs(n,n.state.selection.from)=="ltr"?1:-1:1;return Ps(n,i,r)||ut(n,i)}else{if(t==38||ee&&t==80&&r=="c")return Fs(n,-1,r)||ut(n,-1);if(t==40||ee&&t==78&&r=="c")return Mc(n)||Fs(n,1,r)||ut(n,1);if(r==(ee?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function rr(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||Ve.fromSchema(n.state.schema),l=Ks(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,u=0;for(;c&&c.nodeType==1&&(f=qs[c.nodeName.toLowerCase()]);){for(let h=f.length-1;h>=0;h--){let p=l.createElement(f[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${u?` -${u}`:""} ${JSON.stringify(t)}`);let d=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` -`);return{dom:a,text:d,slice:e}}function zs(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=kc(t),wt&&xc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!gc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Sc($s(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(yc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const gc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function yc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&Ls(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Vs(o[o.length-1],s.length));let f=Fs(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Fs(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function Ls(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function $s(n,e,t){return et})}return Dt.createHTML(n)}function kc(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=js(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Ws[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=bc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const q={},K={},Mc={touchstart:!0,touchmove:!0};class Cc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function wc(n){for(let e in q){let t=q[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Oc(n,r)&&!sr(n,r)&&(n.editable||!(r.type in K))&&t(n,r)},Mc[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),ir(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Tc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function ir(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>sr(n,r))})}function sr(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Oc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Nc(n,e){!sr(n,e)&&q[e.type]&&(n.editable||!(e.type in K))&&q[e.type](n,e)}K.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Ks(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),at&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||mc(n,t)?t.preventDefault():xe(n,"key")},K.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},K.keypress=(n,e)=>{let t=e;if(Ks(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function At(n){return{left:n.clientX,top:n.clientY}}function Ec(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function or(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function It(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Dc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(It(n,new x(t)),!0):!1}function Ac(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(It(n,x.create(n.state.doc,i)),!0):!1}function Ic(n,e,t,r,i){return or(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Ac(n,t):Dc(n,t))}function vc(n,e,t,r){return or(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Rc(n,e,t,r){return or(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Pc(n,t,r)}function Pc(n,e,t){if(t.button!=0)return!1;let r=Js(n,e,!0),i=n.state.doc;return r?(It(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new zc(n,r)),!0):!1}function Js(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function lr(n){return rn(n)}const Hs=ee?"metaKey":"ctrlKey";q.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=lr(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Ec(t,n.input.lastClick)&&!t[Hs]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(At(t));o&&(s=="singleClick"?n.input.mouseDown=new Bc(n,o,t,!!r):(s=="doubleClick"?vc:Rc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class qs{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Bc extends qs{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Hs],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(At(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):Ic(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(It(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class zc extends qs{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(At(e)),r=t&&Js(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),lr(n),xe(n,"pointer")},q.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},q.contextmenu=n=>lr(n);function Ks(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Fc=ye?5e3:-1;K.compositionstart=K.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&ns&&Lc(n)))n.markCursor=n.state.storedMarks||t.marks(),rn(n,!0),n.markCursor=null;else if(rn(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}_s(n,Fc)};function Lc(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}K.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,_s(n,20))};function _s(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>rn(n),e))}function Us(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Vc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Aa(e.focusNode,e.focusOffset),r=Ia(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function rn(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Us(n),e||n.docView&&n.docView.dirty){let t=Xn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function $c(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const vt=G&&we<15||at&&Ba<604;q.copy=K.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=vt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=nr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):$c(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Wc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function jc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Rt(n,r.value,null,i,e):Rt(n,r.textContent,r.innerHTML,i,e)},50)}function Rt(n,e,t,r,i){let s=zs(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Wc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Gs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}K.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=vt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Rt(n,Gs(r),r.getData("text/html"),i,t)?t.preventDefault():jc(n,t)};class Ys{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Jc=ee?"altKey":"ctrlKey";function Xs(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Jc]}q.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(At(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=nr(n,l);(!t.dataTransfer.files.length||!V||ts>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(vt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",vt||t.dataTransfer.setData("text/plain",c),n.dragging=new Ys(f,Xs(n,t),o)},q.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},K.dragover=K.dragenter=(n,e)=>e.preventDefault(),K.drop=(n,e)=>{try{Hc(n,e,n.dragging)}finally{n.dragging=null}};function Hc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(At(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=zs(n,Gs(e.dataTransfer),vt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Xs(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Xl(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(Zn(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}q.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},q.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},q.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in K)q[n]=K[n];function Pt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class sn{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof sn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Pt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class De{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=Zs(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof De){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ae.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Kc(l,n,e,t,i,s,o),f=on(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=Zs(n,l,a+t);if(c){s=!0;let f=on(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=Qs(s?eo(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function fr(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ae.from(e)}const _c={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Uc=G&&we<=11;class Gc{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Yc{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Gc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Uc&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,_c)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Es(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(G&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=lt(s))t.add(s);for(let s=e.anchorNode;s;s=lt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Es(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||Zc(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Xc(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,ef(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:nf(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const nf=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},rf=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function sf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Xn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100Ze(n,Je(13,"Enter"))))return;let R=n.state.tr.setSelection(N);M=="pointer"?R.setMeta("pointer",!0):M=="key"&&R.scrollIntoView(),s&&R.setMeta("composition",s),n.dispatch(R)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=tf(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!rf.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=so(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),G&&we<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((at&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&lf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,_=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let R=so(n,N.doc,c.sel);R&&!(V&&n.composing&&R.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=_(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=of(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=_(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>_(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",R=>R(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(_());else n.dispatch(_())}function so(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Zn(n,e.resolve(t.anchor),e.resolve(t.head))}function of(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||ur(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function af(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class oo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Cc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(uo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=co(this),ao(this),this.nodeViews=fo(this),this.docView=gs(this.state.doc,lo(this),fr(this),this.dom,this),this.domObserver=new Yc(this,(r,i,s,o)=>sf(this,r,i,s,o)),this.domObserver.start(),wc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ir(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(uo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Us(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=fo(this);ff(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&ir(this),this.editable=co(this),ao(this);let a=fr(this),c=lo(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&La(this);if(o){this.domObserver.stop();let h=u&&(G||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&cf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Vc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=gs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&ac(this)&&p.delaySelUpdate())?ke(this,h):(Os(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Va(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&rs(this,t.getBoundingClientRect(),e)}else rs(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return qa(this,e)}coordsAtPos(e,t=1){return cs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ya(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return nr(this,e)}destroy(){this.docView&&(Tc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],fr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Ea())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Nc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&Ra(this.dom.ownerDocument)==this.dom&&Qc(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}oo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function lo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function ao(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function co(n){return!n.someProp("editable",e=>e(n.state)===!1)}function cf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function fo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function ff(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function uo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var Ie={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},ln={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uf=typeof navigator<"u"&&/Mac/.test(navigator.platform),df=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)Ie[48+$]=Ie[96+$]=String($);for(var $=1;$<=24;$++)Ie[$+111]="F"+$;for(var $=65;$<=90;$++)Ie[$]=String.fromCharCode($+32),ln[$]=String.fromCharCode($);for(var dr in Ie)ln.hasOwnProperty(dr)||(ln[dr]=Ie[dr]);function hf(n){var e=uf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||df&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ln:Ie)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const pf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),mf=typeof navigator<"u"&&/Win/.test(navigator.platform);function gf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=ll.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:po({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const xf=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Sf=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),Mf=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=tt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},Cf=n=>e=>n(e),wf=()=>({state:n,dispatch:e})=>ji(n,e),Tf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Of=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Nf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Ef=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Df=n=>n.content?/^text(\*|\+)/.test(n.content):!1,mo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:mo(n,t,"left"),to:mo(e,t,"right")}),If=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Af(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},vf=()=>({commands:n})=>n.keyboardShortcut("Enter"),Rf=()=>({state:n,dispatch:e})=>Wi(n,e);function Pf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function an(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Pf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function go(n,e,t={}){return n.find(r=>r.type===e&&an(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function yo(n,e,t={}){return!!go(n,e,t)}function pr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!go([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&yo([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=ve(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=pr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},zf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(cn()||ko())&&r.dom.focus(),Lf()&&!cn()&&!ko()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!bo(t.state.selection))return o(),!0;const l=Ff(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},$f=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Wf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),xo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&xo(r)}return n};function fn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return xo(t)}function So(n){return typeof n?.nodesBetween=="function"}function dt(n,e,t){if(So(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),dt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Yr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(fn(n),t.parseOptions):he.fromSchema(a).parse(fn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(fn(n),t.parseOptions).content:s.parse(fn(n),t.parseOptions)}return dt("",e,t)}function Mo(n){return!("type"in n)}function Co(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const jf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=dt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Mo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):So(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&Co(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function wo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=wo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=dt(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&Co(e,e.steps.length-1,-1)),!0):!1},Hf=()=>({state:n,dispatch:e})=>fa(n,e),qf=()=>({state:n,dispatch:e})=>ua(n,e),Kf=()=>({state:n,dispatch:e})=>Pi(n,e),_f=()=>({state:n,dispatch:e})=>Li(n,e),Uf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Gt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Gf=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Gt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Yf=()=>({state:n,dispatch:e})=>aa(n,e),Xf=()=>({state:n,dispatch:e})=>ca(n,e);function To(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Qf(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=Qf(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function mr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>an(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const eu=(n,e={})=>({state:t,dispatch:r})=>mr(t,H(n,t.schema),e)?da(t,r):!1,tu=()=>({state:n,dispatch:e})=>Ji(n,e),nu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return wa(r)(e,t)},ru=()=>({state:n,dispatch:e})=>$i(n,e);function Oo(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function No(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const iu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=ve(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,No(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(No(d.attrs,e))))})})}),a},su=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),ou=()=>({tr:n,dispatch:e})=>{if(e){const t=new U(n.doc);n.setSelection(t)}return!0},lu=()=>({state:n,dispatch:e})=>zi(n,e),au=()=>({state:n,dispatch:e})=>Vi(n,e),cu=()=>({state:n,dispatch:e})=>ma(n,e),fu=()=>({state:n,dispatch:e})=>_i(n,e),uu=()=>({state:n,dispatch:e})=>Ki(n,e);function du(n,e,t={},r={}){return dt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const hu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=du(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Mo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function pu(n,e){const t=ve(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function mu(n,e){const t=new Ci(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function gu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function gr(n){return e=>gu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function Eo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...Eo(t())]:e}).flat(10)}function yu(n){return typeof n=="function"}function D(n,e=void 0,...t){return yu(n)?e?n.bind(e)(...t):n(...t):n}function bu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function un(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function ku(n){const e=[],{nodeExtensions:t,markExtensions:r}=un(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function xu(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Do(n){const e=[],t=xu(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Do(r[i]),...Do(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Ao(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>dn(t,r),{})}function Su(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Io(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Su(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function vo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&bu(t)?!1:t!=null))}function Ro(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Mu(n,e){var t;const r=ku(n),{nodeExtensions:i,markExtensions:s}=un(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Ro))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Io(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Ao(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=vo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Ro))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Io(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Ao(m,f)})),[c.name,d]}));return new Yr({topNode:o,nodes:l,marks:a})}function Cu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function wu(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Ou(n,e){return Mu(Tu(n),e)}function Nu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` +`);return{dom:a,text:d,slice:e}}function $s(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",d=>{e=d(e,s||r,n)}),s)return l=new k(b.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",d=>{l=d(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",d=>d(e,i,r,n));if(u)l=u;else{let d=i.marks(),{schema:h}=n.state,p=Ve.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,d)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),o=Ec(t),Tt&&Dc(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let u=+f[3];u>0;u--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||he.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!Tc.test(d.parentNode.nodeName)?{ignore:!0}:null}})),f)l=Ac(Hs(l,+f[1],+f[2]),f[4]);else if(l=k.maxOpen(Oc(l.content,i),!0),l.openStart||l.openEnd){let u=0,d=0;for(let h=l.content.firstChild;u{l=u(l,n,a)}),l}const Tc=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function Oc(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&js(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Js(o[o.length-1],s.length));let f=Ws(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return b.from(o)}return n}function Ws(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function js(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Hs(n,e,t){return et})}return At.createHTML(n)}function Ec(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Ks(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&qs[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=Nc(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{a.checkAttrs(r[l+1])}catch{break}i=b.from(a.create(r[l+1],i)),s++,o++}return new k(i,s,o)}const K={},_={},Ic={touchstart:!0,touchmove:!0};class vc{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Rc(n){for(let e in K){let t=K[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Bc(n,r)&&!or(n,r)&&(n.editable||!(r.type in _))&&t(n,r)},Ic[e]?{passive:!0}:void 0)}j&&n.dom.addEventListener("input",()=>null),sr(n)}function xe(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Pc(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function sr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>or(n,r))})}function or(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Bc(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function zc(n,e){!or(n,e)&&K[e.type]&&(n.editable||!(e.type in _))&&K[e.type](n,e)}_.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Ys(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ye&&V&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),ct&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Je(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||wc(n,t)?t.preventDefault():xe(n,"key")},_.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)},_.keypress=(n,e)=>{let t=e;if(Ys(n)||!t.charCode||t.ctrlKey&&!t.altKey||ee&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof S)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function It(n){return{left:n.clientX,top:n.clientY}}function Fc(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function lr(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function vt(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Lc(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&x.isSelectable(r)?(vt(n,new x(t)),!0):!1}function Vc(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof x&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(vt(n,x.create(n.state.doc,i)),!0):!1}function $c(n,e,t,r,i){return lr(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Vc(n,t):Lc(n,t))}function Wc(n,e,t,r){return lr(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function jc(n,e,t,r){return lr(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Jc(n,t,r)}function Jc(n,e,t){if(t.button!=0)return!1;let r=_s(n,e,!0),i=n.state.doc;return r?(vt(n,r),r instanceof S&&i.eq(n.state.doc)&&(n.input.mouseDown=new qc(n,r)),!0):!1}function _s(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?S.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return S.create(r,l+1,l+1+o.content.size);if(t&&x.isSelectable(o))return x.create(r,l)}return null}function ar(n){return ln(n)}const Us=ee?"metaKey":"ctrlKey";K.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=ar(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Fc(t,n.input.lastClick)&&!t[Us]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(It(t));o&&(s=="singleClick"?n.input.mouseDown=new Hc(n,o,t,!!r):(s=="doubleClick"?Wc:jc)(n,o.pos,o.inside,t)?t.preventDefault():xe(n,"pointer"))};class Gs{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Hc extends Gs{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Us],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof x&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Z&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),xe(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||ke(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(It(e))),this.updateAllowDefault(e),this.allowDefault||!t?xe(this.view,"pointer"):$c(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||j&&this.mightDrag&&!this.mightDrag.node.isAtom||V&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(vt(this.view,T.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):xe(this.view,"pointer")}move(e){this.updateAllowDefault(e),xe(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class qc extends Gs{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),xe(this.view,"pointer");let t=this.view.posAtCoords(It(e)),r=t&&_s(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),ar(n),xe(n,"pointer")},K.touchmove=n=>{n.input.lastTouch=Date.now(),xe(n,"pointer")},K.contextmenu=n=>ar(n);function Ys(n,e){return n.composing?!0:j&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Kc=ye?5e3:-1;_.compositionstart=_.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof S&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||V&&ls&&_c(n)))n.markCursor=n.state.storedMarks||t.marks(),ln(n,!0),n.markCursor=null;else if(ln(n,!e.selection.empty),Z&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Xs(n,Kc)};function _c(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}_.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Xs(n,20))};function Xs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>ln(n),e))}function Qs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Uc(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Va(e.focusNode,e.focusOffset),r=$a(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function ln(n,e=!1){if(!(ye&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Qs(n),e||n.docView&&n.docView.dirty){let t=Qn(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Gc(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Rt=Y&&Te<15||ct&&Ha<604;K.copy=_.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Rt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=rr(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Gc(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Yc(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Xc(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Pt(n,r.value,null,i,e):Pt(n,r.textContent,r.innerHTML,i,e)},50)}function Pt(n,e,t,r,i){let s=$s(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||k.empty)))return!0;if(!s)return!1;let o=Yc(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Zs(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}_.paste=(n,e)=>{let t=e;if(n.composing&&!ye)return;let r=Rt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Pt(n,Zs(r),r.getData("text/html"),i,t)?t.preventDefault():Xc(n,t)};class eo{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Qc=ee?"altKey":"ctrlKey";function to(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Qc]}K.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(It(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(r&&r.mightDrag)o=x.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(o=x.create(n.state.doc,u.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=rr(n,l);(!t.dataTransfer.files.length||!V||ss>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Rt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Rt||t.dataTransfer.setData("text/plain",c),n.dragging=new eo(f,to(n,t),o)},K.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)},_.dragover=_.dragenter=(n,e)=>e.preventDefault(),_.drop=(n,e)=>{try{Zc(n,e,n.dragging)}finally{n.dragging=null}};function Zc(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(It(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=$s(n,Zs(e.dataTransfer),Rt?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&to(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||k.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?oa(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),f=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,u=a.doc;if(f?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(u))return;let d=a.doc.resolve(c);if(f&&x.isSelectable(s.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new x(d));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(er(n,d,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}K.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&ke(n)},20))},K.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)},K.beforeinput=(n,e)=>{if(ye&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,Je(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in _)K[n]=_[n];function Bt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class an{constructor(e,t){this.toDOM=e,this.spec=t||Ke,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof an&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Bt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ae{constructor(e,t){this.attrs=e,this.spec=t||Ke}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==J||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ke)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=ro(t,l,c)){for(i||(i=this.children.slice());sl&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ae){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ke));return Ie.from(r)}forChild(e,t){if(t.isLeaf)return B.empty;let r=[];for(let i=0;it instanceof B)?e:e.reduce((t,r)=>t.concat(r instanceof B?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-d);for(let y=0;yC+f-u)continue;let w=l[y]+f-u;h>=w?l[y+1]=d<=w?-2:-1:d>=f&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let d=t.map(n[c+1]+s,-1),h=d-i,{index:p,offset:m}=r.content.findIndex(u),g=r.maybeChild(p);if(g&&m==u&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);y!=J?(l[c]=u,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=tf(l,n,e,t,i,s,o),f=cn(c,r,0,o);e=f.local;for(let u=0;ut&&o.to{let c=ro(n,l,a+t);if(c){s=!0;let f=cn(c,l,t+a+1,r);f!=J&&i.push(a,a+l.nodeSize,f)}});let o=no(s?io(n):n,-t).sort(_e);for(let l=0;l0;)e++;n.splice(e,0,t)}function ur(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=J&&e.push(r)}),n.cursorWrapper&&e.push(B.create(n.state.doc,[n.cursorWrapper.deco])),Ie.from(e)}const nf={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},rf=Y&&Te<=11;class sf{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class of{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new sf,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():j&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),rf&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,nf)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(vs(this.view)){if(this.suppressingSelectionUpdates)return ke(this.view);if(Y&&Te<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&je(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=at(s))t.add(s);for(let s=e.anchorNode;s;s=at(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&vs(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;ff.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||V&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(f=>f.type=="childList"&&f.removedNodes.length))){for(let f of a)if(f.nodeName=="BR"&&f.parentNode){let u=f.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){f.parentNode.removeChild(f);break}u=u.firstChild}}}else if(Z&&a.length){let f=a.filter(u=>u.nodeName=="BR");if(f.length==2){let[u,d]=f;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of f){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||cf(e,u)!=h)&&d.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),lf(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,ff(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||ke(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let f=0;fs;y--){let C=i.childNodes[y-1],w=C.pmViewDesc;if(C.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||he.fromSchema(n.state.schema),p=d.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:f,ruleFromNode:df(r),context:p});if(f&&f[0].pos!=null){let y=f[0].pos,C=f[1]&&f[1].pos;C==null&&(C=y),m={anchor:y+l,head:C+l}}return{doc:g,sel:m,from:l,to:a}}const df=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(j&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||j&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},hf=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function pf(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let M=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,N=Qn(n,M);if(N&&!n.state.selection.eq(N)){if(V&&ye&&n.input.lastKeyCode===13&&Date.now()-100et(n,Je(13,"Enter"))))return;let R=n.state.tr.setSelection(N);M=="pointer"?R.setMeta("pointer",!0):M=="key"&&R.scrollIntoView(),s&&R.setMeta("composition",s),n.dispatch(R)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=uf(n,e,t,i),f=n.state.doc,u=f.slice(c.from,c.to),d,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ye)&&i.some(M=>M.nodeType==1&&!hf.test(M.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",M=>M(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof S&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let M=co(n,n.state.doc,c.sel);if(M&&!M.eq(n.state.selection)){let N=n.state.tr.setSelection(M);s&&N.setMeta("composition",s),n.dispatch(N)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),Y&&Te<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=f.resolve(p.start),C=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((ct&&n.input.lastIOSEnter>Date.now()-225&&(!C||i.some(M=>M.nodeName=="DIV"||M.nodeName=="P"))||!C&&m.posM(n,Je(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&gf(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",M=>M(n,Je(8,"Backspace")))){ye&&V&&n.domObserver.suppressSelectionUpdates();return}V&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ye&&!C&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(M){return M(n,Je(13,"Enter"))})},20));let w=p.start,A=p.endA,U=M=>{let N=M||n.state.tr.replace(w,A,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let R=co(n,N.doc,c.sel);R&&!(V&&n.composing&&R.empty&&(p.start!=p.endB||n.input.lastChromeDeleteke(n),20));let M=U(n.state.tr.delete(w,A)),N=f.resolve(p.start).marksAcross(f.resolve(p.endA));N&&M.ensureMarks(N),n.dispatch(M)}else if(p.endA==p.endB&&(ne=mf(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let M=U(n.state.tr);ne.type=="add"?M.addMark(w,A,ne.mark):M.removeMark(w,A,ne.mark),n.dispatch(M)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let M=m.parent.textBetween(m.parentOffset,g.parentOffset),N=()=>U(n.state.tr.insertText(M,w,A));n.someProp("handleTextInput",R=>R(n,w,A,M,N))||n.dispatch(N())}else n.dispatch(U());else n.dispatch(U())}function co(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:er(n,e.resolve(t.anchor),e.resolve(t.head))}function mf(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||dr(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function yf(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let f=Math.max(0,s-Math.min(a,c));r-=a+f-s}if(a=a?s-r:0;s-=f,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=f,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class fo{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new vc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(go),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=po(this),ho(this),this.nodeViews=mo(this),this.docView=xs(this.state.doc,uo(this),ur(this),this.dom,this),this.domObserver=new of(this,(r,i,s,o)=>pf(this,r,i,s,o)),this.domObserver.start(),Rc(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&sr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(go),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Qs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=mo(this);kf(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&sr(this),this.editable=po(this),ho(this);let a=ur(this),c=uo(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=s||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(o=!0);let d=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&_a(this);if(o){this.domObserver.stop();let h=u&&(Y||V)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&bf(i.selection,e.selection);if(u){let m=V?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Uc(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=xs(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&yc(this)&&p.delaySelUpdate())?ke(this,h):(As(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():d&&Ua(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&as(this,t.getBoundingClientRect(),e)}else as(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ec(this,e)}coordsAtPos(e,t=1){return hs(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return sc(this,t||this.state,e)}pasteHTML(e,t){return Pt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Pt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return rr(this,e)}destroy(){this.docView&&(Pc(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ur(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Fa())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return zc(this,e)}domSelectionRange(){let e=this.domSelection();return e?j&&this.root.nodeType===11&&ja(this.dom.ownerDocument)==this.dom&&af(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}fo.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function uo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function ho(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function po(n){return!n.someProp("editable",e=>e(n.state)===!1)}function bf(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function mo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function kf(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function go(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var ve={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},fn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},xf=typeof navigator<"u"&&/Mac/.test(navigator.platform),Sf=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),$=0;$<10;$++)ve[48+$]=ve[96+$]=String($);for(var $=1;$<=24;$++)ve[$+111]="F"+$;for(var $=65;$<=90;$++)ve[$]=String.fromCharCode($+32),fn[$]=String.fromCharCode($);for(var hr in ve)fn.hasOwnProperty(hr)||(fn[hr]=ve[hr]);function Mf(n){var e=xf&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||Sf&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?fn:ve)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const Cf=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),wf=typeof navigator<"u"&&/Win/.test(navigator.platform);function Tf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l[l,(...f)=>{const u=a(...f)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,f=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),u}])),run:f};return u}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=gl.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:bo({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...f)=>c(...f)(l)]))}};return l}};const Df=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Af=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),If=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:f}=e,u=c.resolve(f.map(a)),d=c.resolve(f.map(a+l.nodeSize)),h=u.blockRange(d);if(!h)return;const p=nt(h);if(l.type.isTextblock){const{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},vf=n=>e=>n(e),Rf=()=>({state:n,dispatch:e})=>Ki(n,e),Pf=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new S(r.doc.resolve(Math.max(o-1,0)))),!0},Bf=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function H(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const zf=n=>({tr:e,state:t,dispatch:r})=>{const i=H(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Ff=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Lf=n=>n.content?/^text(\*|\+)/.test(n.content):!1,ko=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:ko(n,t,"left"),to:ko(e,t,"right")}),$f=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:f}=Vf(l,a,n.schema);t.deleteRange(c,f)}),t.selection.empty||t.setSelection(S.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Wf=()=>({commands:n})=>n.keyboardShortcut("Enter"),jf=()=>({state:n,dispatch:e})=>qi(n,e);function Jf(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function un(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Jf(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function xo(n,e,t={}){return n.find(r=>r.type===e&&un(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function So(n,e,t={}){return!!xo(n,e,t)}function mr(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!xo([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&So([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Re(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:f}=l;if(i){const u=mr(a,s,e);if(u&&u.from<=c&&u.to>=f){const d=S.create(o,u.from,u.to);t.setSelection(d)}}return!0},qf=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(dn()||Co())&&r.dom.focus(),_f()&&!dn()&&!Co()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!Mo(t.state.selection))return o(),!0;const l=Kf(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Gf=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Yf=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),wo=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&wo(r)}return n};function hn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return wo(t)}function To(n){return typeof n?.nodesBetween=="function"}function ht(n,e,t){if(To(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),ht("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new ei({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?he.fromSchema(a).parseSlice(hn(n),t.parseOptions):he.fromSchema(a).parse(hn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=he.fromSchema(e);return t.slice?s.parseSlice(hn(n),t.parseOptions).content:s.parse(hn(n),t.parseOptions)}return ht("",e,t)}function Oo(n){return!("type"in n)}function No(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=f)}),n.setSelection(T.near(n.doc.resolve(o),t))}const Xf=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ht(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=ht(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:f,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},d=!0,h=!0;const p=Oo(l)?l.content:[l];if(p.forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),f===u&&h){const{parent:g}=r.doc.resolve(f);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(f-=1,u+=1)}let m;if(d)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):To(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,f,u);else{m=b.from(p);const g=r.doc.resolve(f),y=g.node(),C=g.parentOffset===0,w=y.isText||y.isTextblock,A=y.content.size>0;C&&w&&A&&h&&(f=Math.max(0,f-1)),r.replaceWith(f,u,p)}t.updateSelection&&No(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:f,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:f,text:m})}return!0};function Eo(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=Eo(a.parent.contentMatchAt(a.index()));if(!c)return!1;const f=Object.keys(c.spec.attrs||{}),u=s?Object.fromEntries(Object.entries(s).filter(([h])=>f.includes(h))):{};let d;if(o){const h=ht(o,r.schema);d=c.createAndFill(u,h)}else d=c.createAndFill(u);return d?(t&&(e.insert(a.pos,d),l&&No(e,e.steps.length-1,-1)),!0):!1},Zf=()=>({state:n,dispatch:e})=>ka(n,e),eu=()=>({state:n,dispatch:e})=>xa(n,e),tu=()=>({state:n,dispatch:e})=>Li(n,e),nu=()=>({state:n,dispatch:e})=>ji(n,e),ru=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Qt(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},iu=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Qt(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},su=()=>({state:n,dispatch:e})=>ya(n,e),ou=()=>({state:n,dispatch:e})=>ba(n,e);function Do(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function lu(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=lu(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const f=c.map(r.mapping);f&&i&&r.maybeStep(f)}),!0};function gr(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?H(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(f,u)=>{if(f.isText)return;const d=Math.max(r,u),h=Math.min(i,u+f.nodeSize);l.push({node:f,from:d,to:h})});const a=i-r,c=l.filter(f=>o?o.name===f.node.type.name:!0).filter(f=>un(f.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((f,u)=>f+u.to-u.from,0)>=a}const cu=(n,e={})=>({state:t,dispatch:r})=>gr(t,H(n,t.schema),e)?Sa(t,r):!1,fu=()=>({state:n,dispatch:e})=>_i(n,e),uu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Ra(r)(e,t)},du=()=>({state:n,dispatch:e})=>Hi(n,e);function Ao(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Io(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const hu=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Ao(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(f,u)=>{s&&s===f.type&&(a=!0,i&&t.setNodeMarkup(u,void 0,Io(f.attrs,e))),o&&f.marks.length&&f.marks.forEach(d=>{o===d.type&&(a=!0,i&&t.addMark(u,u+f.nodeSize,o.create(Io(d.attrs,e))))})})}),a},pu=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),mu=()=>({tr:n,dispatch:e})=>{if(e){const t=new G(n.doc);n.setSelection(t)}return!0},gu=()=>({state:n,dispatch:e})=>$i(n,e),yu=()=>({state:n,dispatch:e})=>Ji(n,e),bu=()=>({state:n,dispatch:e})=>wa(n,e),ku=()=>({state:n,dispatch:e})=>Xi(n,e),xu=()=>({state:n,dispatch:e})=>Yi(n,e);function Su(n,e,t={},r={}){return ht(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const Mu=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=Su(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const f=Oo(c)?c.content:[c];s.replaceWith(0,a.content.size,f).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Cu(n,e){const t=Re(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function wu(n,e){const t=new Ni(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function Tu(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function yr(n){return e=>Tu(e.$from,n)}function O(n,e,t){return n.config[e]===void 0&&n.parent?O(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?O(n.parent,e,t):null}):n.config[e]}function vo(n){return n.map(e=>{const t=O(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...vo(t())]:e}).flat(10)}function Ou(n){return typeof n=="function"}function D(n,e=void 0,...t){return Ou(n)?e?n.bind(e)(...t):n(...t):n}function Nu(n={}){return Object.keys(n).length===0&&n.constructor===Object}function pn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function Eu(n){const e=[],{nodeExtensions:t,markExtensions:r}=pn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const f=O(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});f&&f().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=a:u.types==="nodes"?d=o:u.types==="marks"?d=l:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const f=O(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!f)return;const u=f();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:d,attribute:p})})}),e}function Du(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Ro(n){const e=[],t=Du(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Ro(r[i]),...Ro(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Po(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>mn(t,r),{})}function Au(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Bo(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Au(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function zo(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&Nu(t)?!1:t!=null))}function Fo(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Iu(n,e){var t;const r=Eu(n),{nodeExtensions:i,markExtensions:s}=pn(n),o=(t=i.find(c=>O(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const f=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=zo({...n.reduce((g,y)=>{const C=O(y,"extendNodeSchema",u);return{...g,...C?C(c):{}}},{}),content:D(O(c,"content",u)),marks:D(O(c,"marks",u)),group:D(O(c,"group",u)),inline:D(O(c,"inline",u)),atom:D(O(c,"atom",u)),selectable:D(O(c,"selectable",u)),draggable:D(O(c,"draggable",u)),code:D(O(c,"code",u)),whitespace:D(O(c,"whitespace",u)),linebreakReplacement:D(O(c,"linebreakReplacement",u)),defining:D(O(c,"defining",u)),isolating:D(O(c,"isolating",u)),attrs:Object.fromEntries(f.map(Fo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(g=>Bo(g,f)));const p=O(c,"renderHTML",u);p&&(d.toDOM=g=>p({node:g,HTMLAttributes:Po(g,f)}));const m=O(c,"renderText",u);return m&&(d.toText=m),[c.name,d]})),a=Object.fromEntries(s.map(c=>{const f=r.filter(m=>m.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},d=zo({...n.reduce((m,g)=>{const y=O(g,"extendMarkSchema",u);return{...m,...y?y(c):{}}},{}),inclusive:D(O(c,"inclusive",u)),excludes:D(O(c,"excludes",u)),group:D(O(c,"group",u)),spanning:D(O(c,"spanning",u)),code:D(O(c,"code",u)),attrs:Object.fromEntries(f.map(Fo))}),h=D(O(c,"parseHTML",u));h&&(d.parseDOM=h.map(m=>Bo(m,f)));const p=O(c,"renderHTML",u);return p&&(d.toDOM=m=>p({mark:m,HTMLAttributes:Po(m,f)})),[c.name,d]}));return new ei({topNode:o,nodes:l,marks:a})}function vu(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Ru(n){return n.sort((t,r)=>{const i=O(t,"priority")||100,s=O(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Bu(n,e){return Iu(Pu(n),e)}function zu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Eu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Du(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Au(n){const e=Du(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Iu(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Au(r)}function Po(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=pr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function hn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function vu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?ve(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>an(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>an(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function yr(n,e){const{nodeExtensions:t}=un(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Bo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Bo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Ru(n,e,t){const{selection:r}=e;let i=null;if(bo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Pu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=ve(n,r.schema);if(i)if(o){const c=pu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Ru(r,t,a)},Bu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),zu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Ui(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Ui(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Fu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},Lu=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Vu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},$u=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return Na(r)(e,t)};function zo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Wu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=hn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&zo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:wo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&zo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},ju=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=R+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...hn(u,f.type.name,f.attrs),...e},m={...hn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const _=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(_)}return!0};function Fo(n){return!n||n==="1"?null:n}function Lo(n,e){return Fo(n)===Fo(e)}const br=(n,e)=>{const t=gr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},kr=(n,e)=>{const t=gr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!Lo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Ju(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Hu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const _=gr(et=>yr(et.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,R=ne&&N&&yr(N.type.name,u)?{node:N,pos:0}:null,Ze=_??R,qd=!!_&&w.depth>=1&&w.depth-_.depth<=1,sl=!!R;if((qd||sl)&&Ze){if(Ze.node.type===h)return ne&&sl?a().command(({tr:et,dispatch:Mn})=>{const Cn=Ju(et);return Cn?(et.setSelection(Cn),Mn&&Mn(et),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(yr(Ze.node.type.name,u)&&h.validContent(Ze.node.content))return a().command(()=>(s.setNodeMarkup(Ze.pos,h),!0)).command(()=>br(s,h)).command(()=>kr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>br(s,h)).command(()=>kr(s,h)).run():a().command(()=>{const et=f().wrapInList(h,r),Mn=A.filter(Cn=>d.includes(Cn.type.name));return s.ensureMarks(Mn),et?!0:c.clearNodes()}).wrapInList(h,r).command(()=>br(s,h)).command(()=>kr(s,h)).run()},qu=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=ve(n,r.schema);return vu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},Ku=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=mr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},_u=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return mr(t,i,e)?r.lift(i):r.wrapIn(i,e)},Uu=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Gu=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},Yu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=ve(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=pr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},Xu=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Qu=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Oo(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=ve(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Zu=new ie("__tiptap_decorations__"),ed=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Zu,{type:"force",name:n}),!0),td=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return ba(i,e)(t,r)},nd=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return Sa(i,e)(t,r)};var rd=ul({blur:()=>xf,clearContent:()=>Sf,clearNodes:()=>Mf,command:()=>Cf,createParagraphNear:()=>wf,cut:()=>Tf,deleteCurrentNode:()=>Of,deleteNode:()=>Nf,deleteRange:()=>Ef,deleteSelection:()=>If,enter:()=>vf,exitCode:()=>Rf,extendMarkRange:()=>Bf,first:()=>zf,focus:()=>Vf,forEach:()=>$f,insertContent:()=>Wf,insertContentAt:()=>jf,insertDefaultBlock:()=>Jf,joinBackward:()=>Kf,joinDown:()=>qf,joinForward:()=>_f,joinItemBackward:()=>Uf,joinItemForward:()=>Gf,joinTextblockBackward:()=>Yf,joinTextblockForward:()=>Xf,joinUp:()=>Hf,keyboardShortcut:()=>Zf,lift:()=>eu,liftEmptyBlock:()=>tu,liftListItem:()=>nu,newlineInCode:()=>ru,resetAttributes:()=>iu,scrollIntoView:()=>su,selectAll:()=>ou,selectNodeBackward:()=>lu,selectNodeForward:()=>au,selectParentNode:()=>cu,selectTextblockEnd:()=>fu,selectTextblockStart:()=>uu,setContent:()=>hu,setMark:()=>Pu,setMeta:()=>Bu,setNode:()=>zu,setNodeSelection:()=>Fu,setTextDirection:()=>Lu,setTextSelection:()=>Vu,sinkListItem:()=>$u,splitBlock:()=>Wu,splitListItem:()=>ju,toggleList:()=>Hu,toggleMark:()=>qu,toggleNode:()=>Ku,toggleWrap:()=>_u,undoInputRule:()=>Uu,unsetAllMarks:()=>Gu,unsetMark:()=>Yu,unsetTextDirection:()=>Xu,updateAttributes:()=>Qu,updateDecorations:()=>ed,wrapIn:()=>td,wrapInList:()=>nd});typeof process<"u"&&process.env.NODE_ENV;function id(n){return Object.prototype.toString.call(n).slice(8,-1)}function pn(n){return id(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Vo(n,e){const t={...n};return pn(n)&&pn(e)&&Object.keys(e).forEach(r=>{pn(e[r])&&pn(n[r])?t[r]=Vo(n[r],e[r]):t[r]=e[r]}),t}var sd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},xr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Vo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},mn=class al extends xr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new al(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},od=class{constructor(n){this.find=n.find,this.handler=n.handler}},fe=class cl extends xr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new cl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};fe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Eu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Nu(r,{from:a.pos,to:c.pos},l)).join(o??` +`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,f,u)=>{a.isBlock&&c>r&&(l+=s);const d=o?.[a.type.name];if(d)return f&&(l+=d({node:a,pos:c,parent:f,index:u,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Fu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Lu(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Vu(n){const e=Lu(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function $u(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),f=e.slice(s).map(a),u=e.invert().map(c,-1),d=e.invert().map(f);r.push({oldRange:{from:u,to:d},newRange:{from:c,to:f}})})}),Vu(r)}function Lo(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=mr(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}function gn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}function Wu(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Re(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>un(f.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:f,$to:u})=>{const d=f.pos,h=u.pos;n.doc.nodesBetween(d,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(d,m),y=Math.min(h,m+p.nodeSize),C=y-g;o+=C,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>un(f.mark.attrs,t,{strict:!1})).reduce((f,u)=>f+u.to-u.from,0),c=l.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,u)=>f+u.to-u.from,0);return(a>0?a+c:a)>=o}function br(n,e){const{nodeExtensions:t}=pn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=D(O(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Vo(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Vo(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function ju(n,e,t){const{selection:r}=e;let i=null;if(Mo(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(f,u,d)=>{if(c)return!1;if(f.isInline){const h=!d||d.type.allowsMarkType(t),p=!!t.isInSet(f.marks)||!f.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const Ju=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Re(n,r.schema);if(i)if(o){const c=Cu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(f,u,(d,h)=>{const p=Math.max(h,f),m=Math.min(h+d.nodeSize,u);d.marks.find(g=>g.type===a)?d.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return ju(r,t,a)},Hu=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),qu=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=H(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Qi(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Qi(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Ku=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ue(n,0,r.content.size),s=x.create(r,i);e.setSelection(s)}return!0},_u=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Uu=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=S.atStart(r).from,l=S.atEnd(r).to,a=Ue(i,o,l),c=Ue(s,o,l),f=S.create(r,a,c);e.setSelection(f)}return!0},Gu=n=>({state:e,dispatch:t})=>{const r=H(n,e.schema);return za(r)(e,t)};function $o(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Yu=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,f=gn(c,l.node().type.name,l.node().attrs);if(s instanceof x&&s.node.isBlock)return!l.parentOffset||!pe(o,l.pos)?!1:(r&&(n&&$o(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const u=a.parentOffset===a.parent.content.size,d=l.depth===0?void 0:Eo(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=u&&d?[{type:d,attrs:f}]:void 0,p=pe(e.doc,e.mapping.map(l.pos),1,h);if(!h&&!p&&pe(e.doc,e.mapping.map(l.pos),1,d?[{type:d}]:void 0)&&(p=!0,h=d?[{type:d,attrs:f}]:void 0),r){if(p&&(s instanceof S&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,h),d&&!u&&!l.parentOffset&&l.parent.type!==d)){const m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(l.before()),d)}n&&$o(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return p},Xu=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=H(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const f=l.node(-1);if(f.type!==o)return!1;const u=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var d;let y=b.empty;const C=l.index(-1)?1:l.index(-2)?2:3;for(let N=l.depth-C;N>=l.depth-3;N-=1)y=b.from(l.node(N).copy(y));const w=l.indexAfter(-1){if(M>-1)return!1;N.isTextblock&&N.content.size===0&&(M=R+1)}),M>-1&&t.setSelection(S.near(t.doc.resolve(M))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?f.contentMatchAt(0).defaultType:null,p={...gn(u,f.type.name,f.attrs),...e},m={...gn(u,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,a.pos);const g=h?[{type:o,attrs:p},{type:h,attrs:m}]:[{type:o,attrs:p}];if(!pe(t.doc,l.pos,2))return!1;if(i){const{selection:y,storedMarks:C}=r,{splittableMarks:w}=s.extensionManager,A=C||y.$to.parentOffset&&y.$from.marks();if(t.split(l.pos,2,g).scrollIntoView(),!A||!i)return!0;const U=A.filter(ne=>w.includes(ne.type.name));t.ensureMarks(U)}return!0};function Wo(n){return!n||n==="1"?null:n}function jo(n,e){return Wo(n)===Wo(e)}const kr=(n,e)=>{const t=yr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,t.pos))||!jo(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},xr=(n,e)=>{const t=yr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&We(n.doc,r))||!jo(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Qu(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return S.between(r,i)}const Zu=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:f})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=H(n,o.schema),p=H(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:C}=m,w=y.blockRange(C),A=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const U=yr(tt=>br(tt.type.name,u))(m),ne=m.from===0&&m.to===o.doc.content.size,M=o.doc.content.content,N=M.length===1?M[0]:null,R=ne&&N&&br(N.type.name,u)?{node:N,pos:0}:null,et=U??R,uh=!!U&&w.depth>=1&&w.depth-U.depth<=1,pl=!!R;if((uh||pl)&&et){if(et.node.type===h)return ne&&pl?a().command(({tr:tt,dispatch:Cn})=>{const wn=Qu(tt);return wn?(tt.setSelection(wn),Cn&&Cn(tt),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(br(et.node.type.name,u)&&h.validContent(et.node.content))return a().command(()=>(s.setNodeMarkup(et.pos,h),!0)).command(()=>kr(s,h)).command(()=>xr(s,h)).run()}return!t||!A||!l?a().command(()=>f().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>kr(s,h)).command(()=>xr(s,h)).run():a().command(()=>{const tt=f().wrapInList(h,r),Cn=A.filter(wn=>d.includes(wn.type.name));return s.ensureMarks(Cn),tt?!0:c.clearNodes()}).wrapInList(h,r).command(()=>kr(s,h)).command(()=>xr(s,h)).run()},ed=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Re(n,r.schema);return Wu(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},td=(n,e,t={})=>({state:r,commands:i})=>{const s=H(n,r.schema),o=H(e,r.schema),l=gr(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},nd=(n,e={})=>({state:t,commands:r})=>{const i=H(n,t.schema);return gr(t,i,e)?r.lift(i):r.wrapIn(i,e)},rd=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},id=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(f=>i||!a.includes(f.name));l.forEach(f=>{for(const u of c)e.removeMark(f.$from.pos,f.$to.pos,u)})}return!0},sd=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Re(n,r.schema),{$from:a,empty:c,ranges:f}=o;if(!i)return!0;if(c&&s){var u;let{from:d,to:h}=o;const p=mr(a,l,(u=a.marks().find(m=>m.type===l))===null||u===void 0?void 0:u.attrs);p&&(d=p.from,h=p.to),t.removeMark(d,h,l)}else f.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,l)});return t.removeStoredMark(l),!0},od=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},ld=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=Ao(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=H(n,r.schema)),l==="mark"&&(o=Re(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const f=c.$from.pos,u=c.$to.pos;let d,h,p,m;t.selection.empty?r.doc.nodesBetween(f,u,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,f),m=Math.min(y+g.nodeSize,u),d=y,h=g)}):r.doc.nodesBetween(f,u,(g,y)=>{y=f&&y<=u&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(C=>{if(o===C.type&&(a=!0,i)){const w=Math.max(y,f),A=Math.min(y+g.nodeSize,u);t.addMark(w,A,o.create({...C.attrs,...e}))}}))}),h&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},ad=new ie("__tiptap_decorations__"),cd=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(ad,{type:"force",name:n}),!0),fd=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return Na(i,e)(t,r)},ud=(n,e={})=>({state:t,dispatch:r})=>{const i=H(n,t.schema);return Aa(i,e)(t,r)};var dd=xl({blur:()=>Df,clearContent:()=>Af,clearNodes:()=>If,command:()=>vf,createParagraphNear:()=>Rf,cut:()=>Pf,deleteCurrentNode:()=>Bf,deleteNode:()=>zf,deleteRange:()=>Ff,deleteSelection:()=>$f,enter:()=>Wf,exitCode:()=>jf,extendMarkRange:()=>Hf,first:()=>qf,focus:()=>Uf,forEach:()=>Gf,insertContent:()=>Yf,insertContentAt:()=>Xf,insertDefaultBlock:()=>Qf,joinBackward:()=>tu,joinDown:()=>eu,joinForward:()=>nu,joinItemBackward:()=>ru,joinItemForward:()=>iu,joinTextblockBackward:()=>su,joinTextblockForward:()=>ou,joinUp:()=>Zf,keyboardShortcut:()=>au,lift:()=>cu,liftEmptyBlock:()=>fu,liftListItem:()=>uu,newlineInCode:()=>du,resetAttributes:()=>hu,scrollIntoView:()=>pu,selectAll:()=>mu,selectNodeBackward:()=>gu,selectNodeForward:()=>yu,selectParentNode:()=>bu,selectTextblockEnd:()=>ku,selectTextblockStart:()=>xu,setContent:()=>Mu,setMark:()=>Ju,setMeta:()=>Hu,setNode:()=>qu,setNodeSelection:()=>Ku,setTextDirection:()=>_u,setTextSelection:()=>Uu,sinkListItem:()=>Gu,splitBlock:()=>Yu,splitListItem:()=>Xu,toggleList:()=>Zu,toggleMark:()=>ed,toggleNode:()=>td,toggleWrap:()=>nd,undoInputRule:()=>rd,unsetAllMarks:()=>id,unsetMark:()=>sd,unsetTextDirection:()=>od,updateAttributes:()=>ld,updateDecorations:()=>cd,wrapIn:()=>fd,wrapInList:()=>ud});typeof process<"u"&&process.env.NODE_ENV;function hd(n){return Object.prototype.toString.call(n).slice(8,-1)}function yn(n){return hd(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Jo(n,e){const t={...n};return yn(n)&&yn(e)&&Object.keys(e).forEach(r=>{yn(e[r])&&yn(n[r])?t[r]=Jo(n[r],e[r]):t[r]=e[r]}),t}var pd=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}},Sr=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...D(O(this,"addOptions",{name:this.name}))}}get storage(){return{...D(O(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Jo(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},bn=class yl extends Sr{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new yl(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},md=class{constructor(n){this.find=n.find,this.handler=n.handler}},ue=class bl extends Sr{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new bl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};ue.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ce({key:new ie("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Fu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>zu(r,{from:a.pos,to:c.pos},l)).join(o??` -`)}}})]}}),fe.create({name:"commands",addCommands(){return{...rd}}}),fe.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=mu(n.before,[n,...e]);Iu(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),fe.create({name:"drop",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fe.create({name:"editable",addProseMirrorPlugins(){return[new ae({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const ld=new ie("focusEvents");fe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ae({key:ld,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),fe.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return cn()||To()?s:i},addProseMirrorPlugins(){return[new ae({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Bo(t.doc))return;const f=t.tr,u=po({state:t,transaction:f}),{commands:d}=new kf({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),fe.create({name:"paste",addProseMirrorPlugins(){return[new ae({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),fe.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ae({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),fe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=un(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ae({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function Bt(n){return new sd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Po(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var $o=class fl extends xr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new fl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function zt(n){return new od({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Po(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var ad=$o.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`)}}})]}}),ue.create({name:"commands",addCommands(){return{...dd}}}),ue.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=wu(n.before,[n,...e]);$u(a).forEach(f=>{a.mapping.mapResult(f.oldRange.from).deletedAfter&&a.mapping.mapResult(f.oldRange.to).deletedBefore&&a.before.nodesBetween(f.oldRange.from,f.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,p=f.oldRange.from<=d&&h<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:a.mapping.map(d),newTo:a.mapping.map(h),deletedRange:f.oldRange,newRange:f.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((f,u)=>{if(f instanceof re){var d,h;const p=c.slice(u).map(f.from,-1),m=c.slice(u).map(f.to),g=c.invert().map(p,-1),y=c.invert().map(m),C=p>0?(d=a.doc.nodeAt(p-1))===null||d===void 0?void 0:d.marks.some(A=>A.eq(f.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||C),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),ue.create({name:"drop",addProseMirrorPlugins(){return[new ce({key:new ie("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),ue.create({name:"editable",addProseMirrorPlugins(){return[new ce({key:new ie("editable"),props:{editable:()=>this.editor.options.editable}})]}});const gd=new ie("focusEvents");ue.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new ce({key:gd,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),ue.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:f,$anchor:u}=a,{pos:d,parent:h}=u,p=u.parent.isTextblock&&d>0?l.doc.resolve(d-1):u,m=p.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&p.parent.childCount===1?g===u.pos:T.atStart(c).from===d;return!f||!h.type.isTextblock||h.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return dn()||Do()?s:i},addProseMirrorPlugins(){return[new ce({key:new ie("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=T.atStart(e.doc).from,c=T.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Vo(t.doc))return;const f=t.tr,u=bo({state:t,transaction:f}),{commands:d}=new Ef({editor:this.editor,state:u});if(d.clearNodes(),!!f.steps.length)return f}})]}}),ue.create({name:"paste",addProseMirrorPlugins(){return[new ce({key:new ie("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),ue.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new ce({key:new ie("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),ue.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=pn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ce({key:new ie("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});function zt(n){return new pd({find:n.find,handler:({state:e,range:t,match:r})=>{const i=D(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),f=c+o.length;if(Lo(t.from,t.to,e.doc).filter(d=>d.mark.type.excluded.find(h=>h===n.type&&h!==d.mark.type)).filter(d=>d.to>c).length)return null;ft.from&&s.delete(t.from+a,c);const u=t.from+a+o.length;s.addMark(t.from+a,u,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}var Ho=class kl extends Sr{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new kl(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Ft(n){return new md({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=D(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const f=a.search(/\S/),u=t.from+a.indexOf(l),d=u+l.length;if(Lo(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>u).length)return null;dt.from&&o.delete(t.from+f,u),c=t.from+f+l.length,o.addMark(t.from+f,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var yd=Ho.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""}),cd=$o.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const Wo=new WeakSet,jo=new WeakSet;function Ge(n){const e=n;return Wo.add(e),e}function Sr(n){return Array.isArray(n)&&Wo.has(n)}function Jo(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&jo.has(e)&&!Sr(e)?Jo(e):[e])}function fd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!Sr(i)&&!jo.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(Sr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=Jo(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const Ho=(n,e)=>fd(n,e),ud=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,dd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,hd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,pd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var md=mn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Ho("strong",{...dn(this.options.HTMLAttributes,n),children:Ho("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:ud,type:this.type}),Bt({find:hd,type:this.type})]},addPasteRules(){return[zt({find:dd,type:this.type}),zt({find:pd,type:this.type})]}});const gd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,yd=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,bd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,kd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var xd=mn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",dn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:gd,type:this.type}),Bt({find:bd,type:this.type})]},addPasteRules(){return[zt({find:yd,type:this.type}),zt({find:kd,type:this.type})]}});const Sd=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},Md=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var Cd=mn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",dn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:Sd,type:this.type})]},addPasteRules(){return[zt({find:Md,type:this.type})]}}),gn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new qo(e):z.empty};var qo=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=gn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=gn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new qo([]);var wd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Td=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ue(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ue(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fNd&&(l=Od(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new bt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new ue(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new ue(p,m,g))}else r.push(new ue(p))},i);let c=[];for(let d=t;dTd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ue(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Od(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ue{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ue(t.getMap().invert(),t,this.selection)}}}class Re{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Nd=20;function Ed(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta(Id)&&(n=new Re(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new Re(n.done.addTransform(t,void 0,r,yn(e)),n.undone,Ko(t.mapping.maps),n.prevTime,n.prevComposition):new Re(n.done,n.undone.addTransform(t,void 0,r,yn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Dd(t,n.prevRanges)),c=o?Mr(n.prevRanges,t.mapping):Ko(t.mapping.maps);return new Re(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,yn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Re(n.done.rebased(t,s),n.undone.rebased(t,s),Mr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Re(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Mr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Dd(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ko(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Mr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Ad(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Go=Uo(!1,!0),wr=Uo(!0,!0);function Rd(n,e){for(const t of n){const r=t.history?.get(e);r!==void 0?(t.ackedHtml=r,t.seq===e&&(t.acked=!0)):t.seq===e&&(t.ackedHtml=t.html,t.acked=!0)}}function Pd(n){const e=[...n];return e.some(t=>!t.acked)?e.sort((t,r)=>t.start-r.start).map(({start:t,end:r,html:i,ackedHtml:s})=>({start:t,end:r,html:i,...s!==void 0?{ackedHtml:s}:{}})):null}const Xe="data-bd-src",Bd=mn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),bn=Ou([ad.extend({content:"inline*"}),cd,md,xd,Cd,Bd]),zd=he.fromSchema(bn),Fd=Ve.fromSchema(bn),Ld={preserveWhitespace:"full"};function Yo(n){return zd.parse(n,Ld)}function Xo(n){const e=document.createElement("div");return e.appendChild(Fd.serializeFragment(n.content)),e.innerHTML}function Vd(n){try{return Xo(Yo(n))===n.innerHTML}catch{return!1}}function Qo(n){const e=n.getAttribute(Xe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const kn=n=>parent.postMessage(n,"*"),Tr=new WeakMap;function Zo(n){let e=Tr.get(n);return e===void 0&&(e=Vd(n),Tr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let Y=null,Pe=null,de=null,Or="",Qe=!1,$d=0,xn=null;const Ft=new Map;function el(){return Y?Xo(Y.state.doc):null}function Sn(){if(!Pe||!de)return;const n=el();if(n===null||n===Or)return;Or=n;const e=++$d,t=de.start+","+de.end,r=Ft.get(t),i=r?.history??new Map;i.set(e,n),Ft.set(t,{start:de.start,end:de.end,html:n,seq:e,acked:!1,ackedHtml:r?.ackedHtml,history:i}),kn({type:"bd-edit:patch",seq:e,start:de.start,end:de.end,html:n})}function Lt(){if(!Y)return;Sn();const n=Pe,e=el();Y.destroy(),Y=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Tr.delete(n),n.removeAttribute("data-bd-edit")),Pe=null,de=null}function Wd(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function jd(n,e,t){if(Pe===n)return;Lt();const r=Qo(n);if(!r)return;Pe=n,de=r,Or=n.innerHTML,n.setAttribute("data-bd-editing","");const i=st.create({doc:Yo(n),plugins:[vd(),ho({"Mod-b":Gi(bn.marks.bold),"Mod-i":Gi(bn.marks.italic),"Mod-z":Go,"Mod-y":wr,"Shift-Mod-z":wr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Lt(),!0)}),ho(xa)]});Y=new oo({mount:n},{state:i,editable:()=>!Qe,dispatchTransaction(s){Qe&&s.docChanged||(Y.updateState(Y.state.apply(s)),s.docChanged&&Sn())}}),Y.focus(),e!==void 0&&t!==void 0&&Wd(Y,e,t)}function tl(n){const e=n?.closest?.(`[${Xe}]`);return e instanceof HTMLElement?e:null}document.addEventListener("click",n=>{if(Qe)return;const e=tl(n.target);if(!e){Lt();return}Zo(e)&&jd(e,n.clientX,n.clientY)},!0),document.addEventListener("mouseover",n=>{const e=tl(n.target);e&&Zo(e)},!0),new MutationObserver(()=>{Pe&&!Pe.isConnected&&(kn({type:"bd-edit:clobbered"}),Y?.destroy(),Y=null,Pe=null,de=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const nl=document.createElement("style");nl.textContent=` - [${Xe}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } - [${Xe}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } - [${Xe}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } - [${Xe}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } -`,document.head.appendChild(nl);const rl=document.currentScript??document.querySelector("script[data-src-hash]"),Jd=rl?.dataset.srcHash??"",Hd=Number(rl?.dataset.srcLen??"-1");kn({type:"bd-edit:ready",hash:Jd,len:Hd,ranges:[...document.querySelectorAll(`[${Xe}]`)].map(n=>Qo(n)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","");function il(){if(!xn)return;const n=Pd(Ft.values());if(n!==null){for(const e of Ft.values())e.acked=!0;xn.postMessage({type:"bd-edit:exit",patches:n})}}window.addEventListener("beforeunload",()=>{Lt(),il()}),window.addEventListener("pagehide",n=>{n.persisted?Sn():Lt(),il()}),window.addEventListener("message",n=>{if(n.source!==window.parent)return;const e=n.data;if(e){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){Rd(Ft.values(),e.seq);return}if(e.type==="bd-edit:port"&&n.ports[0]){xn?.close(),xn=n.ports[0],document.documentElement.setAttribute("data-bd-exit","ready");return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){Sn(),e.lock===!0&&(Qe=!0,Y?.setProps({editable:()=>!Qe})),kn({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Qe=!1,Y?.setProps({editable:()=>!Qe}))}})})(); +`):""}),bd=Ho.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});const qo=new WeakSet,Ko=new WeakSet;function Ge(n){const e=n;return qo.add(e),e}function Mr(n){return Array.isArray(n)&&qo.has(n)}function _o(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Ko.has(e)&&!Mr(e)?_o(e):[e])}function kd(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!Mr(i)&&!Ko.has(i)?Ge(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(Mr(t))return Ge([n,r,t]);if(t.length===0)return Ge([n,r]);const i=_o(t);return i.length===0?Ge([n,r]):Ge([n,r,...i])}return t!=null?Ge([n,r,t]):Ge([n,r])}const Uo=(n,e)=>kd(n,e),xd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Sd=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Md=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Cd=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;var wd=bn.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Uo("strong",{...mn(this.options.HTMLAttributes,n),children:Uo("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[zt({find:xd,type:this.type}),zt({find:Md,type:this.type})]},addPasteRules(){return[Ft({find:Sd,type:this.type}),Ft({find:Cd,type:this.type})]}});const Td=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Od=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Nd=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Ed=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;var Dd=bn.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",mn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[zt({find:Td,type:this.type}),zt({find:Nd,type:this.type})]},addPasteRules(){return[Ft({find:Od,type:this.type}),Ft({find:Ed,type:this.type})]}});const Ad=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},Id=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};var vd=bn.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",mn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[zt({find:Ad,type:this.type})]},addPasteRules(){return[Ft({find:Id,type:this.type})]}}),kn=200,z=function(){};z.prototype.append=function(e){return e.length?(e=z.from(e),!this.length&&e||e.length=t?z.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))},z.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},z.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)},z.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i},z.from=function(e){return e instanceof z?e:e&&e.length?new Go(e):z.empty};var Go=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=kn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=kn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(z);z.empty=new Go([]);var Rd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(z);const Pd=500;class le{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,d)=>{if(!u.step){i||(i=this.remapping(r,d+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new de(u.map));let h=u.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new de(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new le(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fzd&&(l=Bd(l,c),o-=c),new le(l.append(s),o)}remapping(e,t){let r=new kt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new le(this.items.append(e.map(t=>new de(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(s.slice(a+1,h));g&&l++,r.push(new de(p,m,g))}else r.push(new de(p))},i);let c=[];for(let d=t;dPd&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new de(c.invert(),a,f),d,h=i.length-1;(d=i.length&&i[h].merge(u))?i[h]=d:i.push(u)}}else o.map&&r--},this.items.length,0),new le(z.from(i.reverse()),s)}}le.empty=new le(z.empty,0);function Bd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class de{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new de(t.getMap().invert(),t,this.selection)}}}class Pe{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const zd=20;function Fd(n,e,t,r){let i=t.getMeta(Ye),s;if(i)return i.historyState;t.getMeta($d)&&(n=new Pe(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Ye))return o.getMeta(Ye).redo?new Pe(n.done.addTransform(t,void 0,r,xn(e)),n.undone,Yo(t.mapping.maps),n.prevTime,n.prevComposition):new Pe(n.done,n.undone.addTransform(t,void 0,r,xn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Ld(t,n.prevRanges)),c=o?Cr(n.prevRanges,t.mapping):Yo(t.mapping.maps);return new Pe(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,xn(e)),le.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Pe(n.done.rebased(t,s),n.undone.rebased(t,s),Cr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Pe(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Cr(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Ld(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Yo(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Cr(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ye.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Vd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const Zo=Qo(!1,!0),Tr=Qo(!0,!0);function jd(n,e){for(const t of n){const r=t.history?.get(e);r!==void 0?(t.ackedHtml=r,t.seq===e&&(t.acked=!0)):t.seq===e&&(t.ackedHtml=t.html,t.acked=!0)}}function Jd(n){const e=[...n];return e.some(t=>!t.acked)?e.sort((t,r)=>t.start-r.start).map(({start:t,end:r,html:i,ackedHtml:s})=>({start:t,end:r,html:i,...s!==void 0?{ackedHtml:s}:{}})):null}const Hd=window.MessageChannel,el=MessagePort.prototype.postMessage,qd=MessagePort.prototype.close,Kd=MessagePort.prototype.start,Xe=EventTarget.prototype.addEventListener,tl=Object.getOwnPropertyDescriptor(new Event("x"),"isTrusted").get,_d=Object.getOwnPropertyDescriptor(MessageEvent.prototype,"data").get,Ud=Object.getOwnPropertyDescriptor(MessageEvent.prototype,"ports").get,Gd=Element.prototype.getAttribute,Yd=Element.prototype.closest,Xd=window.Document.prototype.querySelectorAll,Qd=window.setTimeout.bind(window),Zd=window.clearTimeout.bind(window),eh=window.parent.postMessage.bind(window.parent),nl=document.currentScript,th=nl?.dataset.srcHash??"",nh=Number(nl?.dataset.srcLen??"-1"),rl=new Hd,Or=rl.port1,Lt=n=>{el.call(Or,n)};let Nr=!1,Er=!1,il;const sl=(n=0)=>{Nr=!0,Zd(il),il=Qd(()=>{Nr=!1},n)};for(const n of["keydown","beforeinput","input","textInput","compositionstart","compositionupdate","compositionend","paste","cut","drop"])Xe.call(document,n,e=>{if(tl.call(e)){if(n==="compositionstart")Er=!0;else if(n==="compositionend"){Er=!1,sl(60);return}sl(0)}},!0);const Qe="data-bd-src",rh=bn.create({name:"rawInline",excludes:"",inclusive:!1,addAttributes(){return{tag:{default:"span"},attrs:{default:{}}}},parseHTML(){return[{tag:"a, span, sup, sub, small, abbr, mark, u, s, del, ins, cite, q, var, samp, kbd, time, data, bdi, bdo, big, strike, tt, font, label, ruby, rt, rp, dfn",priority:10,getAttrs:n=>({tag:n.tagName.toLowerCase(),attrs:Object.fromEntries([...n.attributes].map(e=>[e.name,e.value]))})}]},renderHTML({mark:n}){return[n.attrs.tag,n.attrs.attrs,0]}}),Sn=Bu([yd.extend({content:"inline*"}),bd,wd,Dd,vd,rh]),ih=he.fromSchema(Sn),sh=Ve.fromSchema(Sn),oh={preserveWhitespace:"full"};function ol(n){return ih.parse(n,oh)}function ll(n){const e=document.createElement("div");return e.appendChild(sh.serializeFragment(n.content)),e.innerHTML}function lh(n){try{return ll(ol(n))===n.innerHTML}catch{return!1}}function al(n){const e=Gd.call(n,Qe);if(!e)return null;const[t,r]=e.split(","),i=Number(t),s=Number(r);return!Number.isInteger(i)||!Number.isInteger(s)||i>s?null:{start:i,end:s}}const Dr=new WeakMap;function cl(n){let e=Dr.get(n);return e===void 0&&(e=lh(n),Dr.set(n,e),n.setAttribute("data-bd-edit",e?"yes":"no")),e}let q=null,Se=null,ae=null,Ar="",Ze=!1,ah=0,Vt=null;const $t=new Map;function fl(){return q?ll(q.state.doc):null}function Mn(){if(!Se||!ae)return;const n=fl();if(n===null||n===Ar)return;Ar=n;const e=++ah,t=ae.start+","+ae.end,r=$t.get(t),i=r?.history??new Map;i.set(e,n),$t.set(t,{start:ae.start,end:ae.end,html:n,seq:e,acked:!1,ackedHtml:r?.ackedHtml,history:i}),Lt({type:"bd-edit:patch",seq:e,start:ae.start,end:ae.end,html:n})}function Wt(){if(!q)return;Mn();const n=Se,e=fl();q.destroy(),q=null,n&&(e!==null&&(n.innerHTML=e),n.removeAttribute("data-bd-editing"),Dr.delete(n),n.removeAttribute("data-bd-edit")),Se=null,ae=null}function ch(n,e,t){const r=n.posAtCoords({left:e,top:t});if(!r)return;const i=S.near(n.state.doc.resolve(r.pos));n.dispatch(n.state.tr.setSelection(i))}function fh(n,e,t){if(Se===n)return;Wt();const r=al(n);if(!r)return;Se=n,ae=r,Ar=n.innerHTML,n.setAttribute("data-bd-editing","");const i=ot.create({doc:ol(n),plugins:[Wd(),yo({"Mod-b":Zi(Sn.marks.bold),"Mod-i":Zi(Sn.marks.italic),"Mod-z":Zo,"Mod-y":Tr,"Shift-Mod-z":Tr,Enter:()=>!0,"Shift-Enter":()=>!0,Escape:()=>(Wt(),!0)}),yo(Da)]});q=new fo({mount:n},{state:i,editable:()=>!Ze,dispatchTransaction(s){if(!(Ze&&s.docChanged)){if(s.docChanged&&!Nr&&!Er){Lt({type:"bd-edit:clobbered"}),q?.destroy(),q=null,Se=null,ae=null;return}q.updateState(q.state.apply(s)),s.docChanged&&Mn()}}}),q.focus(),e!==void 0&&t!==void 0&&ch(q,e,t)}function ul(n){const e=n instanceof Element?Yd.call(n,`[${Qe}]`):null;return e instanceof HTMLElement?e:null}Xe.call(document,"click",n=>{if(!tl.call(n))return;const e=n;if(Ze)return;const t=ul(e.target);if(!t){Wt();return}cl(t)&&fh(t,e.clientX,e.clientY)},!0),Xe.call(document,"mouseover",n=>{const e=ul(n.target);e&&cl(e)},!0);function dl(){new MutationObserver(()=>{Se&&!Se.isConnected&&(Lt({type:"bd-edit:clobbered"}),q?.destroy(),q=null,Se=null,ae=null)}).observe(document.documentElement,{childList:!0,subtree:!0});const n=document.createElement("style");n.textContent=` + [${Qe}][data-bd-edit="yes"]:hover { outline: 1px dashed rgba(99,102,241,.7); outline-offset: 2px; cursor: text; } + [${Qe}][data-bd-edit="no"]:hover { outline: 1px dotted rgba(120,120,120,.5); outline-offset: 2px; cursor: not-allowed; } + [${Qe}][data-bd-editing] { outline: 2px solid rgba(99,102,241,.9); outline-offset: 2px; } + [${Qe}][data-bd-editing]:focus { outline: 2px solid rgba(99,102,241,.9); } +`,(document.head??document.documentElement).appendChild(n),Lt({type:"bd-edit:ready",hash:th,len:nh,ranges:[...Xd.call(document,`[${Qe}]`)].map(e=>al(e)).filter(Boolean)}),document.documentElement.setAttribute("data-bd-ready","")}function hl(){if(!Vt)return;const n=Jd($t.values());if(n!==null){for(const e of $t.values())e.acked=!0,e.ackedHtml=e.html;el.call(Vt,{type:"bd-edit:exit",patches:n})}}Xe.call(window,"beforeunload",()=>{Wt(),hl()}),Xe.call(window,"pagehide",n=>{n.persisted?Mn():Wt(),hl()}),Xe.call(Or,"message",n=>{const e=_d.call(n);if(!(!e||typeof e!="object")){if(e.type==="bd-edit:ack"&&typeof e.seq=="number"){jd($t.values(),e.seq);return}if(e.type==="bd-edit:port"){const t=Ud.call(n)[0];if(!t)return;Vt&&qd.call(Vt),Vt=t,document.documentElement.setAttribute("data-bd-exit","ready");return}if(e.type==="bd-edit:flush"&&typeof e.id=="number"){Mn(),e.lock===!0&&(Ze=!0,q?.setProps({editable:()=>!Ze})),Lt({type:"bd-edit:flushed",id:e.id});return}e.type==="bd-edit:unlock"&&(Ze=!1,q?.setProps({editable:()=>!Ze}))}}),Kd.call(Or),document.readyState!=="loading"?dl():Xe.call(document,"DOMContentLoaded",dl,{once:!0}),eh({type:"bd-edit:hello"},"*",[rl.port2])})(); From 50bfcccfd2db5cd66488d0eebd2d04a8218a1d5f Mon Sep 17 00:00:00 2001 From: Byeonghoon Yoo Date: Thu, 12 Nov 2026 03:22:50 +0900 Subject: [PATCH 22/34] fix(webapp): lock VisualEdit stamped ranges and block script writes to open editor --- CHANGELOG.md | 1 + architecture/webapp-frontend.md | 1 + architecture/webapp-server.md | 4 +- .../webapp/frontend/e2e/inline-edit.spec.ts | 145 ++++++ .../frontend/src/components/VisualEdit.tsx | 27 +- internal/webapp/frontend/src/inline-edit.ts | 429 +++++++++++++++--- internal/webapp/htmledit.go | 15 +- internal/webapp/htmledit_test.go | 34 ++ ...{Editor-Cp12kr6p.js => Editor-DpIY2BsF.js} | 2 +- .../static/assets/VisualEdit-B9yuu_mv.js | 1 + .../static/assets/VisualEdit-DbM9aXAX.js | 1 - .../{index-Dgs5VYVU.js => index-VVZsewL1.js} | 4 +- ...ile-f4YTnm99.js => sharedfile-BHVT_e-J.js} | 2 +- internal/webapp/static/index.html | 2 +- internal/webapp/static/inline-edit.js | 34 +- 15 files changed, 614 insertions(+), 88 deletions(-) rename internal/webapp/static/assets/{Editor-Cp12kr6p.js => Editor-DpIY2BsF.js} (99%) create mode 100644 internal/webapp/static/assets/VisualEdit-B9yuu_mv.js delete mode 100644 internal/webapp/static/assets/VisualEdit-DbM9aXAX.js rename internal/webapp/static/assets/{index-Dgs5VYVU.js => index-VVZsewL1.js} (99%) rename internal/webapp/static/assets/{sharedfile-f4YTnm99.js => sharedfile-BHVT_e-J.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index f158398a..0b3f1abc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ bytes, so do not run v0.18.9 and v0.18.10 side by side on one storage root. - **Browser co-editing keeps edits through slow joins, saves and most tab closes.** When the room has not answered after 2.5 seconds, the editor mounts a staging buffer (`onStalled`) and checkpoints it into the room as text over `ycollab/sync`, then merges it three ways when the socket connects. Previously the editor gave up on the room after 8 seconds and saved its own copy for the rest of the session. `save()` is single-flight. `Mod-s` saves immediately, and Done saves every edit, including any typed during the save, before leaving, and stays in the editor if the save fails or opens a shrink confirmation. `pagehide` sends pending edits with `keepalive` when the encoded HTTP request body is at most 60,000 bytes (`KEEPALIVE_MAX_BYTES`, below the browser's 64 KiB in-flight `keepalive` limit); a larger body goes out as a regular `fetch`, which the browser may cancel during unload, and delivery is never guaranteed once the browser tears the page down. `pageshow` resets the exit-send guard, so a page restored from the back/forward cache can flush again on a later close. Room snapshots that arrive after a save are recognized as the room's own history (`seenRoomTexts`), which stops false `#peer-wrote` banners when eight or more people edit one meeting note. `VisualEdit` applies an element edit as the smallest splice inside that element. - **`VisualEdit` flushes unacknowledged iframe edits through a same-origin exit worker when the tab closes.** The editing iframe stays `sandbox="allow-scripts"` and is never given a session, token or URL. `VisualEdit` starts a dedicated Web Worker on the app's origin (`editexit.worker.ts`), keeps it current with the rendered source, the anchored ranges and what the file and document hold after every save, and hands the iframe only one end of a `MessageChannel` (`bd-edit:port`). The app acknowledges each numbered patch it applies (`bd-edit:ack`); when the iframe unloads with an unacknowledged patch, it posts its edited spans to the worker (`bd-edit:exit`). This exit save is best-effort and runs only once the worker has started and been armed with the anchored render. The worker splices only anchored, script-free spans onto the render, merges the result three ways with the current document, and saves it with the app's own cookie: `POST /api/p//ycollab/sync` on a hub or `bdrive desktop`, or `PUT upload/content` on the latest `If-Match` in a plain folder, so it also works after earlier auto-saves. A same-word clash parks a conflict copy, an unconfirmed sharp shrink is not sent, and delivery is still subject to the browser's teardown limits (`keepalive` up to 60,000 bytes). - **The `VisualEdit` iframe talks to the app only over a sealed channel, and the exit worker re-arms after a back/forward-cache restore.** The editable view now injects `/inline-edit.js` synchronously before any script in the synced HTML file, so it captures the browser's own `MessageChannel`, `MessagePort` methods and `Event.isTrusted` before page code can replace them. It opens a private `MessageChannel` and sends `bd-edit:hello` with one port to the app once; every later editor message (ready, patch, ack, port, flush, unlock) uses that channel instead of `window.postMessage`, and an editor opens or changes only on a trusted user event. When a page comes back from the back/forward cache, `VisualEdit` sends the exit worker `rearm` with a fresh port, so an unacknowledged edit made after the restore is still saved when the tab closes again. +- **`VisualEdit` edits only the ranges the hub stamped, and page scripts cannot write into an open editor.** The bootstrap tag now also carries `data-src-ranges`, the stamped `start,end` list the hub measured. `inline-edit.js` reads and removes its `data-src-*` attributes at load, locks `data-bd-src` against page-script writes, and binds each stamped element once, refusing a duplicate or unstamped range. A page script that changes the element being edited (its own key or input listener, `execCommand`, any DOM write) is refused, and the frame reports `bd-edit:clobbered` instead of saving. Before anchoring a range or arming the exit worker, `VisualEdit` checks that the element's initial HTML matches the source slice, comparing both as an inert `